close

PHP如何重導向網址,參考至StackOverflow

header("Location: " . $url, true, 301 or 302 or 303)

301代表permanent,表示永久轉移,Client會儲存Cache

302代表非永久,可能之後你更改程式碼時,會自動更新,而不會有Cache.

303與302相似,皆為重導向且不做Cache,但是在Stack上看到大多數人皆說目前303很多Browser還不太支援(2014-12-12) 雖然已經是舊文了XDD。

注意:使用301必須確認你清楚你本人在做什麼樣的動作。

Never issue a 301 unless you mean it. 301 means permanent, and permanent means permanent, meaning it will be cached by user agents, meaning long, caffeine-filled nights staring at application logs wondering if you're going insane because you swear some page should have been called or updated and you swear to God it works on your machine but not the client's. If you absolutely must call a 301, put a cache-control max-age on the resource. You don't have infinite wisdom and you shouldn't be acting like you do   – madumlao 

看起來這位大師被301搞得很慘,因為301的Response code讓Browser幫Client自動Cache所以導致Server已經更新了,Client卻持續使用舊的版本的網頁,

在這裡就知道最好還是設定一個cache-control max-age的tag,本身也好幾次因為cache的問題,一直以為哪裡有Bug。

 

JavaScript作法: 

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

HTML作法:

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

 

 

備註:通常使用 header("Location: " . $url, true, 302);

後面需要接exit(); or die();

然而看到有網友 Nick Humphrey 的建議感覺還不錯,在DailyWTF推薦使用exit()方法,因為如果使用die()的話,會導致你在log檔裡面看到一堆無意義的eror log

因為每一次執行到die()就會記錄下來,雖然是正常的執行。

而另一位網友 robertodecurnex 推薦使用throw new RedirectionError(),然後統一在某個地方共同處理該項錯誤,讓你的程式碼較好維護,個人也覺得這種寫法還不錯。

集中管理Exception.

is to throw a RedirectionException and catch it on you application entry point. After that you can have all your "after *" calls (logs/close connections/what ever) 

 

連結:

https://stackoverflow.com/questions/768431/how-to-make-a-redirect-in-php

arrow
arrow
    創作者介紹
    創作者 蕭瑞文 的頭像
    蕭瑞文

    Neil的部落格

    蕭瑞文 發表在 痞客邦 留言(0) 人氣()