PHP - 在表单提交中检查http://或https://

时间:2014-04-24 19:07:42

标签: php variables http-headers

我对PHP很新,我正在编写HTTP请求标头检查器。它工作得很好,但是我希望检查用户是否在URL中添加了http://或https://,如果两者都没有添加,那么它应该自动将http://添加到$ url变量

我已经使用http://实现了这一点,但我无法解决如何检查https://的问题!

到目前为止我的代码如下:

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
    <input name="url" type="text" placeholder="URL">
    <input type="submit" value="Submit">
</form>
<p>
<?php
    echo $_POST['url'];
    echo "<br /> <br />";
?>
<p id="header">
<?php
    $url = $_POST['url'];
    if (empty($url)) { 
        echo "Please type a URL";
    }
    elseif (substr($url, 0, 7) !='http://' ) {
        $url = 'http://' . $url;
        $headers = get_headers($url);
    }
    else $headers = get_headers($url);
    echo "$headers[0]";
    unset($headers);
?>  
</p>

2 个答案:

答案 0 :(得分:1)

您可以通过以下方式检查https:

if ($_SERVER["HTTPS"] == "on") {
        //Its https
    }

你想要的是:

if (empty($url)) { 
        echo "Please type a URL";
    }
    elseif (!preg_match("%https?://%ix", $url) )
        $url = 'http://' . $url;
        $headers = get_headers($url);

答案 1 :(得分:0)

我猜你需要使用正则表达式:

if (preg_match('%^(http(s)?://).*$%', $url, $regs)) {
    // there is http or https protocol
    $proto = $regs[1];
} else {
    // but this can be not a valid url still...
    $url = 'http://' . $url;
}

您可以使用get_headers来确定网址是否有效,如here所示。