Stop Post Data From Different Domain PHP

0 votes
asked Jul 1, 2009 by juan

I'm a beginner in PHP.

What I'm trying to do is stop Post Data coming from another webpage.

The problem I am having is let's say someone copies my form and pastes it in their website. I want to be able to stop that Post Data from running the script on my email form.

How can I do this? Let me know if I'm not being clear enough.

My PHP Contact form runs on one page with conditional statements. i.e. if data checks out, submit.

4 Answers

0 votes
answered Jul 1, 2009 by andymckenna

$_SERVER['HTTP_Referrer'] would be nice but it isn't reliable. You could use a hidden form field that MD5's something and then you check it on the other side.

0 votes
answered Jul 1, 2009 by peter-stone

If you're looking for a quick-and-dirty approach, you can check the REFERER header.

If you really want to make sure that the form was fetched from your site though, you should generate a token each time the form is loaded and attach it to a session. A simple way to do this would be something like:

$_SESSION['formToken'] = sha1(microtime());

Then your form can have a hidden input:

<input type="hidden" name="token" value='<?=$_SESSION['formToken'];?>' />

and you can check that when deciding whether to process your form data.

0 votes
answered Jul 1, 2009 by tom-ritter

You're trying to prevent CSRF - Cross-Site Request Forgery. Jeff himself has a blog article about this.

True XSRF Prevention requires three parts:

  • Hidden Input Fields, to prevent someone from just snatching the form and embedding it
  • Timechecking within an epsilon of the form being generated, otherwise someone can generate a valid form once and use the token (depending on impementation/how it's stored)
  • Cookies: this is to prevent a malicious server from pretending it's a client, and performing a man-in-the-middle attack
0 votes
answered Jul 1, 2009 by matt-bridges

In the form:

<?
$password = "mypass"; //change to something only you know
$hash = md5($password . $_SERVER['REMOTE_ADDR']);
echo "<input type=\"hidden\" name=\"iphash\" value=\"$hash\"/>";
?>

When you are checking:

$password = "mypass"; //same as above
if ($_POST['iphash'] == md5($password . $_SERVER['REMOTE_ADDR'])) {
    //fine
}
else {
    //error
}
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...