How to Redirect URLs in PHP

In this programming tutorial, we will look at different methods to redirect URLs in PHP. Specifically, we will be examining 301 URL redirect methods via code, meta refresh and the use of PHP header location settings to invoke a redirection.

There are times when you decide to write a redirect script in PHP. The following are the advantages of using creating such a script in PHP:

1.) PHP is a server side scripting language; the redirect script will be executed on your server and not on your visitors browser. This is a non-client/browser dependent approach. Some redirects are client side, such as JavaScript and will fail if the user wishes to disable Java Scripting functionality.

2.) It is a more flexible and versatile approach; you can execute several types of redirects in PHP that you can’t with other methods. For example, the following are the most commonly types of redirects that can be done in PHP:

a.) 301 permanent redirection status.
b.) 302 temporary redirection status.
c.) Refresh type

There are still other redirection header status’ that you can do with PHP, but this tutorial will focus on the above types of redirecting URLs. This is helpful for beginning webmasters who are looking for ways to implement URL redirection if it is not possible to with other common solutions, such as .htaccess.

The PHP Header() Function

Redirecting URLs in PHP centers around the PHP Header() function. For example, suppose you want to redirect to this URL http://www.somewebsite.com/target.php. In the originating PHP page, you will simply call this script:

<?php
header(‘Location:
http://www.somewebsite.com/target.php’);
?>

This is the most basic form and may not be appropriate in all cases or in your own implementation. Anyway for the purpose of introducing you to redirecting URLs in PHP, try this simple experiment in your XAMPP localhost:

1.) Open a text editor and type this code:

<?php
echo "Hi this is codex-m";
?>

Save it as targetpage.php and put it inside the htdocs folder.

2.) Open another blank text file and enter this code:

<?php
header(‘Location:
http://localhost/targetpage.php’);
?>

Save it as originatingpage.php and put it also in the htdocs folder.

3.) Now launch your web browser. In the browser address bar, type: http://localhost/originatingpage.php

4.) You will notice that after you press enter. This URL: http://localhost/originatingpage.php redirects to http://localhost/targetpage.php and the content you see is the targetpage.php content which is “Hi this is codex-m”.

Let’s try to analyze what happens internally in the server header status sent and received by your browser. You need to have Firebug: http://getfirebug.com/ installed in your Firefox browser to do this.

1.) In your Firefox browser, paste the originating page URL: http://localhost/originatingpage.php in the address bar and do not yet press enter.

2.) In the browser, go to View and click “Firebug”.
3.) Click “Net” tab.
4.) Now, click on the browser address bar and press enter to load the page.
5.) You will notice that after pressing enter, the server header status details are showing in the Firebug Net panel. This is how it looks:

Let’s dissect what happened. First, the browser requested this URL: http://localhost/originatingpage.php to the server, then the server executed the code inside originatingpage.php.

Since, it contains this line:

header(‘Location: http://localhost/targetpage.php’);

The server responded by redirecting the user to http://localhost/targetpage.php. You also observed that the redirection status is 302 found, which means it is a “temporary” type of redirection. After redirection, there are no further redirections and the page is given with a 200 OK status.

Lessons:

1.) By default, this line:

header(‘Location: http://www.yourtargeturl.com’);

Returns a 302 found redirection status.

2.) After redirection, the page is given with a 200 OK header status.

Mistake: Outputting HTML or even spaces before Header()

Now you have a very basic working knowledge of how to use header() to redirect URLs. Let’s go deeper to illustrate a common pitfall when doing redirections. Try this experiment:

1.) Go to originatingpage.php script and add any HTML tag before:

header(‘Location: http://localhost/targetpage.php’);

Suppose you have this code:

<html>
<head>
<title>This a redirection example that will fail</title>
</head>
<body>
<?php
header(‘Location:
http://localhost/targetpage.php’);
?>
</body>
</html>

2.) Save the file.
3.) Run again originating.php script in the browser using your development server/XAMPP localhost. If you don’t see any error, you will notice that it still redirects cleanly to targetpage.php
4.) Now try changing the target URL to point to your real website, example:

<html>
<head>
<title>This a redirection example that will fail</title>
</head>
<body>
<?php
header(‘Location:
http://www.php-developer.org/’);
?>
</body>
</html>

5.) Upload originatingpage.php to your remote hosting website root directory.
6.) Execute the script in the browser by calling the originatingpage.php URL, for example: http://www.php-developer.org/originatingpage.php
7.) You will notice that this time, you will encounter an error such as:

Warning: Cannot modify header information – headers already sent by (output started at /home/phpdevel/public_html/originatingpage.php:6) in /home/phpdevel/public_html/originatingpage.php on line 7

