Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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! :)


1 Answers

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.
like image 137
Pascal MARTIN Avatar answered Sep 08 '25 10:09

Pascal MARTIN