如何在PHP中重定向?

[英]How to make a redirect in PHP?


Is it possible to redirect a user to a different page through the use of PHP?

是否可以通过使用PHP将用户重定向到另一个页面?

Say the user goes to www.example.com/page.php and I want to redirect them to www.example.com/index.php, how would I do so without the use of a meta refresh? Possible?

假设用户访问www.example.com/page.php,而我想将其重定向到www.example.com/index.php,如果不使用元刷新,我怎么做?可能吗?

This could even protect my pages from unauthorized users.

这甚至可以保护我的页面从未经授权的用户。

27 个解决方案

#1


1373  

Summary of existing answers plus my own two cents:

现有答案的总结加上我自己的两美分:

1. Basic answer

You can use the header() function to send a new HTTP header, but this must be sent to the browser before any HTML or text (so before the <!DOCTYPE ...> declaration, for example).

可以使用header()函数发送一个新的HTTP报头,但是必须在任何HTML或文本之前将其发送到浏览器(所以在 <之前!doctype……> 声明,例如)。

header('Location: '.$newURL);

2. Important details

die() or exit()

die()或退出()

header("Location: http://example.com/myOtherPage.php");
die();

Why you should use die() or exit(): The Daily WTF

为什么要使用die()或exit(): Daily WTF

Absolute URL

绝对URL

The URL must be an absolute. See RFC 2616. But in most cases a relative URL will be accepted too.

必须绝对URL。看到RFC 2616。但在大多数情况下,一个相对URL将被接受。

Status Codes

状态码

PHP's "Location"-header still uses the HTTP 302-redirect code, but this is not the one you should use. You should consider either 301 (permanent redirect) or 303 (other).

PHP的“位置”筒式水管仍然使用HTTP 302重定向代码,但这不是你应该使用。你应该考虑301(永久重定向)或303(其他)。

Note: W3C mentions that the 303-header is incompatible with "many pre-HTTP/1.1 user agents. Currently used browsers are all HTTP/1.1 user agents. This is not true for many other user agents like spiders and robots.

注意:W3C提到303-header与“许多pre-HTTP/1.1用户代理”不兼容。当前使用的浏览器都是HTTP/1.1用户代理。对于许多其他用户代理(如蜘蛛和机器人)来说,情况并非如此。

3. Documentation

HTTP Headers and the header() function in PHP

PHP中的HTTP header和header()函数

4. Alternatives

You may use the alternative method of http_redirect($url); which needs the PECL package pecl to be installed.

您可以使用http_redirect($url)的替代方法;需要安装PECL软件包PECL。

5. Helper Functions

This function doesn't incorporate the 303 status code:

此函数不包含303状态码:

function Redirect($url, $permanent = false)
{
    header('Location: ' . $url, true, $permanent ? 301 : 302);

    exit();
}

Redirect('http://example.com/', false);

This is more flexible:

这是更灵活:

function redirect($url, $statusCode = 303)
{
   header('Location: ' . $url, true, $statusCode);
   die();
}

6. Workaround

As mentioned header() redirects only work before anything is written out. They usually fail if invoked inmidst HTML output. Then you might use a HTML header workaround (not very professional!) like:

如前所述,头()重定向仅在写入任何内容之前有效。如果在HTML输出中调用,它们通常会失败。然后你可以使用一个HTML头(不是很专业!)

 <meta http-equiv="refresh" content="0;url=finalpage.html">

Or a JavaScript redirect even.

甚至一个JavaScript重定向。

window.location.replace("http://example.com/");

#2


87  

function Redirect($url, $permanent = false)
{
    if (headers_sent() === false)
    {
        header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);
    }

    exit();
}

Redirect('http://www.google.com/', false);

Don't forget to die()/exit()!

别忘了die()/退出()!

#3


84  

Output JavaScript from PHP using echo, which will do the job.

使用echo的PHP输出JavaScript,这将完成任务。

echo '<script type="text/javascript">
           window.location = "http://www.google.com/"
      </script>';

You can't really do it in PHP unless you buffer the page output and then later check for redirect condition. That might be too much of a hassle. Remember that headers are the first thing that is sent from the page. Most of the redirect is usually required later in the page. For that you have to buffer all the output of the page and check for redirect condition later. At that point you can either redirect page user header() or simply echo the buffered output.

除非缓冲页面输出,然后再检查重定向条件,否则无法在PHP中实现。那可能太麻烦了。记住,页眉是从页面发送的第一件事。大多数重定向通常需要在页面的后面进行。为此,您必须缓冲页面的所有输出,并在稍后检查重定向条件。此时,您可以重定向page user header(),也可以简单地回显缓冲输出。

