0

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>

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.