开发者

Use $_POST["x"] directly or to copy to a local variable and then use?

Consider the following pair of snippets, both do the same essentially.

<html>
<body>
    <?php
    if(isset($_POST["firstName"]) && isset($_POST["lastName"])){
    //I'm copying the POST variable to a local one.
    $firstName = $_POST["firstName"];
    $lastName = $_POST["lastName"];     
    echo "<h1>Thank you for taking the census!</h1>";
    echo "On behalf of Sergio's Emporium, we name you: " . $firstName . $lastName . ", conquerer of worlds!";
    //Here I'm just pulling it from the POST info.
    echo "I think that's fitting since you're a " . $_POST["item"];
    }
    else {      
    echo "You didn't write in the necesarry information.";      
    }
    ?>
</body> 
</html>

Which is better to use (from a security standpoint) and which one is encouraged to be used by standards.

Since I'm new开发者_高级运维 to PHP this is something that's yanking my chain. Thanks guys! :)


I would say none of those two solutions change anything from a security point of view, as long as you properly :

  • Filter / validate input
  • and Escape output.

Here, as you are outputting some HTML, it might be useful to escape your data with htmlspecialchars, for instance ;-)


To facilitate that, some people like to consider that :

  • $_POST contains the raw input
  • and some local variable are used to contain the filtered input -- i.e. that you can use "safely" in the rest of your script.


I believe you should because you should do some sort of santizing to the post vars then assign to a local var


According to the performance guru's at google, PHP variable copying should be avoided as much as possible: http://code.google.com/speed/articles/optimizing-php.html

Personally, I like it when I can clearly see at the top of the script which variables the script expects from the request so i used to write copies of the $_REQUEST and friends in the top:

<?php
    $req_param1 = $_REQUEST['param1'];
    ...
    if (isset($req_param1)) {
        ...
    }
    ...

Nowadays, I do it differerntly. I typically use define() or in a class, const to define the names of the parameters I expect to get from the request. I can then search for those in the code to see where I actually refeernce them:

define('REQ_PARAM1', 'param1');
...
function foo(){ 
    if (isset($_REQUEST[REQ_PARAM1])){
    ...
    }
    ...
}

example with class:

class MyClass {
    const REQ_PARAM1 = "param1";
    ...
    function foo(){
        if (isset($_REQUEST[MyClass::REQ_PARAM1])){
            ...
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