What’s going on here? The cause of the problem is that you already output HTML before header() function. In this case, this are the HTML you already outputted based on the above example:

<html>
<head>
<title>This a redirection example that will fail</title>
</head>
<body>

Lessons:

1.) Some errors pertaining to the use of PHP header() to do redirections will not be visible or experienced in the development server (such as the XAMPP example above). But this will introduce serious issue when executed on your actual website (at the remote server).

2.) You should never output even a single HTML character, tag or text before the header() function. This includes spaces. Examples below will NOT work:

a.)

<p>Hi, hello!</p>
<?php
header(‘Location:
http://www.yourtargeturl.com’);
?>

Note: You outputted <p> tags before header.

b.)

{space before <?php opening tag}
<?php
header(‘Location:
http://www.yourtargeturl.com’);
?>

Note: You have a space before the PHP opening tag.

c.) Some weird things will also happen if you save the updated PHP file as UTF-8, because it will introduce this character before <?php: ο»Ώ , this is called “BOM”, make sure you double check this.

{mospagebreak title=Permanent URL 301 Redirect in PHP}

So far the examples above will return a 302 as the header status. The most important redirects in real-world implementations use the 301 redirection status. The primary reason is that it is the only “search engine friendly” redirect. If you moved the URL to its new location, search engine ranking scores such as Google PageRank won’t be passed to the new URL unless you are using 301 redirects.

So how you will be able to 301 redirect using the PHP Header()? This time you need to use the http response code parameter of header(). Supposing you will 301 redirect to: http://localhost/targetpage.php from http://localhost/originatingpage.php

The redirection code will be:

<?php
header(‘Location:
http://localhost/targetpage.php’,TRUE,301);
?>

The 301 is now included to make sure it will return a 301 header status. You can check this using Firebug if you are using a development server. Or if you are testing this using a live server, you might need to use a server header status checker such as: http://www.seoconsultants.com/tools/headers.

Common 301 redirection PHP code examples (always remember to place these codes above any HTML and ensure that HTML is not outputted first):

1.) Conditional 301 redirect (redirect when the URL matches to a given URL)

<?php

//Function to get the current URL of the website
function currentpageurl() {
 $currentpageurl = ‘http';
 if ($_SERVER["HTTPS"] == "on") {$currentpageurl .= "s";}
 $currentpageurl .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $currentpageurlL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $currentpageurl .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $currentpageurl;
}

//Equate the current URL with $currentpageurl variable
$currentpageurl=currentpageurl();

//Conditional check to redirect
if ($currentpageurl=="
http://www.example.org/301redirecttest.php") {

//URL match, do 301 redirect
header(‘Location:
http://www.example.org/’,TRUE,301);
exit();
}
?>

The above example will only do a 301 redirect to the homepage URL http://www.example.org if the URL is http://www.example.org/301redirecttest.php

2.) 301 redirect all non-www URLs to www URLs using PHP (assuming your protocol is http:// all throughout your website and not using https):

<?php

//Get current page URL
$currentpageurl= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

//Check if the URL is non-www version
if (!(preg_match("/www/i",$currentpageurl))) {

//URL is a non-www version, append www to the URL
$wwwversion="
http://www.".$currentpageurl;

//301 redirect to the www version
header("Location: $wwwversion",TRUE,301);
exit();
}
?>

3.) 301 redirect all http to https (non-secure to secure 301 redirection):

<?php

$currenturl= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

//Check if it is not using the secure port which is 443
if ($_SERVER["SERVER_PORT"] != "443") {

//not connecting through secure https port
, this URL is using http protocol

//append https
$secureversion="
https://".$currenturl;

//Redirect to the secure version
header("Location: $secureversion",TRUE,301);
exit();
}

echo "Hi, this will redirect any non-secure page to equivalent secure page";
?>

Disclaimer and remarks: The above scripts are provided for illustration/basic example purposes only. In actual implementation, the above sample redirection scripts might be tweaked further to fully fit the implementation.

{mospagebreak title=Refresh Redirects in PHP}

Another type of redirect is the refresh type of redirect. This is easily done in HTML as a meta refresh redirect. In PHP, you can do this as follows:

<?php
header("refresh:5;url=http://www.example.org/targeturl.php");
echo ‘You’ll be redirected in about 10 secs. If not, click <a href="
http://www.example.org/anotherurl.php">here</a>.’;
?>

This is not a search engine friendly redirect and along with 302 redirection, it should not be used for SEO purposes. The only thing that is acceptable to most search engines including Google is the 301 redirect.

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye