PHP TutorialsWeb Developer

Create a website redirect with php headers

Written by:

Sometimes on your website you will have the need to redirect users to other pages. Be it because of an old and broken link or just redirecting them after they login. No matter the reason, it can be done quickly and with very little effort using php headers.

Redirecting between users to a different page in PHP is done using “headers”. Basically headers are the FIRST pieces of information that a websites will send to users when they are viewing the site. Note that I said the FIRST.

I cannot stress how important this is if you’re manually changing the headers being sent to the user to. Specifically to tell their browser to go to a different location. And it is very important that it is the first and only information we send to the user from original page they are landing on.

If any other data is sent to the user like displaying a simple message or even a full web page, the redirect will NOT work! So keep that in mind.

Out of standard practice of redirecting users using PHP, the only content or code in the file the user visits is just a few lines of code. Anything more and it will defeat the purpose or the redirect. After all, why display content if you are sending them somewhere else.

Redirects with header function

<?php header("Location:"); die(); ?>

The header() function takes a single string parameter, with the string being formatted a special way of course. That simple way being just stating what header you want to manually set (e.g. “Location” or “Expires”). Do note that each header begins with an upper case first letter. If you want to lean more, you can learn some other use on the page for the header function.

Check this out:  Create a Custom URL Shortener in PHP

For a simple redirect you just need to specify the new “Location” that you want to send the user to. In my case, i am just going to send them to my sites homepage.

After the header function, the die() function closes the script. The reason for this is that header redirects can be blocked if the user wants to prevent them, so in the event that a user does prevent the redirect your web page will always stop everything else it is doing. This way any malicious attacker cannot use this to their advantage to attack your web site.

Advanced Headers You Can Change

If you want to make a slightly more advanced header redirect, I like to specify a few extra headers.

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");

Using the “Expires” and no-cache header options tells the browser that the page was created so long ago, that it is not worth trying to save any of the content on the current page to make it load faster in the future. This way, our redirect will be just a little more efficient.

Leave a Reply

%d bloggers like this: