0

I have problem with this code:

    $parse = parse_url($url); //$url is POST from input field
    $urls = $parse['host'];

    $domain = array('mydomain.com', 'mydomain.net');

    if (!in_array($urls, $domain)) {

       echo 'invalid URL';
    }

Checking url, if not in array, give error if yes continue.... I see all similar thread but no one fix my problem.

P.S the problem is: Only give Invalid URL (in case when url is correct and in case when URL is wrong)

e.x url: mydomain.com/u/123-test need to be valid url

Kaja
  • 13
  • 4

1 Answers1

0

The main reason it is not working because your url doesn't contain the scheme http(s) part. With the http(s)://, when you try to parse_url() it returns path value not the host value

<?php
$url = 'http://yourdomain.com/u/123-test';  //$url is POST from input field
$url = parse_url($url, PHP_URL_HOST);
$domain = array('yourdomain.com', 'yourdomain.net');
if (!in_array($url, $domain)) {
     echo 'invalid URL';
    }else{
     echo 'valid URL';
}
?>  

PHP Parse URL - Domain returned as path when protocol prefix not present

DEMO: https://3v4l.org/nUCfH

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • This alters the original input. Additionally the `path` as the added note suggests won't work because it contains directories. I'd suggest the dup and prepend the protocol when not present. – user3783243 Aug 24 '19 at 17:04