Pergunta

I'm fairly new to PHP and I am writing a HTTP request header checker. It is working fairly well, but I would like it to check whether the user has added either http:// or https:// to the URL and if neither have been added then it should automatically add http:// to the $url variable.

I have already acheived this with just http:// but I can't work out how to get it to check https:// too!

The code that I have so far is below:

<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>
Foi útil?

Solução

You can Check for https by:

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

What You Want is:

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

Outras dicas

I guess you need to use regex:

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;
}

And you can use get_headers to identify if url is valid, like is showed here.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top