0

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?

1
  • What exactly are you intending to "check"? What are the criteria? Commented Jan 19, 2011 at 12:29

5 Answers 5

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;

}
Sign up to request clarification or add additional context in comments.

2 Comments

the preg_match seems to block valid urls like "itavisen.no/gfx/speedometerNy.png"
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.
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.

2 Comments

Well, you might at least test that it's a valid URL.
If that's the real question then it's a dupe of stackoverflow.com/questions/206059/php-validation-regex-for-url
1

Have you seen this?

best way to determine if a URL is an image in PHP

Comments

0

You can use FILTER_VALIDATE_URL.

Look at : parsing url - php, check if scheme exists, validate url regex

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.