Redirect to main page php

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.

Источник

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

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

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

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

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

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

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

Особенности редиректа на 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 Make a Redirect in PHP

Redirects are particularly useful when web admins are migrating websites to a different domain, implementing HTTPS, or deprecating pages.

There are several ways to implement a redirect, with PHP redirects being one of the easiest and safest methods. A PHP redirect is a server-side redirect that quickly redirects users from one web page to another.

Even though PHP redirects are considered safe, not implementing them correctly can cause serious server issues.

This guide explains two ways to set up a PHP redirect, and the advantages and disadvantages of each method.

How to set up a PHP redirect.

Method 1: PHP Header Function

The fastest and most common way to redirect one URL to another is by using the PHP header() function.

The general syntax for the header() function is as follows:

header( $header, $replace, $http_response_code ) 
  • $header . The URL or file name of the resource being redirected to. Supported file types include but are not limited to HTML, PDF, PHP, Python, Perl, etc.
  • $replace(optional). Indicates whether the current header should replace a previous one or just add a second header. By default, this is set to true . Using false forces the function to use multiple same-type headers.
  • $http_response_code(optional). Sets the HTTP response code to the specified value. If not specified, the header returns a 302 code.

Important: To correctly redirect using the header() function, it must be placed in the page’s source code before any HTML. Place it at the very top of the page, before the !DOCTYPE declaration.

Consider the following PHP code example:

The defined header() function redirects the page to http://www.example.com/example-url, replaces any previous header function and generates a 301 response code.

The exit() or die() function is mandatory. If not used, the script may cause issues.

Note: Permanent (301) redirects are typically used for broken or removed pages. That way, users are redirected to a page relevant to them.

Method 2: JavaScript via PHP

If using the PHP header() function is not a viable solution, use JavaScript to set up a PHP redirect. Take into consideration that JavaScript redirects via PHP work slower and require the end user’s browser to have JS enabled and downloaded.

There are three ways to set up a PHP redirect using the JS window.location function:

Below is a brief overview of the differences between the three options:

window.location.href window.location.assign window.location.replace
Function Returns and stores the URL of the current page Replaces the current page. Loads a new document.
Usage Fastest JS redirect method. Used when the original webpage needs to be removed from browser history. Safer than href.
Does it show the current page?
Does it add a new entry to the user’s browser history?
Does it delete the original page from the session history?

window.location.href

window.location.href sets the location property of a page to a new URL.

The following code is used to call window.location.href via PHP.

 window.location.href="http://www.example-url.com" ?> 

The advantage of window.location.href is that it is the fastest-performing JS redirect. The disadvantage is that if the user navigates back, they return to the redirected page.

window.location.assign

window.location.assign() calls a function to display the resource located at the specified URL.

Note: window.location.assign() only works via HTTPS. If the function is used for an HTTP domain, the redirect does not function, and it displays a security error message instead.

The following code snippet calls the window.location.assign() via PHP:

 window.location.assign("http://www.example-url.com") ?> 

The disadvantage of using window.location.assign() is that its performance and speed is determined by the browser’s JavaScript engine implementation. However, its the safer option. Should the target link be broken or unsecure, the function will display a DOMException – an error message.

window.location.replace

window.location.replace() replaces the current page with the specified URL.

Note: window.location.replace() only works on secure domains (HTTPS) too.

The following code is used to call window.location.replace() via PHP:

 window.location.replace("http://www.example-url.com") ?> 

Once a page is replaced, the original resource does not exist in the browser’s history anymore, meaning the user cannot click back to view the redirected page.

The advantage of window.location.replace() is that, just like window.location.assign() , it does not allow redirects to broken or unsecure links, in which case it outputs a DOMException .

The disadvantage of window.location.replace() is that it may perform slower than window.location.href() .

PHP Header Vs. JS Methods — What to Use?

The general consensus is that the PHP header() function is the easiest and fastest way to set up a PHP redirect. JavaScript via PHP is typically reserved as an alternative when setting up the PHP header fails.

This is due to two reasons:

  • JavaScript must be enabled and downloaded on the end user’s browser for redirects to function.
  • JavaScript redirects perform slower.

You now know how to set up a PHP redirect using the header() function or through some clever use of JavaScript.

After setting up redirects, monitor their performance. A routine website audit can detect the presence of redirect loops and chains, missing redirects or canonicals, and potential setup errors (redirects being temporary instead of permanent, and vice versa).

Источник

Читайте также:  Meta http equiv refresh content 0 index php
Оцените статью