Redirect user to https 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.

Читайте также:  Округлить до ближайшего целого kotlin

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.

Источник

PHP: Redirect HTTP to HTTPS.

This is a guide on how to force users to use your PHP application with HTTPS instead of HTTP. Over the past few years, HTTPS has risen in popularity – especially since Google announced that HTTPS was being used as a ranking signal for websites.

Читайте также:  Операций в секунду java

There are three ways to go about doing this. You can use PHP code to redirect users, you can use Apache’s Redirect directive or you can use Apache’s mod_rewrite module.

Using PHP.

Take a look at the following PHP code:

The code above is pretty simple. It checks the HTTPS variable in the $_SERVER superglobal array to see if it equal to “on”. If the variable is not equal to “on”, then it redirects the user to the HTTPS version of the current URL. It then uses the exit construct to prevent the rest of the PHP code from executing.

Obviously, you could add the PHP snippet above to a custom function so that you can call it at the top of all of your scripts.

Using Apache’s Redirect.

If you are using Apache web server and you have access to the Virtual Hosts file, then you can make use of the Redirect directive:

 ServerName www.mywebsite.com Redirect / https://www.mywebsite.com/ ServerName www.mywebsite.com #configure your SSL 

In the configuration above, we redirect all traffic on port 80 to port 443 (the default port for HTTPS).

Using Apache’s mod_rewrite.

If you’re using shared hosting and you don’t have access to your Apache configuration files, then you can create a .htaccess file in the main public root of your website:

RewriteEngine On RewriteCond % off RewriteRule (.*) https://%%

The above .htaccess file will “rewrite” the URL to the HTTPS version if HTTPS is found to be off.

Hopefully, you found this guide useful!

Источник

Редирект с HTTP на HTTPS в htaccess

Как настроить перенаправление с HTTP на HTTPS в PHP и .htaccess на разных хостингах.

Редирект в PHP

if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === "off") < $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; header('HTTP/1.1 301 Moved Permanently'); header('Location: ' . $location); exit; >

Timeweb

SetEnvIf X-HTTPS 1 HTTPS RewriteEngine On RewriteBase / RewriteCond % !1 RewriteRule ^(.*)$ https://%/$1 [R=301,L]

Masterhost

RewriteCond % !443 RewriteRule ^(.*)$ https://%/$1 [R=301,L]

nic.ru

RewriteCond % !on RewriteRule ^(.*)$ https://%/$1 [R=301,L]

reg.ru

RewriteCond % !^443$ RewriteRule ^(.*)$ https://%/$1 [R=301,L]

beget.com

RewriteCond % !=https RewriteRule .* https://%% [R=301,L]

sweb.ru

RewriteEngine on SetEnvIf X-Forwarded-Proto https SERVER_PORT=443 SetEnvIf X-Forwarded-Proto https HTTPS=on RewriteCond % !=on [NC] RewriteRule ^(.*)$ https://%% [R=301,L]

jino.ru

RewriteCond % !=https RewriteRule .* https://%% [R=301,L]

Sprinthost.ru

RewriteCond % !https RewriteRule ^ https://%% [L,R=301,NE]

Комментарии

Другие публикации

Как сделать редирект PHP

На страницах сайтов постоянно что-то добавляется, удаляется и обновляется, чтобы в поисковиках была только актуальная информация и нужные страницы не выпадали из поиска применяются редиректы.

Location – URL текущей страницы

Объект Location связан с адресной строкой браузера, в его свойствах содержатся все компоненты URL доступные для чтения.

CURL - если сервер отдает редирект

Бывает так что сервер перенаправляет на другой URL. Например Google, если перейти на https://google.com c IP из РФ он.

Читайте также:  Help and manual html

Переезд сайта на HTTPS

В последнее время вопрос переезда сайта с HTTP на HTTPS перешел из рекомендаций в необходимость, как со стороны поисковиков, так и браузеров.

Источник

HTTP Redirects with plain PHP

With PHP we can redirect the user to a different website or URL by means of the Location HTTP header. This response header gives an indication to the browser where to redirect the user to.

In order to send back HTTP headers in PHP we need the built-in header() network function of PHP. This function allows you to send back a raw HTTP header.

As mentioned above we set the HTTP headers raw, so we don’t separate the header name and value as a key-value pair or so. Instead we set both the name and value in a single string.

This looks like the following in a PHP script:

Do make sure that you don’t write any output to the browser before setting the header, otherwise the script will fail.

Redirect with response code

PHP is smart enough to change the HTTP response status code for you when you set the Location header. Instead of a regular 200 response the code 302 is returned to indicate a redirect.

  • 301 to indicate that the location of the requested resource has been changed permanently.
  • Or 307 to indicate a temporarily moved resource.

We can set the response code as the third argument to the header() function.

The response code is the third argument to the header() function, we can pass the response code as an integer. The second argument in the replace option which defaults to true when not set manually. It indicates whether the header should be replaced if it has been set already.

Redirect HTTP to HTTPS

Probably a more suitable place to redirect HTTP traffic to HTTPS is in the webserver configuration. But, if necessary, a redirect in PHP does the job too.

First, make sure you only redirect to HTTPS if you are on actually on HTTP. To prevent your script from getting in an infinite redirect loop (ERR_TOO_MANY_REDIRECTS).

Second, we can get the current host with URI from the $_SERVER automatic global variable. This we can use to redirect to HTTPS.

<?php if (!isset($_SERVER['HTTPS']))  $currentUrl = ""; header("Location: https://"); exit; > 

Redirect to relative URI

Besides redirects to absolute URIs it is perfectly legal to redirect to relative URIs as well. This allows you to redirect traffic to a different page on the same website.

In this case we only need to pass the path as the header value.

Источник

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