initphp / escaper
InitPHP Escaper 类
1.0
2022-03-16 07:05 UTC
Requires
- php: >=7.4
- ext-ctype: *
README
安全且安全地转义HTML、HTML属性、JavaScript、CSS和URL。
要求
- PHP 7.4或更高版本
- PHP CType 扩展
- PHP MB_String 或 Iconv 扩展
安装
composer require initphp/escaper
使用
\InitPHP\Escaper\Esc::esc() :
public static function esc(string[]|string $data, string $context = 'html', ?string $encoding = null): array|string;
$data: 要清除的内容。$context: 用于清理的方法。如果值不是以下之一; 抛出Exception。htmljscssurlattr
$encoding: 如果未指定要使用的字符集或NULL; 默认使用UTF-8。
html 转义示例
<?php require_once "vendor/autoload.php"; use \InitPHP\Escaper\Esc; $input = '<script>alert("initphp")</script>'; ?> <!DOCTYPE html> <html> <head> <title>Encodings set correctly!</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <?php echo Esc::esc($input, 'html'); ?> </body></html>
attr 转义示例
<?php require_once "../vendor/autoload.php"; use \InitPHP\Escaper\Esc; $input = 'faketitle onmouseover=alert(/InitPHP!/);'; ?> <!DOCTYPE html> <html> <head> <title>Quoteless Attribute</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <div> <?php // <span title=faketitle onmouseover=alert(/InitPHP!/);> ?> <span title=<?php echo Esc::esc($input, 'attr'); ?>> Hello World </span> </div> </body> </html>
Js 转义示例
<?php require_once "../vendor/autoload.php"; use InitPHP\Escaper\Esc; $input = 'bar"; alert("Hello!"); var xss="true'; ?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Escaped Entities</title> <meta charset="UTF-8"/> <script type="text/javascript"> <?php /** * var foo = bar\x26quot\x3B\x3B\x20alert\x28\x26quot\x3BHello\x21\x26quot\x3B\x29\x3B\x20var\x20xss\x3D\x26quot\x3Btrue; */ ?> var foo = <?php echo Esc::esc($input, 'js'); ?>; </script> </head> <body> <p>Hello World</p> </body> </html>
css 转义示例
<?php require_once "../vendor/autoload.php"; use \InitPHP\Escaper\Esc; $input = <<<INPUT body { background-image: url('http://example.com/bar.jpg?</style><script>alert(13)</script>'); } INPUT; ?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Escaped CSS</title> <meta charset="UTF-8"/> <style> <?php /** * body\20 \7B \D \A \20 \20 \20 \20 background\2D image\3A \20 url\28 \27 http\3A \2F \2F example\2E com\2F bar\2E jpg\3F \3C \2F style\3E \3C script\3E alert\28 13\29 \3C \2F script\3E \27 \29 \3B \D \A \7D */ echo Esc::esc($input, 'css'); ?> </style> </head> <body> <p>User controlled CSS needs to be properly escaped!</p> </body> </html>
url 转义示例
<?php require_once "../vendor/autoload.php"; use \InitPHP\Escaper\Esc; $query = <<<QUERY " onmouseover="alert('hello') QUERY; ?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Unescaped URL</title> <meta charset="UTF-8"/> </head> <body> <?php // http://example.com/?query=%22%20onmouseover%3D%22alert%28%27hello%27%29 ?> <a href="http://example.com/?query=<?php echo Esc::esc($query, 'url'); ?>">Click</a> </body> </html>
致谢
许可证
版权所有 © 2022 MIT许可证