Example of form post a spam
How to check the form being posted from another domain
Last time, I’ve posted the article about useful server variables in PHP. Among them, we can use HTTP_REFERRER server variables to prevent the cross domain form post request. You can look at the example code in PHP below to check the POST request is from the same domain or different domain.
//if example.com is there in HTTP_REFERRER variable
HTTP_REFERRER variable is used here to check where the post request came from. Then, along with strpos() function of PHP, we can check weather the HTTP_REFERRER variable contains our domain as a referrer website or not. If the post request is from our domain then only we can execute the remaining code of our page.
A better approach
The HTTP_REFERRER headers can be disabled or faked and we can’t rely 100% on it.But, we can also use cookie to check for the cross-site post request forgery. And, you know that cookies are also unreliable anyway.
One of the better approach will be to use use a hidden field in the form which contains the md5() value of a salt (a secret value stored in the database) with another dynamic value like session id or IP address of the user and verifying it with PHP when the post request of that form comes in PHP.