Aurazo Script
Aurazo Script

Reputation: 115

PHP Check for HTTP and HTTPS in the submitted URL through FORM

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.

Upvotes: 1

Views: 69

Answers (3)

Accountant م
Accountant م

Reputation: 7523

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

Upvotes: 1

user2182349
user2182349

Reputation: 9782

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

Upvotes: 1

user3783243
user3783243

Reputation: 5224

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

if(!preg_match("@^https?://@i",$turl)){

Upvotes: 3

Related Questions