Redirect after header php

Header() in PHP – Refresh (Redirect) to Location (URL) in X seconds

Recently, I was designing a simple user system for one of my websites. Obviously, it had login and logout feature. Now when I designed the login page, on a successful login, I wanted the user to be redirected to index page without displaying any kind of message. Whereas when I designed the logout page, I wanted the page to display “Logged out successfully” message for 5 seconds, then redirect to index page.

Now you can achieve this in HTML using the meta tag which I will be showing at the end of this tutorial, but if you wish to do this in PHP, it’s a little bit tricky. Following are the two cases and their solutions.

Case 1 : Redirect a page to a URL without waiting in PHP.

Say, after a successful login, you wish to redirect the user to index.php without waiting. Following is the code that can be used for the same :

Make sure that no text is sent to the browser before this part of the script is executed. Since header() is a function which is used to set “Headers” for a page when it is opened in a browser. In simpler words, when the browser starts receiving data from the server, it takes the header messages first and then the data that is supposed to be displayed. Now, if you send any data to be displayed, obviously you cannot send header messages any longer. So always make it a point to use PHP header() function before sending any kind of data to be displayed.

Case 2 : Redirect a page to an URL after waiting for X seconds in PHP.

Let us take the same example in the above scenario but let’s say that this time you wish to show a message saying logged in successfully, then wait for 5 seconds and redirect to index page. Here’s the code to do it :

Please note that I have used “echo” statement AFTER using “header()” function. I have briefly explained the logic behind this, in Case 1. If you use an echo statement or display any text before setting headers in a PHP page, the header function won’t work. So make sure you first set the headers and then use echo statement.

Bonus Tip 1: HTML code to redirect a webpage after X seconds.

Following is the code to redirect a webpage to an URL (for e.g. http://nimishprabhu.com) after, say, 5 seconds.

Читайте также:  Изменить атрибут html javascript

Just place the above code in the head section of the page i.e. after and before tag. This will refresh (redirect) a page to a specific URL after specified number of seconds.

Bonus Tip 2: Javascript code to redirect a webpage after X seconds.

If you would like to use Javascript for some reason, then you can use setTimeout() function to achieve similar result, provided user has Javascript enabled.

You will replace “https://nimishprabhu.com” with your URL and 5000 (5000 milliseconds i.e 5 seconds) with desired number of milliseconds to wait before redirecting the page.

Hope this article was useful. If you have any doubts, feel free to drop a comment using the form below.

Источник

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.

Читайте также:  Or symbol in java code

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 Redirects – How to Create and Configure them

PHP Redirects – How to Create and Configure them

PHP redirect is a method used to redirect a user from one page to another page without clicking any hyperlinks.

This will be helpful in such circumstances when you want to redirect a certain page to a new location, change the URL structure of a site and redirect users to another website.

Redirection is very important and frequently used in Web Development phases.

There are several reasons to use PHP redirect, including, Merger of two websites, Change of business name, Redirect traffic to updated content and many more.

In this tutorial, we will learn how to redirect PHP page with the header() function.

PHP Redirect Basic Syntax

To use a redirect in PHP, we use a header() function. The header() function is an inbuilt function in PHP which is used to send a raw HTTP header to the client.

Basic syntax of header() function in PHP redirect is shown below:

header( header, replace, http_response_code )

Each parameter is described below:

  • header:
    This is used to hold the header string to send
  • replace:
    Indicates the header should replace a previous similar header, or add a second header of the same type
  • http_response_code:
    This is used to hold the HTTP response code
Читайте также:  Com объект в javascript

PHP Redirect Example

In this section, we will give you a quick example of how to create a redirect using PHP.

In this example, we will create a page1.php that contains code that issues a redirect and page2.php that contains just HTML.

Add the following contents:

Save and close the file. Then, create a page2.php:

Add the following contents:


This my page2


Save and close the file, when you are finished.

Next, you can test the URL redirection by visiting the page1.php at URL http://localhost/page1.php. You will be redirected to the page2.php as shown below:

php-redirect

You can also test the URL redirection with Curl command:

curl -I http://localhost/page1.php

You should see the following output:

HTTP/1.1 302 Moved Temporarily
Server: nginx/1.4.6 (Ubuntu)
Date: Wed, 11 Sep 2019 09:48:42 GMT
Content-Type: text/html
Connection: keep-alive
X-Powered-By: PHP/5.5.9-1ubuntu4.29
Location: page2.php

By default, search engine replies with the default response code 302 while Browser reply with the response code 30x.

If you want to redirect page1.php to another site https://www.webservertalk.com with response code 301 then edit the php1.php file with the following contents:

Add the following contents:

header(«Location: https://www.webservertalk.com»,TRUE,301);
exit;
?>

Save and close the file. Then, check PHP redirect again with the Curl command:

curl -I http://localhost/page1.php

You should see the following output:

HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.6 (Ubuntu)
Date: Wed, 11 Sep 2019 10:21:58 GMT
Content-Type: text/html
Connection: keep-alive
X-Powered-By: PHP/5.5.9-1ubuntu4.29
Location: https://www.webservertalk.com

PHP Redirect with Absolute URL

In the above examples, The URL does not contain a hostname, this will work on modern browser. But, it is better to redirect to an absolute URL.

You can achieve this by editing the page1.php file as shown below:

Make the following chages:

header(‘Location: http://’ . $_SERVER[‘HTTP_HOST’] . ‘/page2.php’);
exit;
?>

Save and close the file when you are finished. Then, you can test it with your web browser or Curl command.

PHP Redirect with Time Delay

You can also redirect PHP page to another page with refresh function instead of Location.

For example, create a page1.php that redirect to page2.php after 10 seconds:

Add the following contents:

header( «refresh:10; url=/page2.php» );
echo «Redirecting in 10 secs.»;
exit;
?>

Save and close the file. Then, check the URL redirection by visiting the URL http://localhost/page1.php. You should see the following page:

Above page indicates that page1.php will redirects after 10 seconds.

Conclusion

In the above tutorial, we have learned how to redirect URL from one page to another with PHP header() function.

I hope you have now enough knowledge on how PHP redirection works. For more information, you can visit the PHP redirect documentation at PHP redirect.

Recent Posts

  • Forcepoint Next-Gen Firewall Review & Alternatives
  • 7 Best JMX Monitoring Tools
  • Best PostgreSQL Backup Tools
  • Best CSPM Tools
  • Best Cloud Workload Security Platforms
  • Best Automated Browser Testing Tools
  • Event Log Forwarding Guide
  • Best LogMeIn Alternatives
  • Citrix ShareFile Alternatives
  • SQL Server Security Basics
  • Cloud Security Posture Management Guide
  • Cloud Workload Security Guide
  • The Best JBoss Monitoring Tools
  • ITL Guide And Tools
  • 10 Best Enterprise Password Management Solutions

Источник

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