Current Location: Home> Latest Articles> Comprehensive Guide to Verifying PHP Form Submission Sources

Comprehensive Guide to Verifying PHP Form Submission Sources

M66 2025-09-20

How to Verify Form Submission Sources in PHP

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.

Check the HTTP Referer

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
}

Validate HTTP POST Data

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
}

Use CSRF Tokens

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
}

Use Salt Verification

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
}

Conclusion

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.