doz97171 2014-07-21 08:09
浏览 197
已采纳

htmlspecialchars()足够安全吗?

The user input is like this

$user_input = htmlspecialchars($_GET['$user_input']);

According to PHP.net:

'&' (ampersand) becomes '&'
'"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
"'" (single quote) becomes ''' (or ') only when ENT_QUOTES is set.
'<' (less than) becomes '&lt;'
'>' (greater than) becomes '&gt;'

But what about $? For example the code is like this:

echo "Some cool text $user_input";

Now lets say user input is $secretCode so:$_GET['$user_input'] = "$secretCode"; Will the code then not echo the $secretCode?

Also what about this. Lets assume the code is like this:

$html = <<<EOF <head>.... EOF;

What if the input is $_GET['$user_input'] = "EOF;"; Won't this quit the string?

  • 写回答

3条回答 默认 最新

  • dongshadu4498 2014-07-21 08:19
    关注

    You're assuming a level interpretation that doesn't exist. If you write string literals like this:

    $foo = 'bar';
    $baz = "Hello $foo";
    

    Then yes, $foo will be interpolated into the string. That is because it is explicitly written as a string literal in PHP source code.

    On the other hand:

    $foo = 'bar';
    $baz = $_GET['var'];
    

    Under no circumstances whatsoever will anything be interpolated here. Nor here:

    $foo = <<<EOL
        $_GET[var]
    EOL;
    

    $_GET['var'] can contain whatever it wants to, it is of no concern. PHP does not recursively evaluate all values over and over to see if there may be something that can be interpolated. There is no security issue here.

    To provoke any of this recursive behaviour, you'd have to explicitly construct PHP source code as a string and then explicitly evaluate it:

    $code = <<<EOL
        $foo = 'bar';
        echo "Hello $_GET[var]";
    EOL;
    
    // $code is now, say:
    // $foo = 'bar';
    // echo "Hello $foo";
    
    eval($code);
    

    Unless you do something like this (and please, never use eval), nothing will happen.

    For embedding arbitrary text inside of HTML, htmlspecialchars is fine to escape characters which have a special meaning in HTML; yes, it's secure.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值