For more about buffering (advantages)

有关缓冲的更多信息(优点)

What is output buffering?

输出缓存区是什么?

#4


76  

Use header() function to send HTTP Location header:

使用header()函数发送HTTP位置header:

header('Location: '.$newURL);

Contrary to some think, die() has nothing to do with redirection. Use it only if you want to redirect instead of normal execution.

与某些人的想法相反,die()与重定向无关。只有在您想重定向而不是常规执行时才使用它。

example.php:

example.php:

<?php 
header('Location: static.html');
$fh = fopen('/tmp/track.txt','a');
fwrite($fh, $_SERVER['REMOTE_ADDR'].' '.date('c')."\n");
fclose($fh);
?>

Result or 3 executions:

结果或3执行:

bart@hal9k:~> cat /tmp/track.txt
127.0.0.1 2009-04-21T09:50:02+02:00
127.0.0.1 2009-04-21T09:50:05+02:00
127.0.0.1 2009-04-21T09:50:08+02:00

Resuming — obligatory die()/exit() is some urban legend, that has nothing to do with actual PHP. Has nothing to do with client "respecting" Location: header. Sending header does not stop PHP execution, regardless of client used.

恢复-强制die()/exit()是一些都市传奇,与实际的PHP无关。与客户端“尊重”位置无关:header。发送header不会停止PHP执行,不管使用的客户端是什么。

#5


56  

1. Using header function with exit()

1。使用带有exit()的header函数

<?php 
     header('Location: target-page.php');
     exit();
?>

but if you use header function then some times you will get "warning like header already send" to resolve that do not echo or print before sending headers or you can simply use die() or exit() after header function.

但是如果您使用header函数,那么有时您会得到“像header already sent一样的警告”,以解决在发送header之前不回送或打印的问题,或者您可以使用die()或exit() after header函数。

2. Without header

2。没有头

<?php 
    echo "<script>location.href='target-page.php';</script>";
?>

here you will not face any problem

在这里你不会遇到任何问题

3. Using header function with ob_start() and ob_end_flush()

3所示。使用带有ob_start()和ob_end_flush()的header函数

<?php
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
?>

#6


47  

Most of these answers are forgetting a very important step!

大多数的答案都忘记了一个非常重要的步骤!

header("Location: myOtherPage.php");
die();

Leaving that vital second line out might see you end up on The Daily WTF. The problem is that browsers do not have to respect the headers which your page return, so with headers being ignored, the rest of the page will be executed without a redirect.

把至关重要的第二行去掉,可能会让你变成每天的WTF。问题是浏览器不需要尊重你的页面返回的标题,所以当标题被忽略时,页面的其余部分将会在没有重定向的情况下执行。

#7


22  

<?php header('Location: another-php-file.php'); exit(); ?>

or if you have already opened php tags, use this:

或者,如果您已经打开了php标记,请使用以下命令:

header('Location: another-php-file.php'); exit();

You can also redirect to external pages, eg:

你也可以重定向到外部页面,例如:

header('Location: https://www.google.com'); exit();

Make sure you include exit() or include die()

确保包含exit()或include die()

#8


17  

Many of these answers are correct, but they assume you have an absolute URL, which may not be the case. If you want to use a relative URL and generate the rest, then you can do something like this...

这些答案中有许多是正确的,但它们假设您有一个绝对URL,这可能不是事实。如果您想使用一个相对URL并生成其余的,那么您可以这样做…

$url = 'http://' . $_SERVER['HTTP_HOST'];            // Get the server
$url .= rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // Get the current directory
$url .= '/your-relative/path-goes/here/';            // <-- Your relative path
header('Location: ' . $url, true, 302);              // Use either 301 or 302

#9


16  

You can use session variables to control access to pages and authorize valid users as well.

您可以使用会话变量来控制对页面的访问并授权有效的用户。

<?php

session_start();

if ( !isset( $_SESSION["valid_user"]) )
{
    header("location:../");
   die();
}

// Page goes here
?>

http://php.net/manual/en/reserved.variables.session.php.

http://php.net/manual/en/reserved.variables.session.php。

Recently, I got cyber attacks and decided, i needed to know the users trying t access Admin Panel or reserved part of the web application.

最近,我受到了网络攻击,我决定,我需要了解尝试访问管理面板或保留部分web应用程序的用户。

so, I added a log access IP and user sessions in a text file because I don't want to bother my database.

