PHP Redirect To Another URL / Web Page Script Example

by on August 25, 2008 · 71 comments· LAST UPDATED March 8, 2015

in , ,

How do I redirect with PHP script? How can I use a PHP script to redirect a user from the url they entered to a different web page/url?

Tutorial details
DifficultyEasy (rss)
Root privilegesNo
Estimated completion time1m
Under PHP you need to use header() to send a raw HTTP header. Using headers() method, you can easily transferred to the new page without having to click a link to continue. This is also useful for search engines. Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

HowTo redirect with PHP

You can easily redirect using following header("Location: ....) syntax:

/* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */

The header() is used to send a raw HTTP/1.1 specification specific header. header() must be called before any actual output is sent, the following example will not work:

echo "Hello world";
echo $var;
* Remember that header() must be called before any actual output is sent,
* either by normal HTML tags, blank lines in a file, or from PHP.

PHP Redirect with HTTP Status Code

Create a sample function called movePage() in sitefunctions.php (note I'm not the author of the following I found it somewhere else on the Internet):

function movePage($num,$url){
   static $http = array (
       100 => "HTTP/1.1 100 Continue",
       101 => "HTTP/1.1 101 Switching Protocols",
       200 => "HTTP/1.1 200 OK",
       201 => "HTTP/1.1 201 Created",
       202 => "HTTP/1.1 202 Accepted",
       203 => "HTTP/1.1 203 Non-Authoritative Information",
       204 => "HTTP/1.1 204 No Content",
       205 => "HTTP/1.1 205 Reset Content",
       206 => "HTTP/1.1 206 Partial Content",
       300 => "HTTP/1.1 300 Multiple Choices",
       301 => "HTTP/1.1 301 Moved Permanently",
       302 => "HTTP/1.1 302 Found",
       303 => "HTTP/1.1 303 See Other",
       304 => "HTTP/1.1 304 Not Modified",
       305 => "HTTP/1.1 305 Use Proxy",
       307 => "HTTP/1.1 307 Temporary Redirect",
       400 => "HTTP/1.1 400 Bad Request",
       401 => "HTTP/1.1 401 Unauthorized",
       402 => "HTTP/1.1 402 Payment Required",
       403 => "HTTP/1.1 403 Forbidden",
       404 => "HTTP/1.1 404 Not Found",
       405 => "HTTP/1.1 405 Method Not Allowed",
       406 => "HTTP/1.1 406 Not Acceptable",
       407 => "HTTP/1.1 407 Proxy Authentication Required",
       408 => "HTTP/1.1 408 Request Time-out",
       409 => "HTTP/1.1 409 Conflict",
       410 => "HTTP/1.1 410 Gone",
       411 => "HTTP/1.1 411 Length Required",
       412 => "HTTP/1.1 412 Precondition Failed",
       413 => "HTTP/1.1 413 Request Entity Too Large",
       414 => "HTTP/1.1 414 Request-URI Too Large",
       415 => "HTTP/1.1 415 Unsupported Media Type",
       416 => "HTTP/1.1 416 Requested range not satisfiable",
       417 => "HTTP/1.1 417 Expectation Failed",
       500 => "HTTP/1.1 500 Internal Server Error",
       501 => "HTTP/1.1 501 Not Implemented",
       502 => "HTTP/1.1 502 Bad Gateway",
       503 => "HTTP/1.1 503 Service Unavailable",
       504 => "HTTP/1.1 504 Gateway Time-out"
   header ("Location: $url");

First include sitefunctions.php and than call movePage() as follows:

/* Move page with 301 http status code*/

How do I test url redirection?

If you are using Apple OS X or Linux/Unix-like operating system, open the Terminal app and type curl command as follows:
$ curl -I your-url-here
$ curl -I

Sample outputs:

HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Mon, 30 Dec 2013 22:31:37 GMT
Connection: keep-alive
X-Galaxy: Andromeda-2

If you are on MS-Windows or do not want to use command line try redbot tool:

Fig. 01:  Check HTTP Location url redirection with redbot tool

Fig. 01: Check HTTP Location url redirection with redbot tool

Tweet itFacebook itG+ itDownload PDF versionFound an error/typo on this page?
1 sp2hari August 26, 2008 at 11:02 am

Cool post.
You can also do this using HTML or Javascript.

Using HTML META tag

Using Javascript function

function Redirect(url)
 location.href = url;
This can be called as
Redirect ("");

2 sp2hari August 26, 2008 at 11:03 am

Sorry, I guess the meta tags got removed

This is the meta tag
<META http-equiv=”refresh” content=”5;URL=”>

3 Bill May 18, 2010 at 2:44 am

I’ve used this many times but on this particular site which I did not create a new window opens after a form submission. I’d like it to just come back to the page and not open a new window. Any suggestions? Thanks.

4 tab_Da_man August 26, 2008 at 1:41 pm

the nice thing about a redirect done in php is it is unstoppable. html or javascript redirects

5 kid June 17, 2011 at 1:46 am

nothing at all

6 Tams August 30, 2008 at 6:53 pm

@tab_Da_man: Not so true. lynx, for exmple, asks you if it should follow the redirect.

7 Dave January 14, 2009 at 5:49 pm

When I use this method to redirect I get a 403 error in the browser. AM I missing something?


8 Dave January 15, 2009 at 3:16 pm

Turned out to be a mod_security issue. It’s working now.

9 Chris February 4, 2009 at 6:09 pm

Using a meta tag for a redirect is quite “expensive”, especially for a busy website.

For a simple redirection, it’s much more efficient to use the mod_alias redirect functionality




Redirect 301 /

10 Chris February 4, 2009 at 6:10 pm

Gah. The redirect example didn’t show…

Redirect {optional http response code} {redirect from here} {to here}

11 Salsan Jose February 23, 2009 at 2:22 pm

header(“Location: post.php?id=120″);

This is the method which i am using now to pass values between two pages.
This is not a secure way.
Insted of that i want to “post” values while redirecting.

It will be helpfull to me..

12 Nate March 10, 2009 at 1:58 am

I’m currently using Presta Cart and I want to re-write the order.php file to redirect certain item numbers to different websites BUT still allow items that aren’t included on the list to be sent to the normal online checkout.

If you think you can help me with this please send me an email I will get you all the info! Thanks


13 maan March 14, 2009 at 8:20 am

“how can i do to redirect all the 404 errors (Page not found) to the index of my website.”

Have a file at in the public_html or htdocs folder of your website called .htaccess with this in it:

ErrorDocument 404 /index.php

14 efan October 5, 2009 at 11:42 am

I want to show some data with using redirect script. It like this :

But the problem, can I add the $jdl2 on the header?how’s the script it should be?
Thank you.

15 efan October 5, 2009 at 11:47 am

The Script I post before do not appear, maybe this work

I use this on my local connection.

16 Michael February 26, 2010 at 8:00 pm

not as good as Power Redirector but it’s free, thanks!

17 steve May 10, 2010 at 7:24 pm

? I’d make a big bet that “Power Redirector” uses one of, if not all of, these methods. Sometimes getting down and dirty is where the real power is.

18 michael May 23, 2010 at 7:23 am

Thanks for advice, I’ll try to my website and done…

Great Job

19 crazyblogger June 8, 2010 at 6:08 am

I have one question though. If the visitor clicks on back button then what happens? Where will he go?

20 Rekha kiran June 22, 2010 at 12:44 pm

Now working fine thnx……..

21 Ben June 27, 2010 at 6:20 pm

Can anyone please tell me what’s wrong with the following code:

$review_url = 'http://' . $_SERVER['HTTP_HOST'] . '/show_ad.php?job_id=' . $job_id . '&region_id=' . $region_id ;
header('Location: ' . $review_url);

As I get the very irritating “Warning: Cannot modify header information – headers already sent” message.

22 roshan June 30, 2010 at 1:51 pm

Data sending is not allowed with header……

23 arjun February 17, 2011 at 10:45 am

nothing wrong i have tested your code

24 Magnacarta April 22, 2011 at 7:57 pm

For future reference, can’t put any code before headers other than <?php.

25 arjun April 23, 2011 at 5:08 am

yeah you are correct you can use output buffering to send output before redirect

26 Yohan July 1, 2010 at 4:37 am

Hi, I am trying to lean some php/mysql + js. My problem is: I am trying to display php/mysql output on a mouseover. But when I use the below mention code, result is displayed in a new page instead of displaying in the same page. Hope you get what I mean… Than you in advance. Below is my code

function newDoc(mID){
        var imid=SLdata[mID][0];
        location.assign("http://localhost/logposts/viewImage.php?imid=" +imid);
        return true;
function tellMe(MyDistID){
        var hoverName=SLdata[mID][1];
        var imid=SLdata[mID][0];;
        var hoverValue=SLdata[mID][0];
        document.getElementById('province-Id')'Name of the disctrict: '+hoverName);

I have an SVG map. When I mouseover map/Disctricts I want to display some images related to that district on side of the map. Therefore the images should not open in a new window.

Thank you

27 sikandar hayyat July 14, 2010 at 10:23 am

I want to redirect to antoher page. I use this statement in my if condition.. EVERY TIME condiotin is true but this error occurs. I AM SICK OF THIS

Warning: Cannot modify header information – headers already sent by (output started at C:\xampp\htdocs\Unnamed Site 2\work\databasecon\dbcon.php:12) in C:\xampp\htdocs\Unnamed Site 2\work\save_userdata.php on line 23

28 Pramod December 5, 2010 at 6:48 am

Most of the guys who start their work in PHP end up with this problem at some point or the other… I could not reply to all the other posts.. This one in particular bugged me initially..!

The header function can be used only if the page from which is routed has not modified even a single line in its page(i.e no echos used before it and no html tags before it) and many at times even when every thing is fine u end up getting this error..
The best alternative is that instead of the header function just echo a javascript tag which does the same job.

the sample usage is as shown below

echo “location.href=’Redirec_TO_This_Page.php';”;

29 BrendenAC August 9, 2010 at 4:19 am

is it possible to have an “if” function and if its true it redirects to that page.

like i’m sending text from a form to be $url
and i want that to show up in an iframe on the original page
so i want the php handeler to redirect to $url

Is this possible?

30 Jose from Capital Pawn Shop August 11, 2010 at 10:40 pm

Brilliant help. I am going to use javascript to make a url redirect since…

PHP keeps giving you a header error…i.e. headers have already been submitted.

31 pradeep August 14, 2010 at 11:39 am

good evening,
how to pass array variable from one page to another page with header function.
plz tell me immediately.

32 kj December 28, 2010 at 8:54 am

How to do changes in PHP page.

33 Sniper January 27, 2011 at 1:07 pm

Thanks for this code it helps alot

34 Gary March 2, 2011 at 11:52 pm


I have a link website/#jump-to-bottom-of-page, this link actually takes me to my home page versus to the bottom of the page.. I have no clue on where to look to fix it..

When a person clicks on the link it should take them to the bottom… anyone have any clue on where to look to fix..

I guess I should strip the page of everything: headers, etc..

35 tanvir May 3, 2011 at 8:07 am

after dis hw can i redirect this page to another site?please someone finish my script…..

36 sulaiman May 4, 2011 at 7:03 pm

Warning: Cannot modify header information – headers already sent by (output started at H:\wamp\www\Pos-arif\admin\include\sidebar.php:21) in H:\wamp\www\Pos-arif\include\functions.php on line 19

37 sulaiman May 4, 2011 at 7:04 pm

Warning: Cannot modify header information – headers already sent by (output started at H:\wamp\www\Pos-arif\admin\include\sidebar.php:21) in H:\wamp\www\Pos-arif\include\functions.php on line 19

why this always dam show..

38 rimon May 21, 2011 at 11:41 am

how to use java script in php. help me

39 sonu August 8, 2011 at 12:01 pm

use script tag in echo like this
echo “alert(‘Example :-use js in php’)”;

40 hiren October 17, 2011 at 10:49 am

but how to write js code in php

41 Marc Lawrence May 24, 2011 at 7:21 am

Thanks I been looking for this :D

42 marquise June 11, 2011 at 5:49 pm

im trying to find something that lets me put a hyperlink on my site and when it redirects it keeps them on my site and loads the other site under a nav bar type thing

43 Shel July 25, 2011 at 12:33 pm

I have a registration form that sends an email to me when it is submitted. Right now it goes to my home page but I want it to go to my thanks page.

44 JimB October 24, 2011 at 5:15 pm

Works great. Thanks!

45 Claud October 25, 2011 at 5:31 am

Perfect, search it: “HTTP/1.1 410 Gone”


46 Dwight December 10, 2011 at 4:58 am

Im looking for a if else redirect code. Example of what I want to do:
To stop a user from entering a page directly via it’s URL, user must first agree to terms.
So lets say, agreement var=1 from first page
Second page looks for var=1 to continue loading page.
If var=0, redirect to first page.

47 Dwight December 10, 2011 at 5:54 am

Thanks, found my answer. This closes the backdoor and forces user to take the path laid out for them by checking to see if they came from a specific URL .

48 Mark December 19, 2011 at 7:54 pm

@ Dwight. Please do tell your solution. I have the exact same issue.
I want to add people to MySql Database. This else command is for successfully signing up for the newsletter, and is the else command to send directly to the landing page I have created.

My code:

else {
$sql_insert = mysql_query("INSERT INTO newsletter (name, email, dateTime) VALUES('$name','$email',now() )") or die (mysql_error());
$msg_to_user = 'Thanks ' . $name . ', you have been added successfully.';
$name = "";
$email = "";

49 Dwight January 24, 2012 at 2:05 pm

I place this on top of page. User must come from “”, If not, they are redirected. If they did come from, then they continue to load current page.

50 delhiwonders December 29, 2011 at 7:38 am

its very useful thanks…

51 Raghibsuleman December 29, 2011 at 7:39 am

Thanks for sharing, good work..

52 manchester escort January 16, 2012 at 1:38 pm

thanks, i have created more problem when our website url read google two types first with www. and second without www. then i have created more problem but today when i search on google search engine then found your site, your redirect script,

thanks today i have done

thanks your team


53 Ajit January 31, 2012 at 12:41 pm

Good Work

54 vishnu February 11, 2012 at 11:21 am

sir i want 2 know how a page can redirect when login but that page should not have 2 run separately without login.

55 mac March 20, 2012 at 3:45 pm

Thank you it have worked fine for me

56 jumat sidik April 21, 2012 at 8:26 am

nice tutorial :-)
thank’s you.

57 junedc May 16, 2012 at 9:41 pm

hi it works but how if i want to open a new window instead ?

58 blogzpoint August 12, 2012 at 1:47 pm

nice tutorial :)

59 sanjay gupta August 29, 2012 at 7:20 am

use php variable like this in jjavascript query string
echo “window.location=’customer_detail.php?customer_id=”.$customer_id.”‘”;

60 reenu November 19, 2012 at 10:48 am

I wanna use navigation on my php page as next and previous button plz help me…. n i dnn wnn to link wid othr page…

61 mortimernova May 7, 2013 at 2:33 pm

is that even a sentence? moron…

62 Raul Batter January 19, 2013 at 12:07 am

Hello, in some cases when I first go to this web site I get immediately redirected to a different page which feels very weird. You may well want to take a look at why this is taking place! Thanks

63 mortimernova May 7, 2013 at 2:34 pm

very simple and well written script. this worked perfectly for my multi-index redirects.

64 Giftvincy May 15, 2013 at 12:28 pm

Really clean and informative article.
But, I have a doubt about the purpose of using exit command?

Will it be executed or just to mention that the following lines are not going to be executed?

65 james June 3, 2013 at 11:43 am

Hello :)

Apologies if this sounds particularly dense owing to the simplicity of the task but…

My php complete with link to a new page is within an Iframe (on a Wix site). I’d like to get this link to open in the parent page. Currently the link opens but within the Iframe. Does anyone know how to do this?

Any help would be very much appreciated!

66 mahi August 17, 2013 at 6:38 am

“how to display data from different table on same page but remove previous data on that same page means when click on any link always display content on same page and omit previously shown data on that page in php.”

67 Harsh October 7, 2013 at 10:56 am






in the above code my databse get store but it is not redirecting on the url i mention in the header pls can anyone help me on this on my localwap server it runs pefect but i tried to uplado on 3 diff server i get same error

68 savi October 15, 2013 at 8:36 am

i m not geting error bt page is not redirected to profile,php
below is my code

	$sql="select * from register Where ConfirmEmail='$email_id' AND ConfirmPassword='$password'";
	die("An Error".mysql_error());
		$_SESSION["mid"]= $row["ID"];
		$q = "UPDATE register SET Thislogin=NOW(),logtime='$time',login_status='$login_status' WHERE ConfirmEmail='$email_id' AND ConfirmPassword='$password'";
			$status_msg="Your profile is wating for approval";
			$msg="Invalid Email ID & Password Please Re-enter!";

69 Johan de Kock October 20, 2013 at 5:03 am

Using the mentioned php-script (header();), how do one redirect to different domains/URL’s based on the specific user login, e g if Mr A or Mrs A login, he or she is redirected to http://www.mypage_A/, and if Mr B or Miss B login, he or she is redirected to http://www.mypage_B/, etc. (Assuming that these users will each use different computers (with different IP-addresses), different (physical) locations and blocked the use of cookies, and the only reliable way to determine to which domain/URL to redirect them to is based on their usernames (and passwords) (at login).

70 Altaf Hussain October 28, 2013 at 8:01 am

I am using facebook API for one of my project. But when I redirect to, it sends me to… but I dont want so. I needed the web version. How to redirect to its web version. Please suggest.

71 Steve December 9, 2013 at 9:36 am

Thank you for this information. I now have a fully functional php email script in a popup window that redirects when finished and self closes. Awesome!

All I need now is to figure out how to get php to parse the attachment using the mail() function. I have been bashing my head over that one for a few days now as the coding examples online do not work.

Comments on this FAQ are closed. If you'd like to continue the discussion on this topic, you can do so at our forum.

Tagged as: ,

Previous Faq:

Next Faq: