Тарифы Услуги Сим-карты

Как в PHP задать редирект на другой URL до загрузки страницы

Last modified on February 25th, 2017 by Vincy.

PHP redirect mechanism is used to navigate the user from one page to another without clicking any hyperlinks. This will be helpful in such circumstances where the redirect should be done in the background. For example, when the user is accessing payment gateway, the redirect should automatically be taken place to notify URL using PHP script.

PHP provides predefined function, named header(),for URL redirection. Using this header() function, we need to send location header by specifying URL to which the page should be redirected.

Unlike where there are several ways to handle URL redirect works based on the browser, PHP avoids such confusion and have header() function create the same effect in all browsers. For that only, we have concluded with JavaScript redirect article that server side redirect is preferable.

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"; header("Location: сайт");

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 , 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, header("Location: сайт"); exit;
  • We can enable PHP output buffering to stop sending output to the browser and stored into a buffer instead.

Предположим, что вы хотите, чтобы пользователям, которые переходят на страницу https://example.com/initial.php отображалась страница https://example.com/final.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 для редиректа с текущей страницы на другую:

Единственным недостатком этого метода перенаправления на другой сайт PHP является то, что JavaScript работает на стороне клиента. А у ваших посетителей может быть отключен JavaScript .

Использование метатегов HTML для редиректа

Также можно использовать базовый HTML для выполнения редиректа. Это может показаться непрофессиональным, но это работает. И не нужно беспокоиться о том, что в браузере отключен JavaScript или ранее была отправлена ошибка заголовков:

Также можно использовать последнюю строку из предыдущего примера, чтобы автоматически обновлять страницу каждые «n » секунд. Например, следующий код будет автоматически обновлять страницу каждые 8 секунд:

Заключение

В этой статье я рассмотрел три различных метода перенаправления с index php , а также их преимущества и недостатки. Конкретный метод, который стоит использовать, зависит от задач проекта.

Перевод статьи «How can I do a redirect to different url before page load in PHP » дружной командой проекта .

Хорошо Плохо

(PHP 4, PHP 5, PHP 7)

header — Send a raw HTTP header

Description

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

header() is used to send a raw HTTP header. See the » HTTP/1.1 specification for more information on HTTP headers.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include , or require , functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.


Parameters

The header string.

There are two special-case header calls. The first is a header that starts with the string "HTTP/ " (case is not significant), which will be used to figure out the HTTP status code to send. For example, if you have configured Apache to use a PHP script to handle requests for missing files (using the ErrorDocument directive), you may want to make sure that your script generates the proper status code.

The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set.

Replace

The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in FALSE as the second argument you can force multiple headers of the same type. For example:

Http_response_code

Forces the HTTP response code to the specified value. Note that this parameter only has an effect if the header is not empty.

Return Values

No value is returned.

Changelog Version Description
5.1.2 This function now prevents more than one header to be sent at once as a protection against header injection attacks.
Examples

Example #1 Download dialog

If you want the user to be prompted to save the data you are sending, such as a generated PDF file, you can use the » Content-Disposition header to supply a recommended filename and force the browser to display the save dialog.