PHP Redirect Location url

PHP Redirect Syntax

header("Location: target-url");

In the above syntax of PHP redirect, we need to replace with a valid URL to which we want to move. We can specify either absolute URL or relative URL for this location header. If we specify relative URL, it will search for the page in our domain where we exist.

Note: Before specifying page URL for location header, we should make sure that the page exists.

Caution before Redirect

Before executing PHP redirect, we should ensure about, no output is sent to the browser before the line where we call the header() function. For example,

echo "PHP Redirect";

This script will display the following warning notice to the browser.

Warning: Cannot modify header information - headers already sent by (...

It is not only applicable for header function, rather for all the PHP functions like set_cookie(), session_start() and etc., whatever can modify the header. For that, we should remove all content which will stop sending location header to the browser.

Possible Ways of Sending Output

  • HTML content like text or tags.
  • Unnecessary white spaces before PHP delimiters.
  • PHP error or warning notices that occur before calling redirect.
  • PHP print statements, like, echo(), print().

Safety Measures from output being Sent before PHP Redirect

  • Since HTML content should be sent before the redirect, we can separate PHP logic from HTML content.
  • For being in the safety side we can put exit command after redirect statement of PHP file. For example,
  • We can enable PHP output buffering to stop sending output to the browser and stored into a buffer instead. For example,
    ob_start(); // Output Buffering on

You may also like...

Leave a Reply

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

Show Buttons
Hide Buttons
Social Media Auto Publish Powered By :