<- Back George Lindemann Jr.'s father

How to re-direct with PHP

No picture found

Posted in: Learned along the way
By: Blockcoder ( Admin ) / October 26th, 2011
Stats: no comments / Views: 100


Hi again. Today we are going to teach you a simple php trick! After that you have the answer for “how to re-direct with php?” or maybe “how to automatically refresh a page with php?“. Okay, so what do we have…

The answer is php header(); function!

But how it is used?

  • You can re-direct users using whole address for example: http://www.yoursite.com/index.php
  • Or you can use a relative address like: /tutorials/php_css.html
  • Can be used with “refresh” attribute to delay the directing
  • The parameter which will re-direct is called “Location”

Everyone else is using “Location” parameter but I’m used to use “URL”, it does the same thing.

You can use the URL and Location attributes like this:

//whole address
header( 'url=http://www.blockcoders.net' );

header( 'url=/tutorials/styles.css' );

// using the Location attribute
header( 'Location: http://www.google.com' );

And after that, your browser will take you to index of blockcoders or to /tutorials/styles.css.

You can also refresh page with header(); function

You can delay ( or refresh ) the re-directing:

//re-direct after 10 seconds
header( 'refresh: 10; url=http://www.blockcoders.net' );
<h1>Re-directing in 10 seconds...</h1>

//re-directing after 3 seconds
header( 'refresh: 3; url=styles.css' );
<h1>Re-directing in 3 seconds...</h1>

Now header function will take you to index of blockcoders after 3 seconds ( or to the styles.css in 10 seconds… ) and it will show the message “Re-directing in X seconds…” while the seconds are ticking. You can also use “refresh: 0″ when user is directed immediately without any messages!

Please, remember to send the headers BEFORE everything else, it won’t work either. Read our other tutorial about “Warning: Cannot modify header information…“.

You can do many different things with php header(); function like prompt user to save the data you are sending or you can disable proxies and clients — but they belong to other category, so we are not going them through today. Maybe next time! :)

This block of code ends here. Thanks for reading!

Leave a Reply

Your email address will not be published. Required fields are marked *


* Copy this password:

* Type or paste password here:

1,124 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>