phpfunctionparse-url

Input url validation php


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


Solution

  • 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