I am making a profile page where users can set an url to their profile image. How do I check this with regex for example?
5 Answers
You can use cURL for the mime. For the URL validation I use the following, but there are loads out there. You can use FILTER_VALIDATE_URL but it can contain bugs; http://bugs.php.net/51192.
$url='image.png';
if( preg_match("#((http|https|ftp)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)#ie", $url) ){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, 'http://yoursite.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_exec($ch);
$mime = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
curl_close($ch);
print $mime;
}
2 Comments
ganjan
the preg_match seems to block valid urls like "itavisen.no/gfx/speedometerNy.png"
Matt Lowden
I've updated it, as there were some other errors with it. I generally prefer that URLs are prefixed with HTTP. Personal preference :) but I use this for URLs that will be placed into the href of the HTML base tag.
You can't. Any file can be served at any address. You'd need to check the Content-Type returned by the URL, and probably the format of the image too.
2 Comments
Felix Dombek
Well, you might at least test that it's a valid URL.
Joe
If that's the real question then it's a dupe of stackoverflow.com/questions/206059/php-validation-regex-for-url
You can use FILTER_VALIDATE_URL.
Look at : parsing url - php, check if scheme exists, validate url regex