如何防范这段PHP代码中的路径遍历漏洞?附作业检测需求
Hey there! Let's walk through how to secure this PHP snippet against path traversal attacks while making sure your "welkom" page redirect and integrity stay intact.
First, let's recap the problem with your current code: directly using the unfiltered $_GET['page'] parameter to build file paths lets attackers craft requests like ?page=../etc/passwd to access files outside your pages directory—definitely not something we want.
Here are the most reliable ways to fix this:
1. Use a Whitelist (Most Secure Approach)
This is the gold standard because it only allows explicitly approved page names. No room for malicious path tricks here.
$pagedir = "pages"; // List all pages users are allowed to access $allowedPages = ['welkom', 'about', 'contact']; // Add your valid pages here // Check if the page parameter is missing OR not in our allowed list if (!isset($_GET['page']) || !in_array($_GET['page'], $allowedPages)) { header("Location: ?page=welkom"); exit; } $page = $_GET['page']; // Now we can safely load the file print file_get_contents("$pagedir/$page");
This guarantees only your pre-approved pages are accessible. If you add new pages later, just update the $allowedPages array.
2. Sanitize Paths and Validate Directory Boundaries
If a whitelist isn't feasible (e.g., you have dozens of dynamic pages), you can sanitize the input and verify the final file path stays within your pages directory:
$pagedir = realpath("pages"); // Get the absolute path of your pages directory if (!isset($_GET['page'])) { header("Location: ?page=welkom"); exit; } $page = $_GET['page']; // Remove any potential traversal sequences first $page = str_replace(['../', '..\\'], '', $page); // Build the full path and resolve any remaining relative components $fullPath = realpath("$pagedir/$page"); // Make sure the resolved path is inside the pages directory AND exists if ($fullPath !== false && str_starts_with($fullPath, $pagedir)) { print file_get_contents($fullPath); } else { // Redirect to welkom if the path is invalid header("Location: ?page=welkom"); exit; }
realpath()converts the path to its absolute, resolved form (eliminating../and symlinks).str_starts_with()checks that the final path doesn't escape thepagesdirectory (usesubstr($fullPath, 0, strlen($pagedir)) === $pagedirif you're on PHP < 8.0).
3. Restrict File Extensions (Additional Layer)
If all your pages use a specific extension (like .html or .php), add a check to enforce this:
$page = $_GET['page']; // Only allow files with .html extension (adjust to your needs) if (!str_ends_with($page, '.html')) { header("Location: ?page=welkom"); exit; }
Combine this with one of the above methods for extra protection.
Verifying the Redirect and "welkom" Page Integrity
To confirm everything works as intended:
- Visit your script without the
pageparameter (e.g.,http://yoursite.com/script.php). You should be automatically redirected to?page=welkom. - Test with an invalid page (e.g.,
?page=hackeror?page=../secret.txt). You should redirect towelkomand not see any unauthorized content. - Check the "welkom" page content directly to ensure it hasn't been altered by the security changes—since we're still loading it from the same
pages/welkomfile, it should stay exactly as you intended.
内容的提问来源于stack exchange,提问作者Always0n

