PHP Redirection Redirecting URL Tutorial, PHP Redirecting URL


 

PHP Redirection Redirecting URL Tutorial, PHP Redirecting URL

If you are moving from one hosting company to another, you should know how to keep your existing visitors and redirect them to a new location.

If you are moving from one hosting company to another, you should know how to keep your existing visitors and redirect them to a new location.

In this tutorial I would like to describe three possible ways of redirecting a visitor to any other URL. Also you can read here PHP, HTML and JavaScript redirection source examples.

The first method stands on HTTP protocol advantages. Any HTTP answer sent to browser from the server has two parts: the header and the body.

Header part contains some special fields describing transferred data. This helps the broswer to understand and to show received data in proper way. For example any web programmer should know about the Content-Type header field, which is used to specify the data type.
In this tutorial we need another header field:

Location: URL
URL here is the address for browser to where it should be redirected. When the browser receives the HTTP header with Location field set it ignores all other data and jumps to another location specified in URL.

Perl source code.
It is easy to write a redirection in Perl:

print "Location: http://roseindia.net\n\n";

But you must remember to write this string before any other output. Actually it is the only needed line of output in your redirection script. Note that \n\n symbols in the end of the string. This is a separator between the HTTP header and HTTP body parts and it is necessary to be included.

PHP source code.
In PHP there is a special function called header(). You can specify all HTTP header fields in this function.
Just for redirecting you can use:

header("Location: http://roseindia.net");

Again, remember to write this line before any output operation. Otherwise your header will be generated by the web server and this line would be interpreted like just text.

The second redirection method stands on HTML language. There is a META tag, to be used for redirection needs.
Syntax:

<META http-equiv="refresh" content="0; url=http://roseindia.net">

You can even write the number of seconds into content parameter to allow browser wait before redirection. This tag should be used only in the HEAD part of the HTML page.
Example of the HTML page with redirection:

<HTML> <HEAD> <META http-equiv="refresh" content="0; url=http://roseindia.net"> </HEAD> <BODY> <H1>Redirect page</H1> </BODY> </HTML>

The third method is about using JavaScript. I suggest to use this seldom, because user is allways able to turn off the JavaScript on his browser. This is a JavaScript command for a browser window to move to another location.

window.location=http://roseindia.net;

Example:
Source code:

<form><input onClick=window.location="http://roseindia.net" type=button value=Redirect></form>

Ads