[英]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()
無法正常工作。
output_buffer
參數,並將其設置為4096。 后來的嘗試和調試步驟結束了:
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');
從重復
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.