I have a form in my php page. In this page, i am opening a window popup. In this popup there are some fields. We fill the form and submit it. After submitting the form we send a mail to user. basically it is an form where user can give reference of website to their friend by sending mail to him. Unfortunately someone hacked my website and uses my php script to sending mails. So, I want to restrict access of php script from outside server. What should i do to restrict access. I have tried some option but did not get success.
Asked
Active
Viewed 792 times
0
-
1Without the code showing how you're currently sending mail, we can't really say much. Also, is it your code that is vulnerable, or whatever you're using for mail on the server? Going simply by the post title, CSRF tokens would help. – Jonnix Nov 08 '16 at 11:06
-
I don't think if you can do something because your function is based on sending emails ! maybe you can limit users by their IP (not 100% secure), but can slow down the people who use your script ! – Sinf Nov 08 '16 at 11:06
-
1You need to add csrf token for every post request to prevent cross domain request. Follow this for more info http://stackoverflow.com/a/31683058/4584028 – Balraj Allam Nov 08 '16 at 11:10
1 Answers
1
There are two ways that you can mitigate this, totally stopping this is not possible.
Use HTTP Referer:
$referer = parse_url($_SERVER['HTTP_REFERER']);
$allowedDomain = 'yourdomain.com';
if ($referer['host'] == $allowedDomain){
//Process your mail script here.
}
Note that you can not trust HTTP_REFERER value. It can be easily spoofed.
Use Tokens:
Generate a random token and put it within your form POST like:
if (!isset($_POST['submit'])){
$_SESSION['random_code'] = rand(0, 1000000);
}else{
if ($_POST['random_code'] == $_SESSION['random_code']){
//process your mail script here
//reissue session code
$_SESSION['random_code'] = rand(0, 1000000);
}
}
<input type='hidden' name="random_code" value="<?php echo $_SESSION['random_code'];?>">
Save this random code in your session. And when the form is submitted, match the submitted random_code value with the code saved in your session. If both are same then process your mail script.
In this way, attacker has to first open your page, get the random code and then submit your form. It will not stop this attack, but it will definitely slow down his process.

Ghulam Ali
- 1,935
- 14
- 15