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?
Asked
Active
Viewed 485 times
0
-
What exactly are you intending to "check"? What are the criteria? – Lightness Races in Orbit Jan 19 '11 at 12:29
5 Answers
1
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.

Joe
- 46,419
- 33
- 155
- 245
-
-
If that's the real question then it's a dupe of http://stackoverflow.com/questions/206059/php-validation-regex-for-url – Joe Jan 19 '11 at 13:36
1
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;
}

Matt Lowden
- 2,586
- 17
- 19
-
the preg_match seems to block valid urls like "http://www.itavisen.no/gfx/speedometerNy.png" – ganjan Jan 19 '11 at 12:33
-
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. – Matt Lowden Jan 19 '11 at 12:55
0
You can use FILTER_VALIDATE_URL
.
Look at : parsing url - php, check if scheme exists, validate url regex

Community
- 1
- 1

LaGrandMere
- 10,265
- 1
- 33
- 41
0
First test that is a valid url with filter_var()
$url = filter_var($variable, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED);
Then you'll need to download the resource, and test locally if it's an image.

Xavier Barbosa
- 3,919
- 1
- 20
- 18