In PHP development, confirming the source of form submissions is crucial to prevent forged requests. The following methods can effectively verify whether a submission comes from the expected page and enhance website security.
The HTTP referer header contains the URL of the page that referred the user to the current page. By checking this header, you can determine if the request comes from the same domain:
if (isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], 'yourdomain.com') !== false) {
// Request comes from the same domain
}
POST data contains information submitted via forms. By checking specific fields (such as hidden fields) against expected values, you can verify the submission source:
if (isset($_POST['nonce']) && $_POST['nonce'] === 'expected_nonce') {
// Request comes from the expected form
}
CSRF tokens are random strings generated per session. They can be submitted as hidden fields in forms and compared with the session token:
// Store CSRF token in session
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
// Include hidden field in the form
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
// Verify submitted token
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
// Request comes from the expected form
}
Salt is a random string added to submitted data and then hashed, making it difficult for attackers to forge requests:
// Generate a salt
$salt = bin2hex(random_bytes(32));
// Add salt to data
$data = 'some_data' . $salt;
// Hash the data
$hash = hash('sha256', $data);
// Verify submitted hash
if (isset($_POST['hash']) && $_POST['hash'] === $hash) {
// Request comes from the expected form
}
By using one or more of the methods above, developers can effectively verify the source of form submissions in PHP, prevent forged requests, and enhance the security of web applications.