2011-03-13 59 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'])); 
}