random redirects to sites with php script

September 28th, 2008

I was asked to create a script that would produce an even number of visits to each of three sites. I decided that I would skip the checking of making sure each site had a fair amount and instead generate the url randomly, since by the laws of averages, the number of redirects to each should work out to be roughly even over the course of time. So, onto the script…

$sites = array(
header('Location: '.$sites[array_rand($sites)]);

As you can see, it’s very simple. It is also open for you to add more sites into the $sites array
If you need any help with this or any other code that I have written, contact me via the address in the About page

creating random activation links for downloads

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
              `{$keyfield}` = '{$key}',
              `{$datefield}` = NOW()";

//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


Your website name

//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'];


//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
              (unix_timestamp(NOW()) - unix_timestamp(`{$datefield}`)) < 172800
              `{$keyfield}` = '{$key}'";

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

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


'); }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

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

How to get incoming email via PHP and cPanel

June 24th, 2008

This may be possible to do with other control panel software such as plesk, although I have only done so with cPanel

  1. Open your cPanel homepage, and navigate to the Mail panel
  2. Select the Default Address option
  3. At the bottom of the page, click the Advanced Options »
  4. Select the Pipe to a Program: radio option
  5. In the text field, enter the path from your home directory to the php script
  6. Enter the following code in your script file
#!/usr/bin/php -q

That will collect all the information from the email sent to you, and store it in the $email variable. You will need to add the code after the fclose() for anything to happen with the email, such as save it to a file or parse it for data, or else it will be lost forever. This method will retrieve all headers as well as the data, just for you to be aware

how to process a form with php using one page

June 24th, 2008

Many first time coders in PHP tend to use a form on one page, and a PHP script on a completely different page in order to process it. This is highly irritating since you need to make two pages instead of one, and also, if there is an error you have to redirect back to the original page whilst jumping through hoops to send the data back to the original page.

There is however a rather simple way to do this. First you need to create your (X)HTML document. Below, I’ve created a simple example form using XHTML 1.1

As you can see, it has a single text box and a submit button, with ID’s Name and Submit respectively. Also note the action="". This will automatically make your page post the data to the same page. Many people include the

which is discouraged, since it can lead to XSS Attacks, and since it is not required, it’s just asking for trouble.

OK, onto the PHP code. Here’s some simple PHP, which will check if the form has been posted, by checking if the $_POST['Submit'] is set

	$_POST['Name'] = strip_tags($_POST['Name']);
	$contentdiv = '
Your name is '.$_POST['Name'].'
'; }else{ $contentdiv = '
Please enter your name below
'; } ?>

As you can see, I’ve added the content output I wish to be displayed into a simple <div>. All that is left now is to add some PHP code to the XHTML code to echo out the $content, and save as a .php file and it will all be finished

The PHP code is simply <?php echo $contentdiv; ?> and is added between the <body> and the <form> tags.

You can try out this code by clicking here, or download the script using the button below

Form processor download