繁体   English   中英

PHP标头位置不起作用/ HTTP状态无效:更改

[英]PHP Header location not working / no HTTP Status: change

我在PHP中使用标头时遇到问题。 header('location: http:google.com'); 不管用。 这是我的代码:

if(!headers_sent()){
    header("location: http://google.com");
    exit;
}

HTML Data...

脚本正在退出,但header()无法正常工作。

  • 我已经在php.ini中检查了output_buffer参数,并将其设置为4096。
  • PHP开头标记上方没有多余的行
  • 而且我的脚本使用UTF-8(不带BOM)进行编码。
  • 启用了所有错误,但没有收到任何错误/警告/通知。 怎么了?
  • 环境:PHP 7.0.27和NGINX。

后来的尝试和调试步骤结束了:

  • header("location: http://google.com";, true, 302); 没有区别
  • header("Refresh: ...")确实成功。
  • HTTP响应调试(多次询问):

     StatusCode : 200 StatusDescription : OK Content : <br /> <b>Notice</b>: Undefined index: HTTP_ACCEPT_LANGUAGE in ... RawContent : HTTP/1.1 200 OK Transfer-Encoding: chunked Connection: keep-alive Pragma: no-cache Cache-Control: no-store, no-cache, must-revalidate Content-Type: text/html; charset=UTF-8 Date: Fri, 18 May 201... Forms : {} Headers : {[Transfer-Encoding, chunked], [Connection, keep-alive], 

仍未回答:

  • header("Status: 303 etc"); header('HTTP/1.1 301 Moved Permanently'); 从重复

  • cgi.rfc2616_headers

  • PHP SAPI

  • 在phar之外运行示例代码。

没错,这不只是解决问题的方法,而是在开发服务器上时在客户端工作的一种重定向方法。 我编写了一个中间件函数来为您生成重定向标头,只需将其添加到您的代码中,然后调用Redirect("URL");

<?php

function Redirect($location, $delay=0) {
    // Check to see if the header are already sent.
    if(!headers_sent()) {
        // Check to see if we want Refresh because Location isn't working.
        if(defined('REDIRECT_ALTERNATIVE')) {
            // We want Refresh, let's go!
            header("Refresh: $delay; URL=\"$location\"");  
            exit;
        }

        // We want to do this server side, do it!
        header("Location: $location");
        exit;
    }
}

现在,您已经拥有此功能,只需在文件(最好是常量或配置文件)中,使用代码define('REDIRECT_ALTERNATIVE', true); 然后,这将允许客户端重定向,完成后,只需注释或删除该定义,它将切换回服务器端。

再一次,这不是一个解决方案,而是一个可行的解决方案,但是在经过OP数小时的测试之后,这才是我们设法解决的问题。

编辑:对于任何想知道实际问题是什么的人,OP的开发服务器,无论出于何种原因,总是将http代码设置为200,即使我们手动更改了它,因为我无法访问他的pc并调试他的pc。设置过程中,我想到了一种解决方法,该方法可以避免他的服务器管理重定向。

尝试这个。

     header("Refresh: $seconds; URL=\"$location\"");  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM