如何在两个PHP POST处理逻辑间正确传递全局变量$workshopPath?
$workshopPath Variable Persistence Issue Hey there, I see exactly what's tripping you up here—this is a super common gotcha with PHP and HTTP's stateless nature! Let's break down why your global variable isn't sticking, then fix it step by step.
Why the Global Variable Fails
HTTP is stateless, meaning every time your form submits a request (whether it's clicking "Go to Workshop" or "Update Text"), it spins up a fresh instance of your PHP script. The $workshopPath you set when the user enters a workshop number only exists during that first request. By the time you submit the update form, that global variable is long gone—hence the empty string and your title file getting written to the root directory instead of the correct workshop folder.
The Solution: Use Sessions to Persist the Path
Sessions let you store data across multiple requests for the same user. This is perfect for keeping track of which workshop the user is working on between form submissions. Here's how to implement it:
Step 1: Start the Session
Add session_start() at the very top of your script (before any output—even accidental whitespace!). This initializes the session so you can save and retrieve data across requests.
Step 2: Store $workshopPath in the Session
When the user submits a valid workshop number, save the path to the session instead of a global variable:
$_SESSION['workshopPath'] = "submissions/" . $workshopNumber . "/";
Step 3: Retrieve the Path from the Session During Update
When handling the update request, pull the path from the session. Also, add checks to make sure it's not empty (so you don't try writing to the root if the user skips selecting a workshop first).
Modified Full Code
Here's your updated code with these fixes, plus extra safety checks to avoid bugs and security risks:
<?php // Start the session FIRST—this is critical! session_start(); $error = ''; $success = ''; if (isset($_POST['gotoWorkshop'])) { if (empty($_POST['numberInput'])) { $error = "Please enter a valid workshop number"; } else { // Sanitize input to prevent path traversal attacks (e.g., someone entering "../") $workshopNumber = preg_replace('/[^0-9]/', '', $_POST['numberInput']); if (empty($workshopNumber)) { $error = "Workshop number can only contain digits"; } else { $workshopPath = "submissions/" . $workshopNumber . "/"; // Verify the workshop directory actually exists if (!is_dir($workshopPath)) { $error = "Workshop directory does not exist"; } else { $_SESSION['workshopPath'] = $workshopPath; $success = "Loaded workshop #$workshopNumber successfully!"; } } } } if (isset($_POST['updateTextItems'])) { // Get the saved path from the session, default to empty if not set $workshopPath = $_SESSION['workshopPath'] ?? ''; if (empty($workshopPath)) { $error = "Please select a workshop first"; } elseif (!empty($_POST['titleInput'])) { $titleInput = stripslashes($_POST['titleInput']); $titleFile = fopen($workshopPath . "title.txt", "w") or die("There was an error updating the title file."); fwrite($titleFile, $titleInput); fclose($titleFile); $success = "Workshop title updated successfully!"; } } // Display error/success messages to the user if (!empty($error)) { echo "<p style='color: #dc2626;'>$error</p>"; } if (!empty($success)) { echo "<p style='color: #059669;'>$success</p>"; } ?>
Extra Safety & Usability Notes
- Input Sanitization: The
preg_replaceline strips non-digit characters from the workshop number, which prevents malicious users from using path traversal to access directories outsidesubmissions/. - Directory Validation: We check if the workshop directory exists before saving the path to the session—this avoids trying to write to a non-existent folder later.
- User Feedback: Added simple error/success messages so the user knows what's happening with their actions.
Alternative: Hidden Form Field
If you don't want to use sessions, you could add a hidden input to your update form that holds the $workshopPath value. However, this is less secure because users can easily edit the hidden field's value. Sessions are the safer, more reliable choice here.
内容的提问来源于stack exchange,提问作者Charles M

