PHP Redirect To Another URL / Web Page Script Example

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
Difficulty Easy (rss)
Root privileges No
Requirements php
Time 1m
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

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 71 comments so far... add one

CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04

Comments on this entry are closed.

  • sp2hari Aug 26, 2008 @ 11:02

    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 ("");
  • sp2hari Aug 26, 2008 @ 11:03

    Sorry, I guess the meta tags got removed

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

    • Bill May 18, 2010 @ 2:44

      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.

  • tab_Da_man Aug 26, 2008 @ 13:41

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

    • kid Jun 17, 2011 @ 1:46

      nothing at all

  • Tams Aug 30, 2008 @ 18:53

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

  • Dave Jan 14, 2009 @ 17:49

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


  • Dave Jan 15, 2009 @ 15:16

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

  • Chris Feb 4, 2009 @ 18:09

    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 /

  • Chris Feb 4, 2009 @ 18:10

    Gah. The redirect example didn’t show…

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

  • Salsan Jose Feb 23, 2009 @ 14:22

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

  • Nate Mar 10, 2009 @ 1:58

    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


  • maan Mar 14, 2009 @ 8:20

    “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

  • efan Oct 5, 2009 @ 11:42

    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.

  • efan Oct 5, 2009 @ 11:47

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

    I use this on my local connection.

  • Michael Feb 26, 2010 @ 20:00

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

    • steve May 10, 2010 @ 19:24

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

  • michael May 23, 2010 @ 7:23

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

    Great Job

  • crazyblogger Jun 8, 2010 @ 6:08

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

  • Rekha kiran Jun 22, 2010 @ 12:44

    Now working fine thnx……..

  • Ben Jun 27, 2010 @ 18:20

    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.

    • roshan Jun 30, 2010 @ 13:51

      Data sending is not allowed with header……

    • arjun Feb 17, 2011 @ 10:45

      nothing wrong i have tested your code

    • Magnacarta Apr 22, 2011 @ 19:57

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

      • arjun Apr 23, 2011 @ 5:08

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

  • Yohan Jul 1, 2010 @ 4:37

    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

  • sikandar hayyat Jul 14, 2010 @ 10:23

    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

    • Pramod Dec 5, 2010 @ 6:48

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

  • BrendenAC Aug 9, 2010 @ 4:19

    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?

  • Jose from Capital Pawn Shop Aug 11, 2010 @ 22:40

    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.

  • pradeep Aug 14, 2010 @ 11:39

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

  • kj Dec 28, 2010 @ 8:54

    How to do changes in PHP page.

  • Sniper Jan 27, 2011 @ 13:07

    Thanks for this code it helps alot

  • Gary Mar 2, 2011 @ 23:52


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

  • tanvir May 3, 2011 @ 8:07

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

  • sulaiman May 4, 2011 @ 19:03

    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

  • sulaiman May 4, 2011 @ 19:04

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

  • rimon May 21, 2011 @ 11:41

    how to use java script in php. help me

    • sonu Aug 8, 2011 @ 12:01

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

      • hiren Oct 17, 2011 @ 10:49

        but how to write js code in php

  • Marc Lawrence May 24, 2011 @ 7:21

    Thanks I been looking for this :D

  • marquise Jun 11, 2011 @ 17:49

    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

  • Shel Jul 25, 2011 @ 12:33

    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.

  • JimB Oct 24, 2011 @ 17:15

    Works great. Thanks!

  • Claud Oct 25, 2011 @ 5:31

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


  • Dwight Dec 10, 2011 @ 4:58

    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.

  • Dwight Dec 10, 2011 @ 5:54

    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 .

    • Mark Dec 19, 2011 @ 19:54

      @ 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 = "";
      • Dwight Jan 24, 2012 @ 14:05

        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.

  • delhiwonders Dec 29, 2011 @ 7:38

    its very useful thanks…

  • Raghibsuleman Dec 29, 2011 @ 7:39

    Thanks for sharing, good work..

  • manchester escort Jan 16, 2012 @ 13:38

    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


  • Ajit Jan 31, 2012 @ 12:41

    Good Work

  • vishnu Feb 11, 2012 @ 11:21

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

  • mac Mar 20, 2012 @ 15:45

    Thank you it have worked fine for me

  • jumat sidik Apr 21, 2012 @ 8:26

    nice tutorial :-)
    thank’s you.

  • junedc May 16, 2012 @ 21:41

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

  • blogzpoint Aug 12, 2012 @ 13:47

    nice tutorial :)

  • sanjay gupta Aug 29, 2012 @ 7:20

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

  • reenu Nov 19, 2012 @ 10:48

    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…

    • mortimernova May 7, 2013 @ 14:33

      is that even a sentence? moron…

  • Raul Batter Jan 19, 2013 @ 0:07

    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

  • mortimernova May 7, 2013 @ 14:34

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

  • Giftvincy May 15, 2013 @ 12:28

    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?

  • james Jun 3, 2013 @ 11:43

    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!

  • mahi Aug 17, 2013 @ 6:38

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

  • Harsh Oct 7, 2013 @ 10:56






    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

  • savi Oct 15, 2013 @ 8:36

    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!";
  • Johan de Kock Oct 20, 2013 @ 5:03

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

  • Altaf Hussain Oct 28, 2013 @ 8:01

    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.

  • Steve Dec 9, 2013 @ 9:36

    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.

Use HTML <pre>...</pre> for code samples. Problem posting comment? Email me @