PHP Redirect To Another URL / Web Page Script Example

last updated in Categories , , , , ,

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?

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

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.


71 comment

  1. 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. Sorry, I guess the meta tags got removed

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

    1. 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.

  3. 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 /

  4. Gah. The redirect example didn’t show…

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

  5. 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..

  6. 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


  7. “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

  8. 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.

    1. ? 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.

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

  10. 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.

  11. 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

  12. 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

    1. 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’;”;

  13. 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?

  14. 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.

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

  16. Question.

    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..

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

  18. 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

  19. 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..

  20. 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

  21. 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.

  22. 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.

  23. 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 .

    1. @ 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 = "";
      1. 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.

  24. 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


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

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

  27. 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…

  28. 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

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

  30. 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?

  31. 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!

  32. “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.”

  33. 0)





    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

  34. 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!";
  35. 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).

  36. 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.

  37. 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.

    Still, have a question? Get help on our forum!