PHP Redirect using Headers

PHP Redirect using Headers


A brief tutorial on how to make php redirect to another site using headers.

In this brief tutorial I will show you how to make PHP redirect to another site using headers.

Firstly, note that this will not work if there is any text on the page. This code must be placed on a clean page.

<?php
$url = "http://www.tutorialhelpcentre.com";
header('Location: '.$url);
?>


Code breakdown:
$url = "http://www.tutorialhelpcentre.com";
This line assigns the url you would like to redirect to to the variable $url

header('Location: '. $url);
This line redirects to the location specified in the $url variable. the " '. " tells php that you are redirecting to the url inside the variable $url and not the string '$url'.

An advanced use of this could be a clickthrough monitor, so you know which links your users have visited.

(The following code will require a knowledge of sql databases.)

Firstly you would need to set up a 3 column database firstly an auto_increment, primary key column called 'clickID', a datetime column called 'date' and a varchar column called 'URL'.

You could redirect your users to a URL such as http://www.yoursite.com/click.php?u=http://www.google.com
<?php
include("connection.php"); //connect to your mysql database
$u = $_REQUEST["u"]; //request the information sent in the 'u' url variable
$d = date("Y-m-d H:i:s"); //get todays date

mysql_query("INSERT INTO clicks (date, URL) VALUES('$d', '$u' ) "); //write the information to your database
header('Location: '.$u) ; //redirect the user to the url

?>


This would redirect the user without causing them any extra hastle but allow you to see which of your partners/advertisers are getting the most visits



Submit Comment

Comments

Unfortunately no comments have been left on this tutorial. Be the first using the form above.