ZF2 Http uri validation

痴心易碎 提交于 2019-12-07 07:49:21

问题


I try to validate an URI with ZF2. The problem is when I set $value as 'http://google.com' or 'google/com', it gives me both an output 'bool(false)'.

My code;

use Zend\Uri\Http as ValidateUri;
use Zend\Uri\Exception as UriException;


    class Domain
    {
        public function domain($value)
        {
            return $this->validate($value);
        }

        public function validate($value)
        {   
            if (empty($value) || !is_string($value)) {
                return false;
            }

            try {
                $uriHttp = ValidateUri::validateHost($value);
                var_dump($uriHttp);
            } catch (UriException $e) {
                return false;
            }

            return true;
        }
    }

Thanks in advance! Nick


回答1:


I'm recommending to use validator Zend\Validator\Hostname. Example from documentation:

$hostname  = 'http://google.com';
$validator = new Zend\Validator\Hostname(Zend\Validator\Hostname::ALLOW_DNS);

if ($validator->isValid($hostname)) {
    // hostname appears to be valid
   echo 'Hostname appears to be valid';
} else {
    // hostname is invalid; print the reasons
    foreach ($validator->getMessages() as $message) {
        echo "$message\n";
    }
}



回答2:


As of right now your validator will fail as http://google.com is not a valid hostname. However, google.com is valid.

What you should have: $hostname = 'google.com';




回答3:


Try it:

public function isValidUrl($url) {
    $uri = new \Zend\Validator\Uri();
    if (!$uri->isValid($url)) {
        return FALSE;
    }
    $parseUrl = parse_url($url);
    if(!isset($parseUrl['host']) || empty($parseUrl['host'])) {
        return FALSE;
    }
    $validator = new \Zend\Validator\Hostname(\Zend\Validator\Hostname::ALLOW_DNS);
    if (!$validator->isValid($parseUrl['host'])) {
        return FALSE;
    }
    if (!filter_var($parseUrl['host'], FILTER_VALIDATE_URL) === false) {
        return FALSE;
    }
    return TRUE;
}


来源:https://stackoverflow.com/questions/13893631/zf2-http-uri-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!