Search code examples
phpforms

Restrict domains that can send PHP POST Info


Is it possible to restrict domains that are allowed to send POST info to a process.php file.

So for example at the top of the process.php file (which makes use of the $_POST data from the form submission) I want to add something like this.

<?php
  Allowed Domains: domain.com, domain2.com
?>

And only forms that were submitted from the allowed domains will use any of the post information.

This is to prevent someone from creating an HTML form on their own server and manipulating a form to try and exploit any kind of loopholes in the process.php

Basically I have a process.php file that I want to accept form submissions from multiple domains.

e.g. Domain.com/form.html  >>> http://MainDomain.com/process.php
or   Domain2.com/form.html >>> http://MainDomain.com/process.php

I want to allow any page with a form on the allowed domains list to be able to function on the process.php. If a domain that isn't rejected submits to process.php I want it to be rejected.


Solution

  • You can try something like following.

    <?php
    
    $allowedDomains = array('www.abc.com', 'www.xyz.com');
    
    $referer = $_SERVER['HTTP_REFERER'];
    
    $domain = parse_url($referer); //If yes, parse referrer
    
    if(in_array( $domain['host'], $allowedDomains)) {
        //Run your code here which will process the $_POST
    } else {
        echo "you are not allowed to post at this page";
        exit(); //Stop running the script
    }
     ?>