因此,我在文本文件中添加了日志访问IP和用户会话,因为我不想打扰我的数据库。

#10


13  

I've already answered this question, but I'll do it again since in the meanwhile I've learnt that there are special cases if you're running in CLI (redirects cannot happen and thus shouldn't exit()) or if your webserver is running PHP as a (F)CGI (it needs a previously set Status header to properly redirect).

我已经回答了这个问题,但我会再做一次因为同时我得知有特殊情况如果你运行在CLI(重定向不能发生,因此不应该退出()),或者如果您的网络服务器运行PHP作为一个CGI(F)(它需要一套以前状态头正确定向)。

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();
    }
}

I've also handled the issue of supporting the different HTTP redirection codes (301, 302, 303 and 307), as it was addressed in the comments of my previous answer, here are the descriptions:

我还处理了支持不同的HTTP重定向代码(301、302、303和307)的问题,正如我之前回答的注释中所提到的,以下是描述:

  • 301 - Moved Permanently
  • 301年搬到永久
  • 302 - Found
  • 302年发现的
  • 303 - See Other
  • 303 -看到其他
  • 307 - Temporary Redirect (HTTP/1.1)
  • 307 -临时重定向(HTTP/1.1)

#11


11  

header( 'Location: http://www.yoursite.com/new_page.html' );

头(地点:http://www.yoursite.com/new_page.html);

#12


10  

header("Location: /index.php");
exit(0);   

#13


8  

you can use some java script methods like below

您可以使用一些java脚本方法,如下所示

 1)self.location="http://www.example.com/index.php";

 2)window.location.href="http://www.example.com/index.php";

 3)document.location.href = 'http://www.example.com/index.php';  

 4)window.location.replace("http://www.example.com/index.php");

#14


7  

Yes, you can use header() function,

是的,您可以使用header()函数,

header("Location: http://www.yourwebsite.com/user.php"); /* Redirect browser */
exit();

And also best practice is to call exit() function right after header() function to avoid below code execution.

另外,最佳实践是在header()函数之后调用exit()函数,以避免代码执行以下。

According to the documentation, header() must be called before any actual output is sent.

根据文档,必须在发送任何实际输出之前调用header()。

#15


6  

Like others here said, sending the location header with:

就像这里其他人说的,发送位置标头:

header( "Location: http://www.mywebsite.com/otherpage.php" );

but you need to do it before you've sent any other output to the browser.

但是在向浏览器发送任何其他输出之前,您需要这样做。

Also, if you're going to use this to block un-authenticated users from certain pages, like you mentioned, keep in mind that some user agents will ignore this and continue on the current page anyway, so you'll need to die() after you send it.

另外,如果您打算使用它来从某些页面阻止未经身份验证的用户(如您所提到的),请记住,某些用户代理将忽略这一点,并在当前页面上继续,因此在发送之后您将需要die()。

#16


6  

In the eve of the semantic web, correctness is something to consider. Unfortunately, PHP's "Location"-header still uses the HTTP 302-redirect code, which, strictly, isn't the best one for redirection. The one it should use instead, is the 303 one.

在语义网的前夕,正确性是需要考虑的问题。不幸的是,PHP的“位置”-header仍然使用HTTP 302重定向代码,严格来说,这并不是重定向的最佳代码。它应该使用的是303。

W3C is kind enough to mention that the 303-header is incompatible with "many pre-HTTP/1.1 user agents," which would amount to no browser in current use. So, the 302 is a relic, which shouldn't be used.

W3C很好心地提到303-header与“许多pre-HTTP/1.1用户代理”不兼容,在当前的使用中这相当于没有浏览器。所以,302是文物,不应该用。

...or you could just ignore it, as everyone else...

…或者你可以忽略它,就像其他人一样……

#17


6  

Probably too late to answer this one. Nevertheless, here are my thoughts:

也许现在回答这个问题已经太晚了。然而,我的想法是:

IMHO, the best way to re-direct an incoming request would be by using location headers, which goes

IMHO,重新指导传入请求的最佳方式是使用位置头文件

<?php
header("Location: /index.php");
?>

Once this statement is executed, and output sent out, the browser will begin re-directing the user. However, ensure that there hasn't been any output (any echo / var_dump) before sending headers, else it will lead to errors.

一旦执行此语句并输出,浏览器将开始重定向用户。但是,在发送头之前,请确保没有任何输出(任何echo / var_dump),否则会导致错误。

