問題描述
我在網上看到很多教程說你需要檢查 $_SERVER['HTTPS']
如果服務器的連接是用 HTTPS 保護的.我的問題是,在我使用的某些服務器上,$_SERVER['HTTPS']
是一個未定義的變量,會導致錯誤.是否有另一個我可以檢查的變量應該始終定義?
為了清楚起見,我目前正在使用此代碼來解析它是否是 HTTPS 連接:
if(isset($_SERVER['HTTPS'])) {if ($_SERVER['HTTPS'] == "on") {$secure_connection = 真;}}
即使 $_SERVER['HTTPS']
未定義,這也應該始終有效:
function isSecure() {返回(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')||$_SERVER['SERVER_PORT'] == 443;}
代碼與 IIS 兼容.
來自 PHP.net 文檔和用戶評論:
<塊引用>如果腳本是通過 HTTPS 協議查詢的,則設置為非空值.
請注意,將 ISAPI 與 IIS 一起使用時,該值將為關閉";如果請求不是通過 HTTPS 協議發出的.(對于作為 Fast-CGI 應用程序運行 PHP 的 IIS7,已報告了相同的行為).
此外,即使安全連接,Apache 1.x 服務器(和損壞的安裝)也可能沒有定義 $_SERVER['HTTPS']
.雖然不能保證,但根據約定,端口 443 上的連接很可能使用 安全套接字,因此需要額外的端口檢查.
附加說明:如果客戶端和您的服務器之間存在負載均衡器,則此代碼不會測試客戶端與負載均衡器之間的連接,而是測試負載均衡器與您的服務器之間的連接.要測試之前的連接,您必須使用 HTTP_X_FORWARDED_PROTO
標頭進行測試,但這樣做要復雜得多;請參閱此答案下方的最新評論.
I've seen many tutorials online that says you need to check $_SERVER['HTTPS']
if the server is connection is secured with HTTPS. My problem is that on some of the servers I use, $_SERVER['HTTPS']
is an undefined variable that results in an error. Is there another variable I can check that should always be defined?
Just to be clear, I am currently using this code to resolve if it is an HTTPS connection:
if(isset($_SERVER['HTTPS'])) {
if ($_SERVER['HTTPS'] == "on") {
$secure_connection = true;
}
}
This should always work even when $_SERVER['HTTPS']
is undefined:
function isSecure() {
return
(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
|| $_SERVER['SERVER_PORT'] == 443;
}
The code is compatible with IIS.
From the PHP.net documentation and user comments :
Set to a non-empty value if the script was queried through the HTTPS protocol.
Note that when using ISAPI with IIS, the value will be "off" if the request was not made through the HTTPS protocol. (Same behaviour has been reported for IIS7 running PHP as a Fast-CGI application).
Also, Apache 1.x servers (and broken installations) might not have $_SERVER['HTTPS']
defined even if connecting securely. Although not guaranteed, connections on port 443 are, by convention, likely using secure sockets, hence the additional port check.
Additional note: if there is a load balancer between the client and your server, this code doesn't test the connection between the client and the load balancer, but the connection between the load balancer and your server. To test the former connection, you would have to test using the HTTP_X_FORWARDED_PROTO
header, but it's much more complex to do; see latest comments below this answer.
這篇關于如何在沒有 $_SERVER['HTTPS'] 的情況下確定您是否使用 HTTPS的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!