- Как в PHP реализовать переход на другую страницу?
- Использование функции PHP header() для редиректа URL-адреса
- Вывод кода JavaScript-редиректа с помощью функции PHP echo()
- Использование метатегов HTML для редиректа
- Заключение
- php redirect – How to, Examples, Issues & Solutions
- Setting up php redirect header
- Relative urls in php redirect
- php redirect using session data
- Header already sent error in php redirect
- Internal server error in php redirect
- Replace php redirect header
- php redirect with time delay
- Redirecting using other methods
- How to Redirect a Web Page with PHP
- Using the header() Function
- Using a Helper Function
- JavaScript via PHP
Как в PHP реализовать переход на другую страницу?
Предположим, что вы хотите, чтобы пользователям, которые переходят на страницу https://example.com/initial.php отображалась страница https://example.com/final.php . Возникает вопрос как в PHP реализовать редирект на другую страницу?
Это можно сделать с помощью несколько методов PHP , JavaScript и HTML . В этой статье мы расскажем о каждом из методов, которые можно использовать для PHP перенаправления на другую страницу.
Вот несколько переменных, которые мы будем использовать:
Использование функции PHP header() для редиректа URL-адреса
Если хотите добавить редирект с initial.php на final.php , можно поместить на веб-странице initial.php следующий код. Он отправляет в браузер новый заголовок location :
Здесь мы используем PHP-функцию header() , чтобы создать редирект. Нужно поместить этот код перед любым HTML или текстом. Иначе вы получите сообщение об ошибке, связанной с тем, что заголовок уже отправлен. Также можно использовать буферизацию вывода, чтобы не допустить этой ошибки отправки заголовков. В следующем примере данный способ перенаправления PHP показан в действии:
Чтобы выполнить переадресацию с помощью функции header() , функция ob_start() должна быть первой в PHP-скрипте . Благодаря этому не будут возникать ошибки заголовков.
В качестве дополнительной меры можно добавить die() или exit() сразу после редиректа заголовка, чтобы остальной код веб-страницы не выполнялся. В отдельных случаях поисковые роботы или браузеры могут не обращать внимания на указание в заголовке Location . Что таит в себе потенциальные угрозы для безопасности сайта:
Чтобы прояснить ситуацию: die() или exit() не имеют отношения к редиректам. Они используются для предотвращения выполнения остальной части кода на веб-странице.
При PHP перенаправлении на страницу рекомендуется использовать абсолютные URL-адреса при указании значения заголовка Location . Но относительные URL-адреса тоже будут работать. Также можно использовать эту функцию для перенаправления пользователей на внешние сайты или веб-страницы.
Вывод кода JavaScript-редиректа с помощью функции PHP echo()
Это не является чистым PHP-решением . Тем не менее, оно также эффективно. Вы можете использовать функцию PHP echo() для вывода кода JavaScript , который будет обрабатывать редирект.
Если воспользуетесь этим решением, то не придется использовать буферизацию вывода. Что также предотвращает возникновение ошибок, связанных с отправкой заголовков.
Ниже приводится несколько примеров, в которых использованы разные методы JavaScript для редиректа с текущей страницы на другую:
self.location='https://example.com/final.php';"; echo ""; echo ""; echo ""; ?>
Единственным недостатком этого метода перенаправления на другой сайт PHP является то, что JavaScript работает на стороне клиента. А у ваших посетителей может быть отключен JavaScript .
Использование метатегов HTML для редиректа
Также можно использовать базовый HTML для выполнения редиректа. Это может показаться непрофессиональным, но это работает. И не нужно беспокоиться о том, что в браузере отключен JavaScript или ранее была отправлена ошибка заголовков:
Также можно использовать последнюю строку из предыдущего примера, чтобы автоматически обновлять страницу каждые « n » секунд. Например, следующий код будет автоматически обновлять страницу каждые 8 секунд:
Заключение
В этой статье я рассмотрел три различных метода перенаправления с index php , а также их преимущества и недостатки. Конкретный метод, который стоит использовать, зависит от задач проекта.
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.
How to Redirect a Web Page with PHP
This short snippet will show you multiple ways of redirecting a web page with PHP.
So, you can achieve redirection in PHP by following the guidelines below.
Using the header() Function
This is an inbuilt PHP function that is used for sending a raw HTTP header towards the client.
The syntax of the header() function is as follows:
header( $header, $replace, $http_response_code )
Also, it is likely to apply this function for sending a new HTTP header, but one should send it to the browser prior to any text or HTML.
Let’s see how to redirect a web page using the header() function:
header('Location: //www.w3docs.com'); // or die(); exit(); ?>
As you can notice, exit() is used in the example above. It is applied to prevent the page from showing up the content remained (for instance, prohibited pages).
Also, you can use the header() function with ob_start() and ob_end_flush() , like this:
ob_start(); //this should be first line of your page header('Location: target-page.php'); ob_end_flush(); //this should be last line of your page
Using a Helper Function
Here, we will demonstrate how to use a helper function for redirecting a web page. Here is an example:
function Redirect($url, $permanent = false) < header('Location: ' . $url, true, $permanent ? 301 : 302); exit(); > Redirect('//www.w3docs.com/', false);
All HTTP status codes are listed at HTTP Status Messages
Note that this function doesn’t support 303 status code!
Let’s check out a more flexible example:
function redirect($url, $statusCode = 303) < header('Location: ' . $url, true, $statusCode); die(); >
In some circumstances, while running in CLI (redirection won’t take place) or when the webserver is running PHP as a (F) CGI, a previously set Statusheader should be set to redirect accurately.
function Redirect($url, $code = 302) < if (strncmp('cli', PHP_SAPI, 3) !== 0) < if (headers_sent() !== true) < if (strlen(session_id()) > 0) < // if using sessions session_regenerate_id(true); // avoids session fixation attacks session_write_close(); // avoids having sessions lock other requests > if (strncmp('cgi', PHP_SAPI, 3) === 0) < header(sprintf('Status: %03u', $code), true, $code); > header('Location: ' . $url, true, preg_match('~^30[1237]$~', $code) > 0 ? $code : 302); > exit(); > > ?>
JavaScript via PHP
Here, we will provide you with an alternative method of redirection implementing JavaScript via PHP. In JavaScript, there is a windows.location object that is implemented for getting the current URL and redirecting the browser towards a new webpage. This object encompasses essential information about a page (for example, href, a hostname, and so on).
This is how to redirect a web page using window.location:
html> html> head> title>window.location function title> head> body> p id="demo"> p> script> document.getElementById("demo").innerHTML = "URL: " + window.location.href + ""; document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML + "Hostname: " + window.location.hostname + ""; document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML + "Protocol: " + window.location.protocol + ""; script> body> html>
To conclude, let’s assume that in this short tutorial, we provided you with multiple methods to redirect a web page with PHP. Also, you can find information on how to redirect web pages with HTML, JavaScript, Apache and Node.js.