Easy PHP Expiring Links

Lets say you have a download you want someone to use and you only want them to have access for x days. What do you to? Create an expiring link. I looked for code for this but everyone wanted to charge. So here is my quick implementation.

1) Take the date you want it to start then turn it into an encrypted string

$string = date("m.d.y"); // note the spaces
$key = "poopsy";
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));

2) You can use this encrypted date string and append it as a var to a link for the person to access.

http://www.site.com/index.php?idx=$encrypted
http://www.site.com/index.php?idx=ey7zu5zBqJB0rGtIn5UB1xG03efyCp+KSNR4/GAv14w=

3) For index.php you need to just take idx and decrypt it into the original date and compare to the number of days you want the link to be active. If it falls within those days then show as usual else just show that the link has expired. Remember that the date you are decrypting is the start date.

<?php

$key = 'poopsy';
$encrypteddate = $_GET['idx'];

$nowstring = date("m.d.y");

$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypteddate), MCRYPT_MODE_CBC, md5(md5($key))), "\0");

//Check to see if it as actual date. 
if (($timestamp = strtotime($decrypted)) === false) {
    
	echo "Invalid IDX Or Link Expired. Expires after 10 Days.";
	

} else {
    
	$enddate = strtotime ( '+10 day' , strtotime ( $timestamp ) ) ;
	
	
	//Make sure the date is correct. 
	if (date('l dS \o\f F Y h:i:s A', $enddate) >= date('l dS \o\f F Y h:i:s A', $timestamp)){
		
		
		//Show what you want. 
		
		
	}else{
		echo "Expired Link"; exit(); 
	}
	
}


						
?>

And thats pretty much it. you need to just encrypt the date then decrpyt when passed to you. You can also pass that variable and use another php file that has all of your download links so you can check to see if the var is correct and if it is just add another var that can be used to denote which file you want to bring back then just use a header command to redirect them to that file.

if (date('l dS \o\f F Y h:i:s A', $enddate) >= date('l dS \o\f F Y h:i:s A', $timestamp)){
		
		$filenum = $_GET['fn']; //fn is the variable passed in that holds the wanted file. 
		if ($filenum == 0){
			header('Location: http://www.site.com/dir/poopsy1.zip');
		}else if($filenum == 1){
			header('Location: http://www.site.com/dir/poopsy2.zip');
		}else if($filenum == 2){
			header('Location: http://www.site.com/dir/poopsy3.zip');
		}else{
			echo "Invalid File";
		}
		
		
	}else{
		echo "Expired Link";
	}

Any questions or concerns just post a comment and i will reply.

 

 

 

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *