Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to write to $_POST?

Tags:

php

If this is file_1.php

<?php

  $_POST["test_message"] = "Hello, world";    

  header("Location: http://localhost/file_2.php");
?>

and this is file_2.php

<html>
<head>
</head>
<body>

<?php

  if (!(isset($_POST["test_message"])))
    echo "Test message is not set";
  else
    echo $_POST["test_message"];
?>

</body>
</html>

the output is Test message is not set

Which makes me wonder if one can even write to $_POST and, having wondered that, I wonder if it is bad practice to do so. Should I just let forms with submit buttons and method=post write to $_POST for me, or is it legitimate to write to $_POST to pass data between files?

like image 377
Mawg says reinstate Monica Avatar asked Jul 13 '10 08:07

Mawg says reinstate Monica


2 Answers

You want to use $_SESSION instead.

$_POST is for information that has been POSTed to the current page and doesn't maintain state between page loads, it will only be populated if you actually post something to the second file when redirecting. If you were to include the second file, rather than redirecting via a header, then what you've done would work since the $_POST variable would still be set.

$_SESSION will maintain state between pages, so will accomplish what you want when redirecting.

To use $_SESSION properly, you'll need to call session_start(); first to begin the session. There's more info in the PHP manual.

like image 86
Rich Adams Avatar answered Nov 16 '22 03:11

Rich Adams


Generally spoken $_POST is just a regular PHP array that's populated with the POST data on each request. It's therefore possible to write your own values into $_POST.

But...

1) Your code doesn't work as your header() call in file_1.php instructs the browser to issue a new request which results in a completely new (and empty) $_POST array in file_2.php. The array will be empty because you didn't post anything to file_2.php.

2) In my opinion it's indeed bad practice... Getting data from $_POST (or $_GET or $_REQUEST) indicates that you're retrieving user data which should be handled with extreme caution (filtering, sanitizing, escaping,...). Writing internal data into these arrays will mix up internal and external data leading to confusion and probable security holes.

like image 39
Stefan Gehrig Avatar answered Nov 16 '22 01:11

Stefan Gehrig