Tuesday, June 24, 2008

Prevent form post request from another domain in PHP

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

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
if(strpos($_SERVER['HTTP_REFERER'],’example.com’))
{
//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.

No comments: