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.
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
}
?>
POST requests won't always come from domains. They could come from any device connected to the internet. Thus, you should filter according to IP address.
You could do this by creating an array of whitelisted IP addresses, and use in_array
to check.
if (in_array($_SERVER['REMOTE_ADDR'], $whitelist)) {
You could check that _SERVER[HTTP_HOST]
is in your allowed domain list. This value is set by the server so it can't be spoofed by the client. Note that this is the domain that the code is running on, which seems to be what your question is asking. Do you mean the domain that requests were sent from?
if (!in_array($_SERVER['REMOTE_ADDR'], array('ip1', 'ip2'))) die('Not allowed');
You can't do this by checking domains since the domain sending the request can easily be spoofed by the user agent and you'll be helpless. Helpless!
What you are concerned of is called Cross Site Request Forgery. I think that the ideal solution for you would be to include a randomly generated token in the form you want to protect and store a matching token in the session and only allow posts if they match. Someone posting from another domain will need to set the token in the session first and then acquire the token somehow .. they can't do that without viewing the form you create (or being very lucky).