2011-03-13 57 views
13

我想知道如何在用戶選中HTML表單中的一個框後,在HTTP之後添加s。PHP - 在URL中用http替換http

我在PHP,

$url = 'http://google.com'; 

if(!isset($_POST['https'])) { 
    //something here 
} 

因此,基本上,當用戶檢查箱子的名稱=「https」開頭,我想s添加到$ URL的HTTP使其https://google.com

我對PHP知之甚少,如果有人能向我解釋如何去做這件事,這將是非常有用的!謝謝。

回答

2

方式一:

$url = '%s//google.com'; 
$protocol = 'http:'; 

if(!isset($_POST['https'])) { 
    $protocol = 'https:'; 
} 

$url = sprintf($url, $protocol); 
+0

感謝您的代碼,但因爲它是在以前的使用,我不能拆散$網址的解決方案需要整個網址的功能。會不會有另一種方式呢? – 2011-03-13 12:20:19

+0

@ usr122212:查看@ edorian的回答。 – 2011-03-13 12:21:32

50
$url = preg_replace("/^http:/i", "https:", $url); 
+1

很好的解決方案,但它對incase敏感: '$ url = preg_replace(「/^http:/ i」,「https:」,$ url);' – 2014-04-22 05:33:07

+1

我測試了這個解決方案,不幸的是這不起作用,我用「str_replace」嘗試了下一個解決方案並獲得結果。 – Mimouni 2016-09-27 15:09:42

1

我不知道你想要多少頁這樣的事情發生以後的用戶檢查框,但一個答案是JavaScript和base標籤。

使用base標記,您可以強制使用不同的來源,您的相對URL將被解析爲什麼。

我你正在使用它INA形式,用戶蜱他們sumbits形式的複選框,所有其他頁面將從HTTPS現場查看,這樣你就可以使用相對URL-S無處不在,只需插入不同base當用戶想要更改網站表單或http(s)時標記。

10
$url = str_replace('http://', 'https://', $url); 
0
$count = 1; 
$url = str_replace("http://", "https://", $url, $count); 

注:傳遞1直接將拋出致命錯誤(致命錯誤:只有變量可以通過引用傳遞),所以你必須按引用傳遞它最後一個參數。

+1

它會拋出一個錯誤,因爲'$ count'只會包含執行的替換次數。這不是用來設置邊界或任何東西的參數。 – 2015-03-13 13:29:15

1

不取代包含其他URL網址,例如http://foo.com/redirect-to/http://newfoo.com

$desiredScheme = "http"; // convert to this scheme; 
$parsedRedirectUri = parse_url($myCurrentUrl); 
if($parsedRedirectUri['scheme'] !== $desiredScheme) { 
    $myCurrentUrl= substr_replace($myCurrentUrl, $desiredScheme, 0, strlen($parsedRedirectUri['scheme'])); 
}