2011-09-12 16 views

risposta

4

immagino getimagesize:

list($width, $height, $type, $attr) = getimagesize("path/to/image.jpg"); 

if (isset($type) && in_array($type, array(
    IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF))) { 
    ... 
} 
+5

Leggi documentazione: non utilizzare getimagesize() per verificare che un determinato file sia un'immagine valida. http://php.net/manual/en/function.getimagesize.php –

-1

Io uso questa funzione ... controlla gli URL troppo

function isImage($url){ 
    $params = array('http' => array(
       'method' => 'HEAD' 
      )); 
    $ctx = stream_context_create($params); 
    $fp = @fopen($url, 'rb', false, $ctx); 
    if (!$fp) 
     return false; // Problem with url 

    $meta = stream_get_meta_data($fp); 
    if ($meta === false){ 
     fclose($fp); 
     return false; // Problem reading data from url 
    } 
} 
+0

sì hai ragione ... aggiunto parentesi. –

24

exif_imagetype è una soluzione migliore.

Questo metodo è più veloce rispetto all'utilizzo di getimagesize. Per quotare php.net "Il valore restituito è lo stesso valore che getimagesize() restituisce nell'indice 2 ma exif_imagetype() è molto più veloce."

if(exif_imagetype('path/to/image.jpg')) { 
    // your image is valid 
} 
+1

Ovviamente funziona solo quando l'estensione EXIF ​​è abilitata. Nel mio caso non è il caso e non ho alcun controllo su questo :( –

-1

Io uso questo:

function is_image($path) 
{ 
    $a = getimagesize($path); 
    $image_type = $a[2]; 

    if(in_array($image_type , array(IMAGETYPE_GIF , IMAGETYPE_JPEG ,IMAGETYPE_PNG , IMAGETYPE_BMP))) 
    { 
     return true; 
    } 
    return false; 
} 
1

exif_imagetype è molto più veloce di getimagesize e non usa gd-Lib (lasciando una più snella impronta mem)

function isImage($pathToFile) 
{ 
    if(false === exif_imagetype($pathToFile)) 
    return FALSE; 

    return TRUE; 
} 
2

Come raccomandato dal PHP documentation:

"Non utilizzare getimagesize() per verificare che un determinato file sia un'immagine valida. Utilizzare ap soluzione appositamente creata come l'estensione Fileinfo. "

Ecco un esempio:

$finfo = finfo_open(FILEINFO_MIME_TYPE); 
$type = finfo_file($finfo, "test.jpg"); 

if (isset($type) && in_array($type, array("image/png", "image/jpeg", "image/gif"))) { 
    echo 'This is an image file'; 
} else { 
    echo 'Not an image :('; 
} 
Problemi correlati