Search code examples
phphtmlfunctionposthttp-post

PHP function for checking POST security and storing variable


I am looking for information on how to make a function to make this easier. I know there is an easier way then writing the posted variable I want into PHP.

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  $name =   isset($_POST['name']) ? htmlentities($_POST['name']) : '';
  $email =  isset($_POST['email']) ? htmlentities($_POST['email']) : '';
  $interest = isset($_POST['interest']) ? htmlentities($_POST['interest']) : '';
  $checkbox = isset($_POST['checkbox']) ? htmlentities($_POST['checkbox']) : '';

So far I came up with a function like this:

function req_post($n){
  '$'$n = isset($_POST["$n"]) ? htmlentities($_POST["$n"]) : '';
}

I know I am doing this wrong, kinda new to PHP. Any help would be greatly appreciated. Thank you in advance.


Solution

  • It might seem tempting to make functions like this, seemingly removing duplicate code etc but it always ends up biting you in the end.

    Your code shows you escaping all the POST data ready for the next environment which will be a html page.

    So, if you are outputting $email only to a html page, its seemingly worth it.

    BUT if you are outputting to both a webpage "Thank you $email" and also storing this to a db then you have not escaped it for the db, so you risk sql injection attacks.

    Until you know better, you are best off leaving $_POST['email'] as it is and escaping it as you output it.

    echo htmlentities($_POST['email']);
    

    OR

    $query = 'update names set email = "'.mysql_real_escape_string($_POST['email']).'" where ID =1';
    

    OR PREFERABLY using PDO/Mysqli and prepared statements, which do this escaping for you.

    htmlentities is a method of escaping for html output mysql_real_escape_string is a method of escaping for mysql databases (though outmoded, as has been said by me and others).

    The fact is that if you come across a var like $email you will be left thinking, now hang on, is this escaped ready for the next environment? Where did it come from?

    When you see $_POST['email'] you know you are dealing with potentially very dirty and dangerous data, and you handle it with care.

    You would be far better off spending your time doing some filtering and maybe deciding that if $_POST['email'] (or name or whatever) is indeed empty, what to do next -- relocate the user, show a warning to the user and so on.

    The mnemonic FIEO provides the basic rule, Filter Input, Escape Output and you can save yourself a lot of future pain by spending a couple of hours researching it.