The advantage of the Web is that it can share information and services. The downside is sharing information and services because some people do things without any scruples.
Take a form as an example. Anyone can visit a Web site and create a local copy of the form using File > Save As on the browser. He can then modify the action parameter to point to a fully qualified URL (not to formHandler.php, but to http://www.yoursite.com/formHandler.php since the form is on this site) and do what he wants If you make any changes, click Submit, and the server will receive this form data as a legal communication flow.
First of all, you may consider checking $_SERVER['HTTP_REFERER'] to determine whether the request comes from your own server. This method can block most malicious users, but it cannot block the most sophisticated hackers. These people are smart enough to tamper with the referrer information in the header to make the remote copy of the form look like it was submitted from your server.
A better way to handle remote form submission is to generate a token based on a unique string or timestamp and put this token in the session variable and the form. After submitting the form, check if the two tokens match. If it doesn't match, you know someone is trying to send data from a remote copy of the form.
To create a random token, you can use PHP's built-in md5(), uniqid() and rand() functions, as shown below:
<span style="font-size: small;"><?php session_start(); if ($_POST['submit'] == "go"){ //check token if ($_POST['token'] == $_SESSION['token']){ //strip_tags $name = strip_tags($_POST['name']); $name = substr($name,0,40); //clean out any potential hexadecimal characters $name = cleanHex($name); //continue processing.... }else{ //stop all processing! remote form posting attempt! } } $token = md5(uniqid(rand(), true)); $_SESSION['token']= $token; function cleanHex($input){ $clean = preg_replace("![\][xX]([A-Fa-f0-9]{1,3})!", "",$input); return $clean; } ?> <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"> <p><label for="name">Name</label> <input type="text" name="name" id="name" size="20" maxlength="40"/></p> <input type="hidden" name="token" value="<?php echo $token;?>"/> <p><input type="submit" name="submit" value="go"/></p> </form> </span>
This technique works because in PHP session data cannot be Migrate between servers. Even if someone obtains your PHP source code, moves it to their own server, and submits information to your server, all your server will receive is an empty or malformed session token and the originally provided form token. They don't match and the remote form submission fails.