如何阻止用户直接访问表单提交后的success.html页面?
Great question! The issue here is that success.html is a static file, so anyone can access it directly via URL. To fix this, we need a way to verify that the user arrived there only after a valid form submission through mailer.php. Here are the most reliable approaches:
This is the most secure method because session data is stored server-side, so users can't easily forge it.
First, modify your
mailer.phpto start a session and set a validation flag before redirecting:// Start the session (must be called before any output, including whitespace) session_start(); // Your existing email sending logic here... // Set a flag to confirm this is a valid submission redirect $_SESSION['valid_submission'] = true; // Redirect to success.php (note: rename success.html to success.php) header('Location: success.php'); exit;Next, rename
success.htmltosuccess.phpand add session validation logic at the top:<?php session_start(); // Check if the valid submission flag exists and is true if (!isset($_SESSION['valid_submission']) || $_SESSION['valid_submission'] !== true) { // Redirect back to contact page if access is unauthorized header('Location: contact.html'); exit; } // Clear the flag to prevent re-access via refresh or back button unset($_SESSION['valid_submission']); ?> <!-- Paste all your original success.html content here --> <!DOCTYPE html> <html> <head> <title>Submission Successful</title> </head> <body> <h1>Thank you for reaching out!</h1> <p>We've received your message and will get back to you soon.</p> </body> </html>
If you need a quick fix and don't mind lower security, you can use a GET parameter—though note that users can manually add this parameter to the URL to bypass the restriction:
Update the redirect in
mailer.php:// After processing the email, redirect with a validation parameter header('Location: success.html?submitted=1'); exit;Add JavaScript to
success.htmlto check for the parameter:<script> const urlParams = new URLSearchParams(window.location.search); // Redirect back if the valid parameter isn't present if (!urlParams.has('submitted') || urlParams.get('submitted') !== '1') { window.location.href = 'contact.html'; } </script>
- Always make sure
session_start()is called before any output (even a single space or newline) in your PHP files, otherwise you'll get a "headers already sent" error. - If you insist on keeping
success.htmlas a static file, you could use server configs (like Apache's.htaccess) to restrict access, but this is more complex than using PHP sessions.
内容的提问来源于stack exchange,提问作者zoenightshade