Although this is a quick and dirty way to achieve what was originally asked, yet it would eventually turn out to be an SEO disaster, as this kind of re-direct is always interpreted as a 301 / 302 re-direct, hence search engines will always see your index page as a re-directed page, and not something of a landing page / main page. Hence it will affect the SEO settings of the website.

尽管这是一个快速和肮脏的方式来达到最初问什么,但它最终会变成一个SEO灾难,像这种总是重新解读为301/302重新定位,因此搜索引擎总是看到你的索引页转页,而不是一个着陆页/主页。因此会影响网站的SEO设置。

#18


6  

<?php 
header('Location: redirectpage.php');
header('Location: redirectpage.php');exit();
echo "<script>location.href='redirectpage.php';</script>";
?>

This is regular and normal PHP redirect but you can make a redirecting a page with few second wait below code:

这是常规的和普通的PHP重定向,但是您可以在代码下面进行几秒钟的等待:

<?php
header('refresh:5;url=redirectpage.php '); //Note: here 5 means 5 seconds wait for redirect.
?>

#19


5  

The best way to Redirect with PHP is the following code...

使用PHP重定向的最好方法是以下代码……

 header("Location: /index.php");

Make sure no code will work after

确保之后没有代码可以工作

header("Location: /index.php");

All the codes must be executed before the above line.

所有代码必须在上面一行之前执行。

Suppose,

假设,

Case 1:

案例1:

echo "I am a web developer";
header("Location: /index.php");

It will redirect properly to the location (index.php).

它将正确地重定向到位置(index.php)。

Case 2:

案例2:

return $something;
header("Location: /index.php");

The above code will not redirect to the location(index.php).

上面的代码不会重定向到位置(index.php)。

Hopefully, It is clear.

希望这是清楚的。

#20


4  

Yes it's possible to use PHP, we will redirect to another page, try this one:

是的,可以使用PHP,我们将重定向到另一个页面,试试这个:

<?php
header("location:./");//redirect to index file
header("location:index.php");//redirect to index file
header("location:example.php");
?>

#21


4  

To redirect the visitor to another page (particularly useful in a conditional loop), simply use the following code:

要将访问者重定向到另一个页面(在条件循环中特别有用),只需使用以下代码:

<?php 
header('Location: mypage.php'); 
?>

In this case, mypage.php is the address of the page to which you would like to redirect the visitors. This address can be absolute and may also include the parameters in this format: mypage.php?param1=val1¶m2=val2)

在这种情况下,mypage。php是您想要重定向访问者的页面的地址。这个地址可以是绝对的,也可以包括这种格式的参数:mypage.php ? param1 = val1¶m2 = val2)

Relative/Absolute Path

相对/绝对路径

When dealing with relative or absolute paths, it is ideal to choose an absolute path from the root of the server (DOCUMENT_ROOT). Use the following format:

在处理相对路径或绝对路径时,最好从服务器根(DOCUMENT_ROOT)选择绝对路径。使用以下格式:

<?php 
header('Location: /directory/mypage.php'); 
?>

If ever the target page is on another server, you include the full URL:

如果目标页面在另一个服务器上,则包含完整的URL:

<?php 
header('Location: http://www.ccm.net/forum/'); 
?> 

HTTP Headers

HTTP头信息

According to HTTP protocol, HTTP headers must be sent before any type of content. This means that no characters should ever be sent before the header — not even an empty space!

根据HTTP协议,HTTP头必须在任何类型的内容之前发送。这意味着不应该在页眉之前发送任何字符——甚至是一个空空格!

Temporary/Permanent Redirections

临时或永久重定向

By default, the type of redirection presented above is a temporary one. This means that search engines, such as Google, will not take the redirection into account when indexing.

默认情况下,上述重定向的类型是临时的。这意味着搜索引擎(如谷歌)在索引时不会考虑重定向。

If you would like to notify search engines that a page has been permanently moved to another location, use the following code:

如果您想通知搜索引擎一个页面已被永久移动到另一个位置,请使用以下代码:

<? 
header('Status: 301 Moved Permanently', false, 301); 
header('Location: new_address'); 
?>

For example, this page has the following code:

例如,本页有以下代码:

<? 
header('Status: 301 Moved Permanently', false, 301); 
header('Location: /pc/imprimante.php3'); 
exit(); 
?>

When you click on the link above, you are automatically redirected to this page. Moreover, it is a permanent redirection (Status: 301 Moved Permanently). So, if you type the first URL into Google, you will automatically be redirected to the second, redirected link.

