dongping1922 2011-11-20 00:25
浏览 44
已采纳

从superglobals中删除数组($ _GET,$ _POST ...)

In PHP it's possible to have arrays in $_GET, $_POST, $_COOKIE, $_FILES and $_REQUEST according to PHP documentation. The problem is that those come from user and I might get them instead of strings. For example, consider following snippet.

<?php
if (isset($_GET['hello'])) {
    echo 'Hello, ', htmlspecialchars($_GET['hello']), '.';
}
else {
    echo '<form action="?"><input name="hello"><input type="submit"></form>';
}

Looks OK? Well, as long you will not work will the URL it will work correctly. The problem is that hacker can try making $_GET['hello'] an array. If URL string looks like ?hello[]=something PHP will return error message

Warning: htmlspecialchars() expects parameter 1 to be string, array given in FILE on line 3

OK, who would enable in HTML errors in the production site (the other thing is error log...). But integers also are a problem - PHP is dynamically typed language, so it would accept easily code like '2' + 2. While yes, you can use (int) I have some old code which doesn't do that. If string comes from $_GET or $_POST it could be also array. Something like array('2') + 2 would cause fatal error of PHP.

Fatal error: Unsupported operand types in FILE on line 3

Now it's something that isn't acceptable because it would stop the script. I don't need arrays in those variables, but they annoy me. Is there any simple snippet which would remove arrays from those special variables. If I really would want an array, I could make copy of it before running the snippet.

  • 写回答

3条回答 默认 最新

  • dongwu9647 2011-11-20 00:34
    关注

    I would check if it was a string before using it in a string context.

    $name = (isset($_GET['name']) && is_string($_GET['name'])) ? $_GET['name'] : 'Unknown!';
    

    Or:

    if(isset($_GET['name']) && is_string($_GET['name']) {
        //do stuff
    }
    

    If you wanted to remove all arrays though:

    foreach($_GET as $key => $val) {
        if(is_array($val)) {
            unset($_GET[$key]);
        }
    }
    

    Oops look like Sudhir already beat me to that part, but already had it typed... :)

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部