如何从其他页面访问包含$_POST的变量?附自提交表单场景
Hey there! Let's figure out how to access those $_POST variables from another page—since by default, $_POST is only available on the page that directly receives the form submission. Here are the most practical methods tailored to your setup:
Sessions let you store data across multiple pages for a single user session. This is perfect if you just need to pass the data temporarily after form submission.
Step 1: Modify your existing form-handling page
Add session_start() at the very top (before any HTML output), then save the valid $_POST values to the $_SESSION array:
<?php session_start(); // Must be called before any HTML is printed $errormessage = ""; if($_SERVER["REQUEST_METHOD"]==='POST') { if(empty($_POST["field1"])){ $errormessage = "field1 is required!"; } else { // Save the valid value to session $_SESSION["field1"] = $_POST["field1"]; // Optional: Redirect to the other page immediately header("Location: another_page.php"); exit; // Always exit after a header redirect } } ?> <!-- Your existing HTML form here --> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post"> <!-- Form fields go here --> <input type="text" name="field1"> <button type="submit">Submit</button> </form> <!-- Error message display --> <?php if(!empty($errormessage)) { echo "<p>$errormessage</p>"; } ?>
Step 2: Retrieve the data on the other page
On another_page.php, start the session again and access the stored value:
<?php session_start(); // Check if the session variable exists before using it if(isset($_SESSION["field1"])){ $field1_value = htmlspecialchars($_SESSION["field1"]); // Sanitize for output echo "Value of field1: $field1_value"; // Optional: Clear the session variable once you're done with it // unset($_SESSION["field1"]); } else { echo "No valid field1 value found in session!"; } ?>
If you don't need to keep the data long-term, you can append it to the URL when redirecting to the other page. Never use this for sensitive data (like passwords)—the value will be visible in the URL.
Modify your form-handling page
After validating the input, redirect to the other page with the parameter:
<?php $errormessage = ""; if($_SERVER["REQUEST_METHOD"]==='POST') { if(empty($_POST["field1"])){ $errormessage = "field1 is required!"; } else { // Encode the value to handle special characters $encoded_field1 = urlencode($_POST["field1"]); header("Location: another_page.php?field1=$encoded_field1"); exit; } } ?>
Retrieve on the other page
Use $_GET to access the parameter:
<?php if(isset($_GET["field1"])){ $field1_value = htmlspecialchars($_GET["field1"]); echo "Value of field1: $field1_value"; } else { echo "No field1 parameter provided!"; } ?>
If you need to keep the data permanently or handle sensitive information, store it in a database. This way, you can retrieve it from any page by querying the database.
Step 1: Save to database in your form page
Assuming you're using MySQLi for database connections:
<?php $errormessage = ""; if($_SERVER["REQUEST_METHOD"]==='POST') { if(empty($_POST["field1"])){ $errormessage = "field1 is required!"; } else { // Connect to your database (update credentials to match yours) $conn = mysqli_connect("localhost", "your_username", "your_password", "your_database"); // Sanitize input to prevent SQL injection $safe_field1 = mysqli_real_escape_string($conn, $_POST["field1"]); // Insert the data into a table (create the table first if needed) $sql = "INSERT INTO form_submissions (field1) VALUES ('$safe_field1')"; mysqli_query($conn, $sql); // Get the ID of the new entry to pass to the other page $submission_id = mysqli_insert_id($conn); header("Location: another_page.php?id=$submission_id"); exit; } } ?>
Step 2: Retrieve from database on the other page
<?php if(isset($_GET["id"])){ $conn = mysqli_connect("localhost", "your_username", "your_password", "your_database"); // Sanitize the ID parameter $safe_id = mysqli_real_escape_string($conn, $_GET["id"]); // Query the database for the entry $sql = "SELECT field1 FROM form_submissions WHERE id = '$safe_id'"; $result = mysqli_query($conn, $sql); $submission = mysqli_fetch_assoc($result); if($submission){ $field1_value = htmlspecialchars($submission["field1"]); echo "Value of field1: $field1_value"; } else { echo "No submission found with that ID!"; } } ?>
- Always sanitize user input (use
htmlspecialchars()for output,mysqli_real_escape_string()for database queries, or prepared statements) to prevent XSS attacks and SQL injection. - For sensitive data, avoid using GET parameters or cookies—stick to sessions or encrypted database storage.
- When using sessions, configure PHP to use secure settings (e.g.,
session.cookie_httponly = true,session.cookie_secure = trueif using HTTPS) to reduce cookie theft risks.
内容的提问来源于stack exchange,提问作者JeffreyR