当您点击上面的链接时,您将被自动重定向到此页面。此外,它是一个永久重定向(状态:301永久移动)。因此,如果您将第一个URL输入谷歌,您将自动被重定向到第二个重定向链接。

Interpretation of PHP Code

PHP代码的解释

The PHP code located after the header() will be interpreted by the server, even if the visitor moves to the address specified in the redirection. In most cases, this means that you need a method to follow the header() function of the exit() function in order to decrease the load of the server:

位于header()后面的PHP代码将由服务器解释,即使访问者移动到重定向中指定的地址。在大多数情况下,这意味着您需要一个方法来跟踪exit()函数的header()函数,以减少服务器的负载:

<? 
header('Status: 301 Moved Permanently', false, 301); 
header('Location: address'); 
exit(); 
?>

#22


3  

We can do in two way

我们可以用两种方法

  1. when user come on https://bskud.com/PINCODE/BIHAR/index.php then redirect to https://bskud.com/PINCODE/BIHAR.php
  2. 当用户登录https://bskud.com/PINCODE/BIHAR/index.php,然后重定向到https://bskud.com/PINCODE/BIHAR.php

by below php code

下面的php代码

<?php header("Location: https://bskud.com/PINCODE/BIHAR.php"); exit; ?>

< ?php头(地点:https://bskud.com/PINCODE/BIHAR.php);退出;? >

Save Above code in https://bskud.com/PINCODE/BIHAR/index.php

在https://bskud.com/PINCODE/BIHAR/index.php中保存上述代码

2.When any condition true then redirect to other page

2。当任何条件为真时,重定向到其他页面。

<?php  $myVar = "bskud";   if ($myVar == "bskud") { ?>  <script> window.location.href="https://bskud.com";  </script> <?php  } else {  echo "<b>Check Website Name Again</b>"; } ?>

`

#23


2  

you can update the header in php: header

您可以在php: header中更新标题

#24


1  

You can attempt to use the php header function to do the redirect. You will want to set the output buffer so your browser doesn't throw a redirect warning to the screen.

可以尝试使用php header函数进行重定向。您将希望设置输出缓冲区,以便您的浏览器不会向屏幕抛出重定向警告。

ob_start();
header("Location: ".$website);
ob_end_flush();

#25


1  

If you're running on Apache you can also use .htaccess for redirect.

如果在Apache上运行,也可以使用.htaccess进行重定向。

Redirect 301 / http://new-site.com/

#26


1  

<?php
$url = "targetpage"
Function redirect$url(){
   If (headers_sent()) == false{
      Echo '<script>window.location.href="' . $url . '";</script>';
}}
?>

#27


1  

There are multiple ways of doing this, but if you’d prefer php, I’d recommend the use of the header() function.

有多种方法可以做到这一点,但是如果您更喜欢php,我建议使用header()函数。

Basically

基本上

$your_target_url = “www.example.com/index.php”;
header(“Location : $your_target_url”);
exit();

If you want to kick it up a notch, it’s best to use it in functions, that way, you are able to add authentications and other checking elemnts in it.

如果您想要升级它,最好在函数中使用它,这样,您就可以在其中添加身份验证和其他检查元素。

Let’s try with by checking the user’s level.

让我们检查一下用户的级别。

So,suppose you have stored the user’s authority level in a session called u_auth.

因此,假设您已经将用户的权限级别存储在一个名为u_auth的会话中。

In the function.php

在function.php

<?php

function authRedirect($get_auth_level, $required_level, $if_fail_link = “www.example.com/index.php”){
    if($get_auth_level != $required_level){
        header(location : $if_fail_link);
        return false;
        exit();
    }else{
        return true;
    }
 }

 . . . 

You’ll then call the function for every page that you want to authenticate.

然后,您将为每个希望进行身份验证的页面调用该函数。

Like in page.php or any other page.

像在页面。php或其他页面。

<?php

// page.php

require “function.php”

authRedirect($_SESSION[‘u_auth’], 5);  // redirects to www.example.com/index.php if the user isn’t auth level 5
authRedirect($_SESSION[‘u_auth’], 4);  // redirects to www.example.com/index.php if the user isn’t auth level 4
authRedirect($_SESSION[‘u_auth’], 2, “www.someotherplace.com/somepage.php”);  // redirects to www.someotherplace.com/somepage.php if the user isn’t auth level 2


. . . 

I hope you’ll find some of the content useful

我希望你能找到一些有用的内容

References;

引用;

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2009/04/20/7ad0df535a8cebd680b52f85c116cabf.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告