简体   繁体   中英

filter_var($url, FILTER_VALIDATE_URL) acting weird in PHP 5.3.2

For some weird reason the function below says this url "paradox-productions.net" is invalid on http://alpha.shurl.be/ and valid on my localhost. Is it a bug in PHP or what could cause this? Anyone who can confirm this? Possible to solve or do I need a PHP upgrade on my server?

phpinfo: http://alpha.shurl.be/phpinfo.php

function:

 <?php function validUrl($url) { var_dump($url); if(strpos($url, ".") !== false) { var_dump($url); if(strpos($url, "://") === false) { $url = "http://" . $url; var_dump($url); } } if(filter_var($url, FILTER_VALIDATE_URL)) { echo "VALID\\n"; } else { echo "INVALID\\n"; } var_dump(filter_var($url, FILTER_VALIDATE_URL)); return filter_var($url, FILTER_VALIDATE_URL); } ?> 

This is a known bug in PHP 5.3.2. It thinks URL's with dashes in them are invalid. See https://bugs.php.net/bug.php?id=51258 . Your local PHP must be a different version where this bug is not present.

If you can upgrade to a working version, probably a good idea to do so. If you can't, you can work around this by removing all dashes separated by other valid url characters from the string before validating. The below regex is not perfect, but it should work if you know the dashes will only appear between letters, digits, or underscores (typically true, but just be aware of the caveat that this will not deal with certain unlikely edge cases).

$url_to_validate = preg_replace("/([\w\d])-(?=[\w\d])/", '\\1\\2', $url);

\\w means "any letter or underscore" and \\d means "any digit", so [\\w\\d] means any letter, digit, or underscore. The second one requires a zero-width positive lookahead assertion (using (?=...) ) to make sure it catches all the dashes in sequences like abcde (without it, it would miss every other dash in that sequence).

Here's the body of the bug report:

Description:

FILTER_VALIDATE_URL does not allow dashes/hyphens in the host name. That's just silly.

Test script:

 $ php -r 'var_dump(filter_var("http://www.something.com/", FILTER_VALIDATE_URL));' $ php -r 'var_dump(filter_var("http://www.some-thing.com/", FILTER_VALIDATE_URL));' 

Expected result:

 $ php -r 'var_dump(filter_var("http://www.something.com/", FILTER_VALIDATE_URL));' string(25) "http://www.something.com/" $ php -r 'var_dump(filter_var("http://www.some-thing.com/", FILTER_VALIDATE_URL));' string(26) "http://www.some-thing.com/" 

Actual result:

 $ php -r 'var_dump(filter_var("http://www.something.com/", FILTER_VALIDATE_URL));' string(25) "http://www.something.com/" $ php -r 'var_dump(filter_var("http://www.some-thing.com/", FILTER_VALIDATE_URL));' bool(false) 

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