Archive for July, 2008

creating random activation links for downloads

Monday, July 21st, 2008

This article is intended for advanced users. It explains the principles behind creating a download activation link that is completely random and will stay active for 48 hours after a payment through paypal for example is made

You are going to need two files for this to work. The first is going to be the file that creates the link, adds it to a database table and sends the link via email. The second is the file that will parse all incoming links for the download script, and if the link is verified as being correct it will proceed to allow a user to download the file

NOTE: I will not be describing the intricacies of email or the payment via paypal in this article, merely the methods by which you will need to follow in order to achieve a link creation and verification

Part 1 – Creating the activation key

This should go in your script after your payment has been accepted. I have also not included mysql connection details and function either ie the mysql_connect function or the close function. This is in case you are working with multiple databases whilst doing this

The rand_text function is explained here

function rand_text(   $min = 10,
                      $max = 20,
                      $randtext = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' )
{
    if($min < 1) $min=1;
    $varlen = rand($min,$max);
    $randtextlen = strlen($randtext);
    $text = '';

    for($i=0; $i < $varlen; $i++)
    {
        $text .= substr($randtext, rand(1, $randtextlen), 1);
    }
    return $text;
}

// Some setup values
$tblname = 'tbl_keys'; #table name in database
$keymin = 50; #mimumum key length
$keymax = 80; #maximum key length
$keyurl = 'http://www.domain.com/activate.php?key='; #domain to add key to
$datefield = 'added'; #date field to put insert date into
$keyfield = 'key'; #activation key field
$mailto = 'email@example.com'; #email to send link to
$mailsubject = 'Download activation link'; #email subject line

// create random string
$key = rand_text($keymin,$keymax);
// add it to database with current date
$query = "INSERT INTO
              `{$tblname}`
          SET
              `{$keyfield}` = '{$key}',
              `{$datefield}` = NOW()";
mysql_query($query);

//Add key to activation url template
$keyurl .= $key;

//Create mail message
$message = "Below is your activation link. You have 48 hours in which to use it, after which it will expire

{$keyurl}

Your website name
http://www.yourdomain.com/";

//Mail activation key to the user
mail($mailto, $mailsubject, $message);

So you now have an emailing key generator. Next you will need to make a table in your database (remember to change tbl_keys to the one assigned to $tblname above)

CREATE TABLE `tbl_keys` (
  `id` int(11) NOT NULL auto_increment,
  `added` datetime NOT NULL,
  `key` varchar(100) NOT NULL,
  PRIMARY KEY  (`id`)
)

That's a basic example just for this tutorial. For yours you can add other information such as the download id for the link (ie what the user will download upon clicking the link) plus any other info you wish to store with each link

Part 2 - Creating the key verification and download script

Now we need to create the activate.php script that was in the $keyurl above, to take the key and verify that the key hasn't expired

//Verify a key has been entered
if(!isset($_GET['key']) || strlen($_GET['key'] == 0))
{
	//Redirect to site homepage
	header('Location: /index.php');
}

// Some setup values (same as first script)
$tblname = 'tbl_keys'; #table name in database
$datefield = 'added'; #date field to put insert date into
$keyfield = 'key'; #activation key field

//Assign key to shorter variable for ease of use
$key = $_GET['key'];

//////////////////////////////////////////////////
//CONNECT HERE TO DATABASE USING mysql_connect()//
//////////////////////////////////////////////////

//Remove any nasty characters that might cause SQL Injection
//(removes any characters except a-z and 0-9)
$key = preg_replace('/[^A-Za-z0-9]/','',$key);

//Set up query to run (The 172800 is 48 hours in seconds)
$query = "SELECT
              *
          FROM
              `{$tblname}`
          WHERE
              (unix_timestamp(NOW()) - unix_timestamp(`{$datefield}`)) < 172800
          AND
              `{$keyfield}` = '{$key}'";

//Run the query
$res = mysql_query($query);

//Check that a result was found
if(mysql_num_rows($res) < 1)
{
	//Key not found
	die('

ERROR: KEY INVALID/EXPIRED

'); }else{ //////////////////////////////////////////////////////// //INSERT YOUR CODE HERE FOR WHAT HAPPENS IF THE KEY IS// //CORRECT AND HASNT EXPIRED // //////////////////////////////////////////////////////// }

All that's left is for you to add your mysql connection and also your code for what to do if the link is valid in the above code

If you have any suggestions on how to improve it or any questions, just drop me a line

php random string generator function

Wednesday, July 16th, 2008

Many people need a random string for things such as salts, activation keys and new passwords. Here’s a simple but versatile function to return a random string

function rand_text(   $min = 10,
                      $max = 20,
                      $randtext = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' )
{
    if($min < 1) $min=1;
    $varlen = rand($min,$max);
    $randtextlen = strlen($randtext);
    $text = '';

    for($i=0; $i < $varlen; $i++)
    {
        $text .= substr($randtext, rand(1, $randtextlen), 1);
    }
    return $text;
}

To call this function, you can simply use rand_text() which will return a random alphanumeric string between 10 and 20 characters long. You can also specify a min and max length, and can also specify the string of characters that can be used in the random string. For example

echo rand_text(5,8,'abcdef0123456789');

will output a random hex value between 5 and 8 characters in length such as 2fe4e1