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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With