Как перенаправить на другую страницу php
Перейти к содержимому

Как перенаправить на другую страницу php

  • автор:

header

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.

<?php
header ( «Location: http://www.example.com/» ); /* Redirect browser */

/* Make sure that code below does not get executed when we redirect. */
exit;
?>

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:

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.

Errors/Exceptions

On failure to schedule the header to be sent, header() issues an E_WARNING level error.

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.

<?php
// We’ll be outputting a PDF
header ( ‘Content-Type: application/pdf’ );

// It will be called downloaded.pdf
header ( ‘Content-Disposition: attachment; filename=»downloaded.pdf»‘ );

// The PDF source is in original.pdf
readfile ( ‘original.pdf’ );
?>

Example #2 Caching directives

PHP scripts often generate dynamic content that must not be cached by the client browser or any proxy caches between the server and the client browser. Many proxies and clients can be forced to disable caching with:

Note:

You may find that your pages aren't cached even if you don't output all of the headers above. There are a number of options that users may be able to set for their browser that change its default caching behavior. By sending the headers above, you should override any settings that may otherwise cause the output of your script to be cached.

Additionally, session_cache_limiter() and the session.cache_limiter configuration setting can be used to automatically generate the correct caching-related headers when sessions are being used.

Notes

Note:

Headers will only be accessible and output when a SAPI that supports them is in use.

Note:

You can use output buffering to get around this problem, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start() and ob_end_flush() in your script, or setting the output_buffering configuration directive on in your php.ini or server configuration files.

Note:

The HTTP status header line will always be the first sent to the client, regardless of the actual header() call being the first or not. The status may be overridden by calling header() with a new status line at any time unless the HTTP headers have already been sent.

Note:

Most contemporary clients accept relative URI s as argument to » Location:, but some older clients require an absolute URI including the scheme, hostname and absolute path. You can usually use $_SERVER[‘HTTP_HOST’] , $_SERVER[‘PHP_SELF’] and dirname() to make an absolute URI from a relative one yourself:

Note:

Session ID is not passed with Location header even if session.use_trans_sid is enabled. It must by passed manually using SID constant.

See Also

  • headers_sent() — Checks if or where headers have been sent
  • setcookie() — Send a cookie
  • http_response_code() — Get or Set the HTTP response code
  • header_remove() — Remove previously set headers
  • headers_list() — Returns a list of response headers sent (or ready to send)
  • The section on HTTP authentication

User Contributed Notes 32 notes

I strongly recommend, that you use

header($_SERVER[«SERVER_PROTOCOL»].» 404 Not Found»);

header(«HTTP/1.1 404 Not Found»);

I had big troubles with an Apache/2.0.59 (Unix) answering in HTTP/1.0 while I (accidentially) added a «HTTP/1.1 200 Ok» — Header.

Most of the pages were displayed correct, but on some of them apache added weird content to it:

A 4-digits HexCode on top of the page (before any output of my php script), seems to be some kind of checksum, because it changes from page to page and browser to browser. (same code for same page and browser)

«0» at the bottom of the page (after the complete output of my php script)

It took me quite a while to find out about the wrong protocol in the HTTP-header.

Several times this one is asked on the net but an answer could not be found in the docs on php.net .

If you want to redirect an user and tell him he will be redirected, e. g. «You will be redirected in about 5 secs. If not, click here.» you cannot use header( ‘Location: . ‘ ) as you can’t sent any output before the headers are sent.

So, either you have to use the HTML meta refresh thingy or you use the following:

<?php
header ( «refresh:5;url=wherever.php» );
echo ‘You\’ll be redirected in about 5 secs. If not, click <a href=»wherever.php»>here</a>.’ ;
?>

Hth someone

A quick way to make redirects permanent or temporary is to make use of the $http_response_code parameter in header().

<?php
// 301 Moved Permanently
header ( «Location: /foo.php» , TRUE , 301 );

// 302 Found
header ( «Location: /foo.php» , TRUE , 302 );
header ( «Location: /foo.php» );

// 303 See Other
header ( «Location: /foo.php» , TRUE , 303 );

// 307 Temporary Redirect
header ( «Location: /foo.php» , TRUE , 307 );
?>

The HTTP status code changes the way browsers and robots handle redirects, so if you are using header(Location:) it’s a good idea to set the status code at the same time. Browsers typically re-request a 307 page every time, cache a 302 page for the session, and cache a 301 page for longer, or even indefinitely. Search engines typically transfer «page rank» to the new location for 301 redirects, but not for 302, 303 or 307. If the status code is not specified, header(‘Location:’) defaults to 302.

When using PHP to output an image, it won’t be cached by the client so if you don’t want them to download the image each time they reload the page, you will need to emulate part of the HTTP protocol.

// Test image.
$fn = ‘/test/foo.png’ ;

// Getting headers sent by the client.
$headers = apache_request_headers ();

// Checking if the client is validating his cache and if it is current.
if (isset( $headers [ ‘If-Modified-Since’ ]) && ( strtotime ( $headers [ ‘If-Modified-Since’ ]) == filemtime ( $fn ))) <
// Client’s cache IS current, so we just respond ‘304 Not Modified’.
header ( ‘Last-Modified: ‘ . gmdate ( ‘D, d M Y H:i:s’ , filemtime ( $fn )). ‘ GMT’ , true , 304 );
> else <
// Image not cached or cache outdated, we respond ‘200 OK’ and output the image.
header ( ‘Last-Modified: ‘ . gmdate ( ‘D, d M Y H:i:s’ , filemtime ( $fn )). ‘ GMT’ , true , 200 );
header ( ‘Content-Length: ‘ . filesize ( $fn ));
header ( ‘Content-Type: image/png’ );
print file_get_contents ( $fn );
>

?>

That way foo.png will be properly cached by the client and you’ll save bandwith. 🙂

If using the ‘header’ function for the downloading of files, especially if you’re passing the filename as a variable, remember to surround the filename with double quotes, otherwise you’ll have problems in Firefox as soon as there’s a space in the filename.

So instead of typing:

<?php
header ( «Content-Disposition: attachment; filename keyword»>. basename ( $filename ));
?>

you should type:

<?php
header ( «Content-Disposition: attachment; filename=\»» . basename ( $filename ) . «\»» );
?>

If you don’t do this then when the user clicks on the link for a file named «Example file with spaces.txt», then Firefox’s Save As dialog box will give it the name «Example», and it will have no extension.

See the page called «Filenames_with_spaces_are_truncated_upon_download» at
http://kb.mozillazine.org/ for more information. (Sorry, the site won’t let me post such a long link. )

// Response codes behaviors when using
header ( ‘Location: /target.php’ , true , $code ) to forward user to another page :

$code = 301 ;
// Use when the old page has been «permanently moved and any future requests should be sent to the target page instead. PageRank may be transferred.»

$code = 302 ; (default)
// «Temporary redirect so page is only cached if indicated by a Cache-Control or Expires header field.»

$code = 303 ;
// «This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource and is not cached.»

$code = 307 ;
// Beware that when used after a form is submitted using POST, it would carry over the posted values to the next page, such if target.php contains a form processing script, it will process the submitted info again!

// In other words, use 301 if permanent, 302 if temporary, and 303 if a results page from a submitted form.
// Maybe use 307 if a form processing script has moved.

According to the RFC 6226 (https://tools.ietf.org/html/rfc6266), the only way to send Content-Disposition Header with encoding is:

Content-Disposition: attachment;
filename*= UTF-8»%e2%82%ac%20rates

for backward compatibility, what should be sent is:

Content-Disposition: attachment;
filename=»EURO rates»;
filename*=utf-8»%e2%82%ac%20rates

As a result, we should use

<?php
$filename = ‘中文文件名.exe’ ; // a filename in Chinese characters

$contentDispositionField = ‘Content-Disposition: attachment; ‘
. sprintf ( ‘filename=»%s»; ‘ , rawurlencode ( $filename ))
. sprintf ( «filename*=utf-8»%s» , rawurlencode ( $filename ));

header ( ‘Content-Type: application/octet-stream’ );

readfile ( ‘file_to_download.exe’ );
?>

I have tested the code in IE6-10, firefox and Chrome.

You can use HTTP’s etags and last modified dates to ensure that you’re not sending the browser data it already has cached.

<?php
$last_modified_time = filemtime ( $file );
$etag = md5_file ( $file );

header ( «Last-Modified: » . gmdate ( «D, d M Y H:i:s» , $last_modified_time ). » GMT» );
header ( «Etag: $etag » );

if (@ strtotime ( $_SERVER [ ‘HTTP_IF_MODIFIED_SINCE’ ]) == $last_modified_time ||
trim ( $_SERVER [ ‘HTTP_IF_NONE_MATCH’ ]) == $etag ) <
header ( «HTTP/1.1 304 Not Modified» );
exit;
>
?>

It seems the note saying the URI must be absolute is obsolete. Found on https://en.wikipedia.org/wiki/HTTP_location

«An obsolete version of the HTTP 1.1 specifications (IETF RFC 2616) required a complete absolute URI for redirection.[2] The IETF HTTP working group found that the most popular web browsers tolerate the passing of a relative URL[3] and, consequently, the updated HTTP 1.1 specifications (IETF RFC 7231) relaxed the original constraint, allowing the use of relative URLs in Location headers.»

Be aware that sending binary files to the user-agent (browser) over an encrypted connection (SSL/TLS) will fail in IE (Internet Explorer) versions 5, 6, 7, and 8 if any of the following headers is included:

Workaround: do not send those headers.

Also, be aware that IE versions 5, 6, 7, and 8 double-compress already-compressed files and do not reverse the process correctly, so ZIP files and similar are corrupted on download.

Workaround: disable compression (beyond text/html) for these particular versions of IE, e.g., using Apache’s «BrowserMatch» directive. The following example disables compression in all versions of IE:

BrowserMatch «.*MSIE.*» gzip-only-text/html

Just to inform you all, do not get confused between Content-Transfer-Encoding and Content-Encoding

Content-Transfer-Encoding specifies the encoding used to transfer the data within the HTTP protocol, like raw binary or base64. (binary is more compact than base64. base64 having 33% overhead).
Eg Use:- header(‘Content-Transfer-Encoding: binary’);

Content-Encoding is used to apply things like gzip compression to the content/data.
Eg Use:- header(‘Content-Encoding: gzip’);

Note that ‘session_start’ may overwrite your custom cache headers.
To remedy this you need to call:

. after you set your custom cache headers. It will tell the PHP session code to not do any cache header changes of its own.

It is important to note that headers are actually sent when the first byte is output to the browser. If you are replacing headers in your scripts, this means that the placement of echo/print statements and output buffers may actually impact which headers are sent. In the case of redirects, if you forget to terminate your script after sending the header, adding a buffer or sending a character may change which page your users are sent to.

This redirects to 2.html since the second header replaces the first.

<?php
header ( «location: 1.html» );
header ( «location: 2.html» ); //replaces 1.html
?>

This redirects to 1.html since the header is sent as soon as the echo happens. You also won’t see any «headers already sent» errors because the browser follows the redirect before it can display the error.

<?php
header ( «location: 1.html» );
echo «send data» ;
header ( «location: 2.html» ); //1.html already sent
?>

Wrapping the previous example in an output buffer actually changes the behavior of the script! This is because headers aren’t sent until the output buffer is flushed.

<?php
ob_start ();
header ( «location: 1.html» );
echo «send data» ;
header ( «location: 2.html» ); //replaces 1.html
ob_end_flush (); //now the headers are sent
?>

A call to session_write_close() before the statement

<?php
header ( «Location: URL» );
exit();
?>

is recommended if you want to be sure the session is updated before proceeding to the redirection.

We encountered a situation where the script accessed by the redirection wasn’t loading the session correctly because the precedent script hadn’t the time to update it (we used a database handler).

Please note that there is no error checking for the header command, either in PHP, browsers, or Web Developer Tools.

If you use something like «header(‘text/javascript’);» to set the MIME type for PHP response text (such as for echoed or Included data), you will get an undiagnosed failure.

The proper MIME-setting function is «header(‘Content-type: text/javascript’);».

For large files (100+ MBs), I found that it is essential to flush the file content ASAP, otherwise the download dialog doesn’t show until a long time or never.

<?php
header ( «Content-Disposition: attachment; filename keyword»>. urlencode ( $file ));
header ( «Content-Type: application/force-download» );
header ( «Content-Type: application/octet-stream» );
header ( «Content-Type: application/download» );
header ( «Content-Description: File Transfer» );
header ( «Content-Length: » . filesize ( $file ));
flush (); // this doesn’t really matter.

$fp = fopen ( $file , «r» );
while (! feof ( $fp ))
<
echo fread ( $fp , 65536 );
flush (); // this is essential for large downloads
>
fclose ( $fp );
?>

<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header ( ‘Location: http://www.example.com/’ );
exit;
?>

this example is pretty good BUT in time you use «exit» the parser will still work to decide what’s happening next the «exit» ‘s action should do (’cause if you check the manual exit works in others situations too).
SO MY POINT IS : you should use :
<?php

?>
‘CAUSE all die function does is to stop the script ,there is no other place for interpretation and the scope you choose to break the action of your script is quickly DONE.

there are many situations with others examples and the right choose for small parts of your scrips that make differences when you write your php framework at well!

Thanks Rasmus Lerdorf and his team to wrap off parts of unusual php functionality ,php 7 roolez.

I made a script that generates an optimized image for use on web pages using a 404 script to resize and reduce original images, but on some servers it was generating the image but then not using it due to some kind of cache somewhere of the 404 status. I managed to get it to work with the following and although I don’t quite understand it, I hope my posting here does help others with similar issues:

header_remove();
header(«Cache-Control: no-store, no-cache, must-revalidate, max-age=0»);
header(«Cache-Control: post-check=0, pre-check=0», false);
header(«Pragma: no-cache»);
// . and then try redirecting
// 201 = The request has been fulfilled, resulting in the creation of a new resource however it’s still not loading
// 302 «moved temporarily» does seems to load it!
header(«location:$dst», FALSE, 302); // redirect to the file now we have it

If you want to remove a header and keep it from being sent as part of the header response, just provide nothing as the header value after the header name. For example.

PHP, by default, always returns the following header:

Which your entire header response will look like

HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Content-Type: text/html; charset=UTF-8
Connection: close

If you call the header name with no value like so.

?>

Your headers now look like this:

HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Connection: close

Saving php file in ANSI no isuess but when saving the file in UTF-8 format for various reasons remember to save the file without any BOM ( byte-order mark) support.
Otherwise you will face problem of headers not being properly sent
eg.
<?php header ( «Set-Cookie: name=user» ); ?>

Would give something like this :-

Warning: Cannot modify header information — headers already sent by (output started at C:\www\info.php:1) in C:\www\info.php on line 1

After lots of research and testing, I’d like to share my findings about my problems with Internet Explorer and file downloads.

Take a look at this code, which replicates the normal download of a Javascript:

<?php
if( strstr ( $_SERVER [ «HTTP_USER_AGENT» ], «MSIE» )== false ) <
header ( «Content-type: text/javascript» );
header ( «Content-Disposition: inline; filename=\»download.js\»» );
header ( «Content-Length: » . filesize ( «my-file.js» ));
> else <
header ( «Content-type: application/force-download» );
header ( «Content-Disposition: attachment; filename=\»download.js\»» );
header ( «Content-Length: » . filesize ( «my-file.js» ));
>
header ( «Expires: Fri, 01 Jan 2010 05:00:00 GMT» );
if( strstr ( $_SERVER [ «HTTP_USER_AGENT» ], «MSIE» )== false ) <
header ( «Cache-Control: no-cache» );
header ( «Pragma: no-cache» );
>
include( «my-file.js» );
?>

Now let me explain:

I start out by checking for IE, then if not IE, I set Content-type (case-sensitive) to JS and set Content-Disposition (every header is case-sensitive from now on) to inline, because most browsers outside of IE like to display JS inline. (User may change settings). The Content-Length header is required by some browsers to activate download box. Then, if it is IE, the «application/force-download» Content-type is sometimes required to show the download box. Use this if you don’t want your PDF to display in the browser (in IE). I use it here to make sure the box opens. Anyway, I set the Content-Disposition to attachment because I already know that the box will appear. Then I have the Content-Length again.

Now, here’s my big point. I have the Cache-Control and Pragma headers sent only if not IE. THESE HEADERS WILL PREVENT DOWNLOAD ON IE. Only use the Expires header, after all, it will require the file to be downloaded again the next time. This is not a bug! IE stores downloads in the Temporary Internet Files folder until the download is complete. I know this because once I downloaded a huge file to My Documents, but the Download Dialog box put it in the Temp folder and moved it at the end. Just think about it. If IE requires the file to be downloaded to the Temp folder, setting the Cache-Control and Pragma headers will cause an error!

I hope this saves someone some time!

I just want to add, becuase I see here lots of wrong formated headers.

1. All used headers have first letters uppercase, so you MUST follow this. For example:

Location, not location
Content-Type, not content-type, nor CONTENT-TYPE

2. Then there MUST be colon and space, like

good: header(«Content-Type: text/plain»);
wrong: header(«Content-Type:text/plain»);

3. Location header MUST be absolute uri with scheme, domain, port, path, etc.

4. Relative URIs are NOT allowed

wrong: Location: /something.php?a=1
wrong: Location: ?a=1

It will make proxy server and http clients happier.

My files are in a compressed state (bz2). When the user clicks the link, I want them to get the uncompressed version of the file.

After decompressing the file, I ran into the problem, that the download dialog would always pop up, even when I told the dialog to ‘Always perform this operation with this file type’.

As I found out, the problem was in the header directive ‘Content-Disposition’, namely the ‘attachment’ directive.

If you want your browser to simulate a plain link to a file, either change ‘attachment’ to ‘inline’ or omit it alltogether and you’ll be fine.

This took me a while to figure out and I hope it will help someone else out there, who runs into the same problem.

If you haven’t used, HTTP Response 204 can be very convenient. 204 tells the server to immediately termiante this request. This is helpful if you want a javascript (or similar) client-side function to execute a server-side function without refreshing or changing the current webpage. Great for updating database, setting global variables, etc.

header(«status: 204»); (or the other call)
header(«HTTP/1.0 204 No Response»);

This is the Headers to force a browser to use fresh content (no caching) in HTTP/1.0 and HTTP/1.1:

<?PHP
header ( ‘Expires: Sat, 26 Jul 1997 05:00:00 GMT’ );
header ( ‘Last-Modified: ‘ . gmdate ( ‘D, d M Y H:i:s’ ) . ‘ GMT’ );
header ( ‘Cache-Control: no-store, no-cache, must-revalidate’ );
header ( ‘Cache-Control: post-check=0, pre-check=0’ , false );
header ( ‘Pragma: no-cache’ );

The encoding of a file is discovered by the Content-Type, either in the HTML meta tag or as part of the HTTP header. Thus, the server and browser does not need — nor expect — a Unicode file to begin with a BOM mark. BOMs can confuse *nix systems too. More info at http://unicode.org/faq/utf_bom.html#bom1

On another note: Safari can display CMYK images (at least the OS X version, because it uses the services of QuickTime)

DO NOT PUT space between location and the colon that comes after that ,
// DO NOT USE THIS :
header(«Location : #whatever»); // -> will not work !

// INSTEAD USE THIS ->
header(«Location: #wahtever»); // -> will work forever !

// Beware that adding a space between the keyword «Location» and the colon causes an Internal Sever Error

//This line causes the error
7
header(‘Location : index.php&controller=produit&action=index’);

// While It must be written without the space
header(‘Location: index.php&controller=produit&action=index’);

Setting the «Location: » header has another undocumented side-effect!

It will also disregard any expressly set «Content-Type: » and forces:

«Content-Type: text/html; charset=UTF-8»

The HTTP RFCs don’t call for such a drastic action. They simply state that a redirect content SHOULD include a link to the destination page (in which case ANY HTML compatible content type would do). But PHP even overrides a perfectly standards-compliant
«Content-Type: application/xhtml+xml»!

PHP редирект — перенаправление на другую страницу

PHP редирект - перенаправление на другую страницуВ рамках данной статьи, я расскажу вам про PHP редирект или же перенаправление на другую страницу.

Периодически возникают такие ситуации, когда нужно на серверной стороне организовать переадресацию на другой url (внешние ссылки, перенос адресов страниц и прочее). И делается это на самом деле очень просто и без каких-либо проблем.

Редирект в php осуществляется с помощью функции header с передачей соответствующих параметров. Вот описание самой функции:

Общий редирект в php выглядит так:

Как видите, все очень просто, всего лишь нужно указать параметр «Location:» а затем указать необходимый url адрес. Учтите, что по умолчанию такой редирект будет с кодом 302 (временно перемещено) или с тем кодом, который был установлен так же с помощью функции header (пример чуть ниже будет). Так же учтите, что переадресация на другой url должна осуществляться только в том случае, если до этого не было сгенерировано никакого кода html на странице. То есть до вызовов echo, print_r и прочего. И после этого так же не должен генерироваться html. В противном случае, это может приводить к ошибкам. Если же html-нужен, то лучше воспользуйтесь задержкой.

Редирект с задержкой в php:

Редирект с задержкой в php позволяет вам отображать на странице какой-то собственный текст в течении некоторого времени до реальной переадресации. Обычно, это привычное «через 5 секунд вы будете перенаправлены, если этого не произошло, щелкните по этой ссылке».

Сделать это можно с помощью двух методов.

В данном случае, редирект осуществит сам браузер через 5 секунд. Сделать такое можно и просто разместив специальный мета-тег в блоке head html-страницы.

Результат будет одинаковым. Однако, полезно знать альтернативные методы, так как некоторые браузеры такое могут не поддерживать. В крайнем случае, вы всегда можете использовать код javascript для переадресации, установив в «window.location» нужный url адрес.

Редирект в php с кодом 301

Периодически необходимо осуществлять редирект с кодом 301 (постоянно перенесено), например, если у вас изменился механизм генерации ЧПУ ссылок. В такой ситуации можно использовать два варианта:

Как видите, просто указали необходимый код http.

И второй вариант, аналогичный по смыслу, но может быть полезным, если установка кода и редирект должны осуществляться в разных местах.

Первая строка указывает код http, а вторая, собственно, задает адрес. В большинстве случаев, проблем не возникнет. Однако, если у вас используется режим FastCGI, то вместо «HTTP/1.1 301 Moved Permanently» может потребоваться написать «Status: 301 Moved Permanently«.

Как в 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 для редиректа с текущей страницы на другую:

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

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

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

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

Заключение

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

Перенаправление на другую страницу с помощью PHP, JavaScript или HTML (Redirect)

Перенаправление на другую страницу с помощью PHP, JavaScript или HTML (Redirect)

Здравствуйте, уважаемые посетители блога BlogGood.ru!
Сегодня мой блог пополнится еще одной полезной статьей для веб-мастеров.
В этой статье я хочу рассказать, как осуществить перенаправление на другую веб-страницу пользователя с помощью PHP, JavaScript или HTML.

Начнем, пожалуй, с PHP.

Перенаправление на другую веб-страницу с помощью PHP

Если вы желаете перенаправить пользователя сразу на другую веб-страницу, используйте вот этот код :

https://bloggood.ru/ — это адрес сайта, на который перенаправится пользователь.

→ перенаправление с задержкой в указанные секунды

Если вы желаете перенаправить пользователя не сразу, а через несколько секунд, тогда используйте вот такой код:

15 – это время, показывающее через сколько секунд пользователь отправится на другую веб-страницу.
https://bloggood.ru/ — это адрес сайта, на который перенаправится пользователь.

Перенаправление на другую веб-страницу с помощью JavaScript

https://bloggood.ru/ — это адрес сайта, на который перенаправится пользователь.

→ перенаправление с задержкой в указанные секунды

https://bloggood.ru/ — это адрес сайта, на который перенаправится пользователь.
15000 – это миллисекунды, через которые перенаправится пользователь на другую веб-страницу. Этот параметр задается не в секундах, а в миллисекундах.

К сведенью: 1 секунда = 1000 миллисекунды.
Значит, 15 000 миллисекунд = 15 секунд.

Перенаправление на другую веб-страницу с помощью HTML

В HTML для перенаправления пользователя используют специальный мета-тег :

0 – это секунды, через которые нужно перенаправить пользователя на другую страницу. В данном примере стоит « 0 », это значит, что пользователя перенаправит сразу.
https://bloggood.ru/ — это адрес сайта, на который перенаправится пользователь.

→ перенаправление с задержкой в указанные секунды

Чтобы перенаправить пользователя через определенное время, например, через 15 секунд, достаточно «0» исправить на «15»:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *