简体   繁体   中英

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM