Php location header back

php redirect – How to, Examples, Issues & Solutions

php redirect is a convenient way to redirect https requests to another page. Learn about correct syntax, response code , common errors using session data and time delayed redirection.

php redirect to another page on same or different website is handled by php headers. php header() sends a raw HTTP header which is used to redirect php pages to other locations along with several other function

php header syntax :

header ( string $header [, bool $replace = TRUE [, int $http_response_code ]] ) : void

header is the header string which is ‘Location:’ for php redirect and it sends headers back to browser.

replace parameter is TRUE by default, but can be FALSE if you want to send multiple headers and don’t want to replace send header with first.

response code – default response code is 302,

browsers and search engines treat these response code differently, search engines take a 301 as permanent move to new page and update page rank, this can help in maintaining same search ranking for the page. Browsers use 30x code to determine how long or what to cache for these pages. It makes sense to specify the status code explicitly for php redirects depending on the requirements.

Setting up php redirect header

A php header redirect can be setup as in following example with default parameters.

or by specifying custom parameters

header(“Location: http://example.com”,TRUE,301);
exit;
?>

The url can be relative to the root domain if it is being redirected to same site

the exit function after the redirect is to ensure the further execution of php script stops and exists.

Relative urls in php redirect

The redirect urls can be constructed using php environment variables as in following example:

$url = ‘http://’ . $_SERVER[‘HTTP_HOST’]; // Get server
$url .= rtrim(dirname($_SERVER[‘PHP_SELF’]), ‘/\\’); // Get current directory
$url .= ‘/relative/path/to/page/’; // relative path
header(‘Location: ‘ . $url, TRUE, 302);

php redirect using session data

session data can be used to redirect based on valid user credentials. However care needs to be taken that search bots and other bots may not looks at the session data and may end up fetching your pages.

if (!isset( $_SESSION[“authorized-user”]))
header(“location. /”);
exit();
>

Header already sent error in php redirect

This is very common error and sometime difficult to debug. The root cause of this error is that php redirect header must be send before anything else. This means any space or characters sent to browser before the headers will result in this error.

Читайте также:  Где можно применить питон

Like following example, there should not be any output of even a space before the headers are sent.

Even a Byte Order Mark can cause this issue when the text encoding is utf8-BOM, this can be fixed by saving again with encoding as utf8 without BOM in text editors.

Internal server error in php redirect

The directive Location is sensitive to the placement of colon, The colon : should always be placed next to Location as Location: , any space between Location and : can result in malfunction and internal server error.

This is NOT correct, notice the placement of colon,

Correct way is :

Replace php redirect header

the headers can be replaced with another entry as long as nothing is sent to browsers

header(“location: page1.php”);
header(“location: page2.php”); //replaces page1.php
exit;
?>

In the following example, headers are not replaced as browser follows the first redirect and then prints the message. No header already sent message here as browser has already redirected before coming to second redirect.

header(“location: page1.php”);
echo “moving to page 2”
header(“location: page2.php”); //replaces page1.php
?>

php redirect with time delay

As you can’t send anything before php headers, to delay a redirect and display a message, you will have to user refresh function instead of Location

The following examples redirects to page after 5 seconds and displays a message during the 5 sec. delay.

Redirecting using other methods

following examples avoid headers already sent issues.

1. php redirect using ob_start() and ob_end_flush() php functions

ob_start(), output buffer keeps everything in buffer without sending or displaying until it is flushed

ob_start(); //this has to be the first line of your page
header(‘Location: page2.php’);
ob_end_flush(); //this has to be the last line of your page
?>

2. Redirect using javascript

This simple example does the redirection using javascript.

Источник

PHP Redirect Tutorial

PHP redirect

PHP Redirect

In this tutorial you’ll learn how to redirect in PHP.

  • How to redirect to another URL by sending a location header.
  • How to redirect with or without using the header() function.
  • The most common mistake and how to avoid it.
  • …and more.

How redirection works.

Redirection happens when you open a web page and you are sent automatically to a different URL.

Redirections can happen at two stages.

Let’s say that you go to page A, and then you are redirected to page B. This redirection can happen:

In the first case, you are immediately sent to page B before any content is received from page A.

An example of this is a form submission page: when you fill and submit the form, the page automatically redirects you to a different “thank you page”, without showing the form again.

In the second case, you open the first URL and your browser loads page A. After that, your browser is sent to page B, immediately or after a timeout.

Читайте также:  Javascript date function gettime

This type of redirection happens often after an online payment: the payment confirmation page tells you that you are going to be redirected to the store’s page in a few seconds.

Now, let’s see how you can perform these operations in PHP.

How to redirect in PHP: the header() function.

In PHP, you can do a page redirect with the header() function.

Let’s see an example right away:

header('Location: https://www.google.com/'); die(); 

The argument of the header() function is a string made of two parts:

As soon as the header() function is executed, the remote user is redirected to the new URL.

This is an “immediate” redirect: the user does not receive any web content before the redirection.

The destination URL should be an absolute URL, like: https://www.google.com.

However, most browsers accept relative URLs too. This can be handy if you want to redirect to a relative URL on your own website.

$thankyou_page = 'thank_you.php'; if ($form_data_valid)

You should always call die() after header(). Otherwise, the script execution may continue after the redirection.

Redirection and output.

The header() function sends an HTTP header to the browser. This header tells the browser to go to a different URL.

It’s important to call header() before any output is sent to the browser, including:

To better understand what that means, here are three wrong examples.

Wrong example #1: HTML output before header()

Wrong example #2: text printed with PHP before header()

echo 'Redirecting. '; header('Location: https://www.google.com/'); die(); 

Wrong example #3: a white line before header() (this happens if you leave one or more empty lines before the PHP opening tag)

But what if the redirection comes after some output has already been sent?

In these cases, you have three choices:

  • Save the output in a variable (instead of echoing it).
  • Use output buffering.
  • Use front-end redirection.

The first solution is the easiest. Basically, instead of using echo or similar commands, you save all the output inside a variable.

Then, you output the variable only if no redirection occurs.

 $html = ' '; $redirect = TRUE; if ($redirect) < header('Location: https://www.google.com/'); die(); >else

Now let’s look at output buffering.

Output buffering makes your PHP script keep all the output until the end of the script.

So, basically, it does exactly what you need without having to use variables explicitly.

Using output buffering is very simple. You just need to call ob_start() when you want the buffer to begin, and then ob_end_flush() when you want all the buffer to be sent.

Now, let’s see how front-end redirection works.

Redirect with an HTML meta tag.

Another way to perform a redirection is to use a specific HTML meta tag.

This tag must be added to the HTML page that you generate with PHP. After the browser has loaded the page, it reads the redirection tag and executes it.

Читайте также:  Php buttons how to

Contrary to the PHP redirect, this is not an immediate redirect, because the browser loads the first page before performing the redirection.

The redirection tag is an HTML meta tag with the http-equiv=”refresh” attribute, and the content attribute containing:

  • A number that tells how many seconds to wait before the redirection. If set to 0, the redirection is immediate. This number is followed by a ;
  • The new URL, in the form url=new_url. If this is not set, then the current URL is loaded again (so, in practice, it works as an auto-refresh).

Redirect with JavaScript.

Instead of using the HTML meta tag, you can also use JavaScript to perform a redirect.

In JavaScript, the redirection command is performed by the window.location.replace() function.

You need to make the page execute this function when you want to perform the redirection, which is usually right after the page is loaded.

If you want to redirect after a timeout, you can simply use the standard JavaScript setTimeout() function.

     

You will be redirected in 5 seconds.

HTTP redirect codes.

Let’s go back to the PHP header() redirection.

When you redirect using the header() function, you can also specify an optional redirection HTTP code.

Redirection is done for two reasons:

  1. You simply want to move the user to a different page, like in the form submission example.
  2. You have moved an URL to a different address, so you want to redirect all the requests to the first URL to the second.

When you send the redirection header, you can also tell the browser the reason why this redirection happens by sending the appropriate HTTP header.

This is mostly relevant for SEO purposes.

In particolar, you want to send:

  • a 301 code if the page has moved permanently to the new URL
  • a 302 code if the page has moved temporarily to the new URL

By default, the header() function sends a 302 code – a temporary redirection.

If you want to send a 301 code instead, because the old URL has moved permanently to the new URL, then you must specify it explicitly.

You can do it by sending a 301 header before the redirection header. Like this:

You can also use the third header() argument to specify the response code:

Conclusion

In this tutorial you learned how to redirect with PHP.

You saw how to use the header() function and how to avoid sending output before the redirection.

You also saw how to perform front-end redirection with an HTML meta tag and with JavaScript, and how to specify the redirection type (301 and 302).

Do you have any questions? Then leave a comment below and I’ll get back to you.

And be sure to subscribe to my free newsletter to get my weekly tips!

Источник

Оцените статью