Redirect to a URL with PHP

Advertisement

Advertisement

Introduction

In PHP, redirecting is easy with the header() function. We will look at:

  • How to redirect to a URL
  • How to specify the response status code
  • Common mistakes

Example of PHP redirect

There are two common types of redirects:

  • 301 Moved Permanently - Good when you are retiring an old URL
  • 302 Found/Moved Temporarily - Good for temporary redirects and pages that are expected to redirect to different locations

This example redirect to a relative URL of / but it could be a full URL like https://www.devdungeon.com/.

NOTE, this is done by setting an HTTP header. HTTP headers must go at the beginning before any content is returned to the client, so you cannot set a redirect somewhere at the bottom of an HTML file after the close of a </body> tag. It must be done before the first line of <html> is even sent. If you don't, you will get the error message headers already sent.

If you do not specify a status code, redirects default to 302 Found/Temporarily moved.

<?php
// Simplest example. Defaults to 302
header('Location: /');

// Or specify explicit status code
//header('Location: /', TRUE, 301);
//header('Location: /', TRUE, 302);

exit; // If you want to ensure nothing else gets output

Conclusion

After reading this you should:

  • Be able to perform simple redirects with PHP
  • Understand some of the common mistakes
  • Know how to specify the redirect status code

References

Advertisement

Advertisement