Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZF2 Http uri validation

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

like image 453
directory Avatar asked Dec 27 '22 13:12

directory


2 Answers

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";
    }
}
like image 174
kierzniak Avatar answered Dec 29 '22 11:12

kierzniak


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

like image 42
Diemuzi Avatar answered Dec 29 '22 11:12

Diemuzi