PHP-在URL中将http替换为https

PHP-在URL中将http替换为https,php,html,checkbox,Php,Html,Checkbox,我试图弄清楚,一旦用户选中html表单中的一个框,如何在HTTP之后添加s 我的PHP中有 $url = 'http://google.com'; if(!isset($_POST['https'])) { //something here } 因此,基本上,当用户选中一个名为“https”的框时,我想将s添加到$url的http中 我对PHP知之甚少,如果有人能向我解释如何做这件事,这将非常有帮助!谢谢。单程: $url = '%s//google.com'; $protocol =

我试图弄清楚,一旦用户选中html表单中的一个框,如何在HTTP之后添加s

我的PHP中有

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

if(!isset($_POST['https'])) { 
  //something here
}
因此,基本上,当用户选中一个名为“https”的框时,我想将s添加到$url的http中

我对PHP知之甚少,如果有人能向我解释如何做这件事,这将非常有帮助!谢谢。

单程:

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

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

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

我不知道在用户选中复选框之前,您希望在多少页上发生这种情况,但有一个答案是JavaScript和标记

使用
base
标记,您可以强制使用不同的来源,您的相对URL-s将根据不同的来源进行解析

如果您在表单中使用它,并且用户勾选复选框,则所有其他页面都将从https站点查看,因此您可以在任何地方使用相对URL-s,只要在用户想要更改站点表单或http时插入不同的
base
标记即可


注意:直接传递1将抛出致命错误(致命错误:只有变量可以通过引用传递),因此您必须通过引用传递最后一个参数。

不替换包含其他URL的URL的解决方案,例如

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

当您考虑大小写不敏感时,使用函数.< /P> 例如:

或者,如果您想替换CDN文件中的URL方案。 例子: 这个。。。(使用https:')
谢谢你的代码,但我不能分解$url,因为它在前面的函数中使用,需要整个url。还有其他方法吗?@usr122212:请参阅@edorian的答案。这是一个很好的解决方案,但对于区分大小写的应用程序更好:
$url=preg\u replace(“/^http:/i”,“https:”,$url)我测试了这个解决方案,不幸的是,这不起作用,我用“str_replace”尝试了下一个解决方案并得到了结果。str_replace对我不起作用,但原来的解决方案起作用了。同样非常感谢这个伟大的解决方案,它避免了wordpress主题im定制带来的一个巨大问题,否则会通过SSL强制混合内容并中断SSL连接。它会抛出一个错误,因为
$count
只会包含执行的替换次数。它不是一个用来设置边界的参数。
$url = str_replace( 'http://', 'https://', $url );
$count = 1;
$url = str_replace("http://", "https://", $url, $count);
$desiredScheme = "http"; // convert to this scheme;
$parsedRedirectUri = parse_url($myCurrentUrl);
if($parsedRedirectUri['scheme'] !== $desiredScheme) {
    $myCurrentUrl= substr_replace($myCurrentUrl, $desiredScheme, 0, strlen( $parsedRedirectUri['scheme'] ));
}
$url = str_ireplace( 'http://', 'https://', $url );
$url = str_ireplace( 'http:', 'https:', $url );
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>