Redirect option in php

Как сделать редирект на php?

Послать каждый может. А вот правильно перенаправить – это целое искусство. Но еще труднее дается перенаправление пользователей на нужный путь в интернете. Для этого лучше всего подходит редирект на php .

Что за редирект?

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

Что за редирект?

В каких случаях может потребоваться редирект:

  • Когда происходит замена движка сайта – в результате этого меняется архитектура всего ресурса. После чего возникает проблема, как сделать редирект;
  • При перекройке структуры ресурса – происходит добавление, удаление или перенос целых разделов или одного материала. Пока происходит этот процесс, временно можно организовать перенаправление пользователя на нужный раздел;
  • Если сайт недавно сменил свое доменное имя – после смены имени домена старое еще некоторое время будет фигурировать в поисковой выдаче. В этом случае редирект пользователя на новый домен будет реализован поисковой системой автоматически;
  • В процессе авторизации – как правило, на большом сайте есть две группы пользователей: обычные посетители и администраторы ресурса. В таком случае имеет смысл реализовать редирект каждого пользователя согласно его правам и роли. После авторизации администратор или модераторы сайта попадают в административную часть ресурса, а посетители – на пользовательскую часть ресурса.
Читайте также:  Как установить java браузер

Особенности редиректа на php

В отличие от других языков php обладает некоторыми преимуществами в реализации редиректа:

  • Php является серверным языком программирования. Поэтому перенаправление будет происходить не в html коде страниц, отображаемых в браузере, а в скрипте, размещенном на сервере;
  • Редирект на php может быть реализован несколькими способами. Что во многом расширяет его применение;
  • Благодаря обработке данных на сервере перенаправление, реализованное с помощью php, менее восприимчиво к действию фильтров поисковых систем.

Для редиректа в php используется функция header() . Она применяется для отправки заголовка http . Ее синтаксис:

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

Принимаемые функцией аргументы:

string $string – строка заголовка;

Существует два типа этого аргумента. Первый предназначен для отправки кода состояния соединения. Он начинается с «HTTP/». Другой тип вместе с заголовком передает клиентскому браузеру код состояния (REDIRECT 302). Этот аргумент начинается с «Location:»

Особенности редиректа на php

  • bool $replace – является необязательным атрибутом типа bool . Отвечает за переопределение предыдущего заголовка. Если будет задано true , то предыдущий заголовок или заголовки одного типа будут заменены. Если в аргументе задано false , то перезапись заголовка не состоится. По умолчанию, задано значение true ;
  • http_response_code – аргумент принудительно устанавливает код ответа HTTP . Установка кода пройдет успешно при условии, что аргумент string не будет пустым.

Код состояния HTTP представляет собой часть верхней строки ответа сервера. Код состоит из трех цифр, после которых идет поясняющая надпись на английском языке. Первая цифра отвечает за класс состояния. Редиректу соответствуют коды от 300 до 307. Их полное описание можно найти в соответствующей технической документации.

При использовании функции header() для редиректа внешних ссылок большое значение имеет место расположения ее вызова. В коде он должен находиться выше всех тегов html :

Особенности редиректа на php - 2

Применение редиректа header()

Для демонстрации действия функции на локальном сервере нужно создать два файла. Один из них назовем redirect.php , а другой redirect2.php . Внутри первого разместим вызов функции в следующем формате:

В другом файле помещаем строку:

echo "Привет! Вы находитесь в файле redirect2.php";

Источник

How to Redirect With PHP

Sajal Soni

Sajal Soni Last updated May 21, 2020

Redirection allows you to redirect the client browser to a different URL. You can use it when you’re switching domains, changing how your site is structured, or switching to HTTPS.

In this article, I’ll show you how to redirect to another page with PHP. I’ll explain exactly how PHP redirects work and show you what happens behind the scenes.

Learn PHP With a Free Online Course

If you want to learn PHP, check out our free online course on PHP fundamentals!

How Does Basic Redirection Work?

Before we dive into the specifics of PHP redirection, let’s quickly understand how exactly HTTP redirection works. Take a look at the following diagram.

How Redirection Works

Let’s understand what’s going on in the above screenshot:

  • The client browser requests a specific page from the server. In the above example, the client has requested the contents of the index.php file.
  • The server receives the index.php file request and wants to inform the client that it’s no longer available or moved somewhere else, and it should look to a new file instead: new_index.php. The server sends the Location header with a new URL along with the 301 or 302 HTTP code. These are the HTTP codes for redirection.
  • When a client browser encounters the 301 or 302 code, it knows that it has to initiate another request to a new URL to fetch the content. It initiates a request to fetch the new_index.php file in the above example.
  • Finally, a server sends the contents of the new URL.

So that’s how a basic HTTP redirection works. In the next section, we’ll discuss how PHP redirection works.

How Redirection Works in PHP

In PHP, when you want to redirect a user from one page to another page, you need to use the header() function. The header function allows you to send a raw HTTP location header, which performs the actual redirection as we discussed in the previous section.

How to Use Header Function

Let’s go through the syntax of the header() function.

header( $header, $replace, $http_response_code ) 
  • $header : This is the HTTP header string that you want to use. In our case, we’ll use the Location header for redirection.
  • $replace : It’s an optional parameter which indicates whether the header should replace a previous similar header.
  • $http_response_code : It allows you to send a specific response code.

Now, let’s have a look at the following example to understand how it all works together.

header("Location: https://www.yoursite.com/new_index.php"); 

When the above script is executed, it’ll redirect the client browser to http://www.yoursite.com/new_index.php. In the background, it sends a raw HTTP Location header along with the 302 status code. The 302 status code is used for temporary redirection, but if you want permanent redirection, you can pass the 301 code in the third argument, as shown in the following snippet.

header("Location: http://www.yoursite.com/new_index.php", TRUE, 301); 

The 301 permanent redirect allows you to inform the search bots that the page is no longer available, and it can be replaced with a new page.

Why Should You Use the Die() or Exit() Function After the Header Redirection?

Users with sharp eyes would have noticed that I’ve used the exit() function in the above example. In fact, it’s mandatory that you use either the exit() or the die() function immediately after the header redirection to stop script execution and avoid any undesired results.

So it’s always recommended practice to use one of these functions after redirection.

The Famous Error: Headers Are Already Sent

If you’re an experienced PHP programmer, I’m sure you’ve come across this famous PHP error at some point in your day-to-day PHP development. For beginners, however, encountering this error is really annoying, since it’s really hard to debug and fix. In most cases, they don’t even have a clue that it’s caused by the header redirection.

The rule of thumb is that when you use the header() function in your script, you need to make sure that you don’t send any output before it. Otherwise, PHP will complain with the «headers are already sent» error. This can happen even if you’ve sent a single white space before using the header function.

Conclusion

In this post, we discussed one of the important features of PHP programming: redirection. First, we went through the basics of HTTP redirection, and then I demonstrated how it works in PHP.

The Best PHP Scripts on CodeCanyon

Explore thousands of the best and most useful PHP scripts ever created on CodeCanyon. With a low-cost one-time payment, you can purchase one of these high-quality WordPress themes and improve your website experience for you and your visitors.

Popular PHP scripts on CodeCanyon

Here are a few of the best-selling and up-and-coming PHP scripts available on CodeCanyon for 2020.

Источник

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