ganjan
ganjan

Reputation: 7576

regex url to image in php

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?

Upvotes: 0

Views: 502

Answers (5)

Spaceghost
Spaceghost

Reputation: 6985

Have you seen this?

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

Upvotes: 1

Matt Lowden
Matt Lowden

Reputation: 2616

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;

}

Upvotes: 1

Xavier Barbosa
Xavier Barbosa

Reputation: 3947

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.

Upvotes: 0

LaGrandMere
LaGrandMere

Reputation: 10359

You can use FILTER_VALIDATE_URL.

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

Upvotes: 0

Joe
Joe

Reputation: 47609

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.

Upvotes: 1

Related Questions