1

I have this code which checks for http:// in the URL submitted. But I want it to also check for https://. So I tried with an or in the if condition but it still checks only for http:// and not https://.

Here is my code.

if(!preg_match("@^http://@i",$turl) or !preg_match("@^https://@i",$turl)){
  $msg = "<div class='alert alert-danger'>Invalid Target URL! Please input a standard URL with <span class='text-info'>http://</span> for example <span class='text-info'>http://www.kreatusweb.com</span> </div>";
}

If I now put https:// in the URL and submit, it still returns this error message as now http:// is false here. What logic or code should I use here to check for both. I just don't want users to submit www.somewebsite.com. I want them to submit full URL using either http:// or https://. If either of these two exists in the URL then only the form will be processed further.

3 Answers 3

3

You can simplify the regex so the s is optional by just adding a ? after it.

if(!preg_match("@^https?://@i",$turl)){
Sign up to request clarification or add additional context in comments.

Comments

1

replace the or with &&

if(!preg_match("@^http://@i",$turl) && !preg_match("@^https://@i",$turl))

I used to do this logic mistake when I started to code because you think like this if (not something or not somethingelse)

but doing if (!http || !https) will return true in both http and https because

1- if it is http, then the !https part will return true

2- if it is https, then the !http part will return true too

2 Comments

That worked. How could I miss checking it with && operator. Feeling funny. Maybe because I haven't slept overnight. My mind needs some serious rest. Thanks anyway. I can go to bed now. :)
You are welcome, yes most of the nights I sleep with unresolved problems in, I find the solution in the next day morning. Go get some rest :)
1

Check out the PHP validate filters at http://php.net/manual/en/filter.filters.validate.php.

<?php

$arr = [ 'http:example.com','https:/example.com','https://www.example.com','http://example.com',
'ftp://example.com','www.example.com','www.example.com/test.php','https://www.example.com/test.php?q=6'];

foreach ($arr as $str) {
    $filtered = filter_var($str,FILTER_VALIDATE_URL,FILTER_FLAG_SCHEME_REQUIRED|FILTER_FLAG_HOST_REQUIRED);
    if (!empty($filtered)) {
        if (stripos($filtered,'http') === 0) {
            echo $str.' is valid'.PHP_EOL;
        } else {
            echo $str.' is a valid URL, but not HTTP'.PHP_EOL;
        }
    } else {
        echo $str.' is not a valid URL'.PHP_EOL;
    }
}

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.