Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop Post Data From Different Domain PHP

Tags:

post

forms

php

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.

like image 419
Juan Avatar asked Jul 01 '09 16:07

Juan


2 Answers

"accepted answer" has security holes. Instead, you should use more secure methods. A simple example:

Step 1: Disable framing of the page (.php), where the form is generated, in the top add:

header('X-Frame-Options: Deny');

Step 2: (important part ! ): In order to avoid XSS and 3rd party exploits, you should create a expirable validation. For example:

  • ASP.NET builtin forms use dynamic input csrf (example value: gtlkjh29f9ewduh024cfvefb )
  • WordPress builtin forms use dynamic input nonce (example value: 340297658942346 )

So, if you are on a custom platform, which doesn't have built-in temporary token validation methods, then implement your approach. A simple concept:

<?php  
$secret_key      = 'fjd3vkuw#KURefg';  //change this
$encrypted_value = Cryptor::encrypt( time(), $_SERVER['REMOTE_ADDR'] . $secret_key);
?>
<form>
...
...
<input value="<?php echo $encrypted_value;?>" name="temp_random" type="hidden"  />
</form>

(Cryptor code is here )

on submission, check:

if(!empty($_POST)){

   // If REFERRER is empty, or it's NOT YOUR HOST, then STOP it
   if( !isset($_SERVER['HTTP_REFERRER']) || parse_url($_SERVER['HTTP_REFERRER'])['host'] != $_SERVER['HTTP_HOST'] ){
       exit("Not allowed - Unknown host request! ");
   }

   // Now, check if valid
   if (   Cryptor::decrypt(  $_POST['temp_random'], $_SERVER['REMOTE_ADDR'] . $secret_key) < time() - 60* 15 ) {
       exit("Not allowed - invalid attempt! ");
   }

   ...........................................
   ... Now, you can execute your code here ...
   ...........................................

}
like image 168
T.Todua Avatar answered Nov 05 '22 11:11

T.Todua


$_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.

like image 45
AndyMcKenna Avatar answered Nov 05 '22 10:11

AndyMcKenna