Thursday, April 29, 2010

2:48 AM

HTTP POST request from outside domain is one of the way of attacking your website. A intruder can use JavaScript in other domain or localhost to send the repetitive POST request to your web page  containing PHP script. We must prevent this kind of cross domain form posting which might be harmful of our website.

Example of form post a spam

Let’s suppose that, we have a contact form in our website and we’re posting the detail of the form to “contact.php” file. A intruder can use JavaScript in another domain and can send the repetitive post request by placing “http://our-site/contact.php” in the action field of their code and spam our website.

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 is there in HTTP_REFERRER variable
  //only process operation here

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.