眾所周知,PHP網站跳轉有三種方法:JS、HTML META Refresh、PHP header("location: $url")。但是這裡有一個非常小的細節,很容易導致出錯。
有一次製作一個跳轉程式,結果忽略了這一點,導致跳轉其實都是沒有成功。
程式全部源碼如下,程式地址:http://www.***.com/go.php
<?phperror_reporting(7);$url = urldecode( trim($_REQUEST['url']));if($url){ header("Location: $url");} else { exit('Error Input,<a href="http://www.***.com/?f=go.php">go back</a>');}
當訪問地址為:http://www.***.com/go.php?url=http%3A%2F%2Fwww.zbphp.com%2F 的時候,firefox瀏覽器是正常的。後來把這個跳轉程式複製到公司的另外一個網站,讓QQ上的一些好友測試,結果很多人都說打不開:IE核心的瀏覽器直接提示無法訪問或者找不到,chrome有時候會提示被重設或找不到,使用firefox測試也偶偶會提示無法找到,但多重新整理一次才顯示正常。
仔細檢查代碼,是沒有問題的。況且firefox是可以跳轉,後想到了以往閱讀到的一點就是:IE瀏覽器如果輸出的內容位元組太小(小於512位元組),那麼就會被忽略。然後將源碼由header location跳轉修改為 js html才所有瀏覽器都測試通過,原先偶偶出現firefox點擊提示找不到xxx伺服器也沒有再出現過,現go.php全部源碼:
<?phperror_reporting(7);function gheader($url){echo '<html><head><meta http-equiv="Content-Language" content="zh-CN"><meta HTTP-EQUIV="Content-Type" CONTENT="text/html;charset=gb2312"><meta http-equiv="refresh"content="0;url='.$url.'"><title>loading ... </title></head><body><div style="display:none"><script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id=\'cnzz_stat_icon_5696423\'%3E%3C/span%3E%3Cscript src=\'" + cnzz_protocol + "s9.cnzz.com/stat.php%3Fid%3D5696423%26show%3Dpic1\' type=\'text/javascript\'%3E%3C/script%3E"));</script></div><script>window.location="'.$url.'";</script></body></html>';exit();}$url = urldecode( trim($_REQUEST['url']));if($url){ gheader($url);} else { exit('Error Input,<a href="http://www.***.com/?f=go.php">go back</a>');}
對於PHP跳轉,我認為最好的方法就是用JS+HTML META。HTML META可以保證訪客在禁用JS的情況下可以照樣跳轉。
如果您有更好的方法,歡迎回帖或發送郵件給我,我的郵箱 admin@zbphp.com。