Below is the complete PHP download script (download.php): <?php //Start PHP session because you need to compare the session received if it is using correct key. session_start(); //Get referer $referer = $_SERVER['HTTP_REFERER']; //Define the correct session value, the value of $pass should be the same with $key as discussed in the previous section no.8. $keymatch= $_SESSION['key']; //Validate user by checking if the user has correct session set and referring page if (($referer=="http://www.yourdomain.com/thisisyourdownloadpage.php")&& ($keymatch==$md5value)) { //User is valid, connect to MySQL database $username = "Your MySQL database username"; //Get the IP address of the user $ipdownloader= $_SERVER['REMOTE_ADDR']; //Sanitize input $ipdownloader = mysql_real_escape_string($ipdownloader); //check if the user already downloaded before if (!($fetch = mysql_fetch_array( mysql_query("SELECT `ipaddress` FROM `downloads` WHERE `ipaddress`='$ipdownloader'")))) { //No records found, fresh downloader //Define the content type and show force download attachment dialog header("Content-type:application/pdf"); //Stream the PDF file for downloading using PHP readfile function
//Record downloader IP address to MySQL database and set download to 1 $firstdownload=1; //Already has downloading records; check how many times the user downloaded the ebook $result = mysql_query("SELECT `downloadtimes` FROM `downloads` WHERE `ipaddress`='$ipdownloader'") //the user downloaded less than 3 times, the user still eligible to download the ebook. Stream the PDF to the user for force downloading. header("Content-type:application/pdf"); //Update download records of the user by incrementing it with 1 $updateddownloadtime = $downloadtimes + 1; //Update download times information of the user in MySQL database mysql_query("UPDATE `downloads` SET `downloadtimes` = '$updateddownloadtime' WHERE `ipaddress` = '$ipdownloader'") //The user already exceeds the downloading limit, prevent downloading session_destroy(); //Redirect the user back to the previous page using meta refresh. echo "<meta http-equiv='refresh' content='0;url=http://www.yourdomain.com/thisisyourdownloadpage.php'>"; //Close the MySQL database connections mysql_close($dbhandle); //Invalid user -fails during user authentication, either bad wrong session key or referring page. //Destroy any session. session_destroy(); //Redirect the user back to the download page. echo "<meta http-equiv='refresh' content='0;url=http://www.yourdomain.com/thisisyourdownloadpage.php'>"; Implementation Tips Below are the recommended tips for implementation:
blog comments powered by Disqus |
|
|
|
|
|
|
|