Articles

The month of PHP functions : checking on images

  • Ecrit par Julien Pauli
  • mardi 17 avril 2007
Image pour le titre du contenu

Ce document est aussi disponible en français fr 


getimagesize() return a wealth of informatino, including an image size and its type. This function is really useful to check if the image referenced by the string given as argument is a picture or not, especially after an upload. It is usually linked to GD functions, though they are totally distinct.
Example 1 - Sanity check : checking if a file contains a picture or not
<?php
if (is_uploaded_file($_FILES['myFile']['tmp_name'])){
    if (!getimagesize($_FILES['myFile']['tmp_name'])){
        "fichier image recquis";
    }
}
?>

getimagesize() also returns the tag's attribute that may be used directly in HTML tags.

Example 2 - Upload of a picture and moving to a temporary folder.

<?php
 
function html_image($image, $alignment = 'absmiddle')
 
{
 
    $desc = @getimagesize($image);
 
    return( '<IMG SRC="'.$image.'" '.$desc[3].' BORDER="0" ALIGN="'.$alignment.'">' ); 
// $desc[3] contains 'height="xxx" width="yyy"'
 
}
 
?><strong>
 
</strong>

getimagesize() gère les formats GIF, JPG, PNG, SWF, PSD, BMP, TIFF(intel byte order), TIFF(motorola byte order), JPC, JP2, JPX, JB2, SWC, IFF, WBMP, XBM. On peut donc s'en servir pour vérifier le type d'une image, quelque soit l'extension donnée au fichier, et un index retourne le type mime, qu'on peut envoyer au navigateur :

Exemple 3 - Envoi d'une image vers le navigateur, avec le bon en-tête HTTP :

<?php
 
$size = getimagesize($filename);
 
$fp = fopen($filename, "rb");
 
if ($size &amp;&amp; $fp) {
 
    header("Content-type: {$size['mime']}");
 
    fpassthru($fp);
 
    exit;
 
}
 
?><strong>
 
</strong>

Keep in mind

  • getimagesize() retunrs FALSE when the file is not a picture of a recognized type, and it will also generate a warning when the picture is not accessible.
  • getimagesize() do not require the GD library.
  • getimagesize() takes a file reference as parameter, may it be a local file, or a distant URL. It doesn't require a GD resource.
  • If you want to check other resources type, use the fileinfo extension.
< Précédent   Suivant >

Commentaires

Vous pouvez ajouter votre commentaire!


Vous devez vous connecter pour commenter