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
$_SESSIONinstead.$_POSTis 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$_POSTvariable would still be set.$_SESSIONwill maintain state between pages, so will accomplish what you want when redirecting.To use
$_SESSIONproperly, you’ll need to callsession_start();first to begin the session. There’s more info in the PHP manual.