Subir imágenes con PHP [The Image Uploader Class]

Existen muchas formas de subir imágenes a un directorio con PHP. En esta ocasión se trata de una clase en PHP que facilita este proceso. Esta clase no solo sube la imagen a tu servidor sino que crea un thumbnails (previa pequeña de la imagen original). Soporta gif, jpg y png.

bme_image_uploader.class.php

<?php
session_start();

class bme_ImageUploader
{

function bme_ImageUploader($maxwidth, $maxheight, $max_filesize, $fieldname)
{

//config all values needed for image uploads
$this->maxwidth = $maxwidth;
$this->maxheight = $maxheight;
$this->max_filesize = $max_filesize;
$this->field = $_FILES[$fieldname]['name'];
$this->field_type = $_FILES[$fieldname]['type'];
$this->field_temp = $_FILES[$fieldname]['tmp_name'];
$this->field_size = $_FILES[$fieldname]['size'];
$this->max_filesize_kb = ($this->max_filesize / 1024);
$this->types_array = array('image/gif','image/pjpeg','image/jpeg','image/jpg','image/x-png','image/png');

}

function uploadfolder()
{
return $this->upload_folder;
}

function upload_image_typecheck()
{
if(!in_array($this->field_type, $this->types_array))
{
$this->is_pic_error = "That file type is not allowed!<br />Allowed File Types: <b>jpg, gif, png</b><br />";
$this->pic_error = TRUE;
}
}

function upload_image_size()
{
$this->imagesize = getimagesize($this->field_temp);
return $this->imagesize;
}

function upload_image_sizecheck()
{
if($this->field_size > $this->max_filesize)
{
$this->is_pic_error = "Your image is too large at ".$this->field_size." kb<br /> Files may be up to ".$this->max_filesize_kb."kb<br />";
$this->pic_error = TRUE;
}
}

function upload_image_width()
{
$this->imagewidth = $this->imagesize[0];
return $this->imagewidth;
}

function upload_image_height()
{
$this->imageheight = $this->imagesize[1];
return $this->imageheight;
}

function upload_image_wh_check()
{
if($this->imagewidth > $this->maxwidth || $this->imageheight > $this->maxheight)
{
$this->is_pic_error = "Your image: ".$this->field." is too large at ".$this->imagewidth."px x ".$this->imageheight."px<br />Files may be up to ".$this->maxwidth."px x ".$this->maxheight."px in size<br />";
$this->pic_error = TRUE;
}
}

function upload_image($extension='', $folder='', $upload_name)
{
//Run error checks
$this->upload_image_typecheck();
$this->uploadfolder();
$this->upload_image_size();
$this->upload_image_width();
$this->upload_image_height();
$this->upload_image_sizecheck();
$this->upload_image_wh_check();
$this->upload_session_name = $upload_name;

//If no errors are thrown and all is well, lets upload the image shall we?
if($this->pic_error == FALSE)
{
//what extenstion are we adding before the image name?
if($extension == FALSE){$this->uniq = date( "m-d-Y-G-i-s" )."_";}else{$this->uniq = $extension;}
//what folder are we uploading image to?
if($folder == FALSE){$this->upload_folder = "imgs";}else{$this->upload_folder = $folder;}

$this->ext = strtolower($this->field);
$this->ext = preg_replace('/\s\s+/', '', $this->ext);
$this->ext = preg_replace('/\'/', '', $this->ext);
$this->ext = str_replace ( ' ', '-', $this->ext );
move_uploaded_file($this->field_temp, $this->upload_folder."/".$this->uniq.$this->ext ) or die ("Couldn't upload ".$this->field."<br />");

//sweet! now the image is uploaded lets go ahead and tell ourselves the name of the new image
$this->upload_image_url();

//UH-OH! Something went wrong. The user was probably stupid, so we shall now tell them what they did wrong
}else{
echo "<div class=\"error\">".$this->is_pic_error."</div>";
}
}

function upload_image_url()
{
$this->newimgurl = "{$this->uniq}{$this->ext}";

$_SESSION['img_upload_success'] = TRUE;
$_SESSION['img_upload_folder'] = $this->upload_folder;
$_SESSION['img_upload_name'] = $this->newimgurl;
$_SESSION[$this->upload_session_name] = $this->newimgurl;

}

function uploaded_image()
{

return $this->newimgurl;

}
function upload_image_reset()
{
$_SESSION['img_upload_success'] = FALSE;
$_SESSION['img_upload_folder'] = FALSE;
$_SESSION['img_upload_name'] = FALSE;
$_SESSION[$this->upload_session_name] = FALSE;

}

function resizeImage($twidth="80", $theight="80", $text="thumb_")
{

if($this->pic_error == FALSE)
{
$n_width = (int)$twidth;
$n_height =(int)$theight;
$tsrc = $this->upload_folder."/ss/".$text.$this->uniq.$this->ext;


if($this->field_type=="image/pjpeg" || $this->field_type=="image/jpeg" || $this->field_type=="image/jpg")
{
$im=ImageCreateFromJPEG($this->upload_folder."/".$this->uniq.$this->ext);
$width=ImageSx($im); // Original picture width is stored
$height=ImageSy($im); // Original picture height is stored
$newimage=imagecreatetruecolor($n_width,$n_height);
imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
imagejpeg($newimage,$tsrc);
}elseif($this->field_type=="image/gif")
{
$im=ImageCreateFromGIF($this->upload_folder."/".$this->uniq.$this->ext);
$width=ImageSx($im); // Original picture width is stored
$height=ImageSy($im); // Original picture height is stored
$newimage=imagecreatetruecolor($n_width,$n_height);
imagecopyresampled($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
//imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
imagegif($newimage,$tsrc);
}elseif($this->field_type=="image/x-png" || $this->field_type=="image/png")
{
$im=ImageCreateFromPNG($this->upload_folder."/".$this->uniq.$this->ext);
$width=ImageSx($im); // Original picture width is stored
$height=ImageSy($im); // Original picture height is stored
$newimage=imagecreatetruecolor($n_width,$n_height);
imageCopyResized($ newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
imagepng($newimage,$tsrc);
}
}
}
}
?>

Ahora para que no tengamos problemas al probar esta clase crea en la misma carpeta donde esta tu clase un carpeta con el nombre gallery y dentro de ésta crea otra carpeta con el nombre ss. En gallery irán las imágenes subidas y en ss los thumbnails (todo esto puedes configurar luego).

Finalmente este es el ejemplo (con la explicación pertinente en inglés) que irá en la carpeta donde está la clase.

index.php

<?php

if($_POST['doaddpic'])
{
/*
IMPORTANT INSTALL INSTRUCTIONS!!!!
(the zip this came in should be correctly ordered.. if not read below)

With the default setup below You will need to create 3 folders.
1. The folder in which index.php and bme_image_uploader.class.php are to be placed in (both in same folder)
2. A folder within the above folder named: gallery
3. A folder within the gallery folder named: ss


This is a simple image uploader class.
Below you will find comments and examples showing how to use it.
This is mainly for those who need a simple single image uploader or those who are trying to learn how to do it.
If you need multiple image uploading, you would need to change the code.

I currently use this code(although modified to fit my CMS system) on [url]http://i-am-mean.com[/url]
The modifictions I made to make this a public release, did not include the core class,
just the below code to make it work without having to use my CMS system
You can easily incorporate Database usage to make a gallery, however for this demo purpose
it uses SESSIONS to display the currently uploaded image
*/

include('bme_image_uploader.class.php');

// !IMPORTANT! This is how we know what to call your image for display purposes!
// If by chance there is a conflict of SESSION names in other code, you can change the name here
$image_session_upload_name = "image_gallery";


// bme_ImageUploader should be easy to understand minus the last one for some.
// The last argument is telling what field name it should be expecting for the image
$addpic = new bme_ImageUploader($maxwidth=1000, $maxheight=1000, $max_size=512000, $fieldname=upload_image);


// upload_image takes 3 arguments.
// 1. What do you want the image to be renamed too once it is uploaded
// The default setting is date/time/second
// No matter what, the original name will be added to this
//
// 2. The folder in which the original and thumbnail image will be uploaded to.
// Currently it is set to 'gallery'
//
// 3. The Image Session Upload Name, set up using $image_session_upload_name = "image_gallery" from above
// This is how we know what the name of the image is for showing it right after it was uploaded
$addpic->upload_image(0,"gallery", "$image_session_upload_name");


// resizeImage: in case you want to create a thumbnail of the image as well as keep the original
// The two arguments here are Width and Height
// The default Width/Height are: 80x80
// It also can take an optional 3rd argument, which like above... will rename it to be whatever you want it to be
// The new name would be added to the original. Default is: thumb_
$addpic->resizeImage("100", "100");


//Here is a simple example form demonstrating usage
//Should be easy to understand
echo "
<form name='upload_image' method='post' action='' enctype='multipart/form-data'>
<strong>UPLOAD IMAGE</strong><br />
<input name='upload_image' type='file' style='cursor:pointer' /><br />
<input name='doaddpic' type='submit' value='Upload Image' />
</form>
<br /><br />";

//Here we check to see if an image was properly uploaded before we try to display it
if($_SESSION[$image_session_upload_name] == TRUE)
{
echo "
SCREENSHOT:
<input name='image' type='hidden' class='textfield' id='image' value='{$_SESSION["$image_session_upload_name"]}' /><br />
<img src=$_SESSION[img_upload_folder]/ss/thumb_{$_SESSION["$image_session_upload_name"]}>

<br /><br />
Normalized:
<input name='image' type='hidden' class='textfield' id='image' value='{$_SESSION["$image_session_upload_name"]}' /><br />
<img src=$_SESSION[img_upload_folder]/{$_SESSION["$image_session_upload_name"]}>
";

//Once the picture has been displayed for the user, lets go ahead and clear the session
//containing the image name. We do this so we can continue to upload another picture
//Yes, this is why you can only use this code as a SINGLE IMAGE UPLOADER
//without modifying how uploaded pictures are displayed.
$addpic->upload_image_reset();
}


}else{

echo "
<form name='upload_image' method='post' action='' enctype='multipart/form-data'>
<strong>UPLOAD IMAGE</strong><br /><br />
<input name='upload_image' type='file' style='cursor:pointer' /><br />
<input name='doaddpic' type='submit' value='Upload Image' />
</form><br /><br />
";
}

?>

Y realmente funciona, muy útil. Evitaremos rompernos la cabeza usando esta sencilla clase.

Vía Digg | Fuente CodeHeretic

8 thoughts on “Subir imágenes con PHP [The Image Uploader Class]

  1. Puede ser que la “clase” sea funcional, pero esta mal diseniada, esta en php 4, no respeta ninguna propiedad de POO, y sobre todo es inentendible, y no esta documentada.
    Voy a tratar de tomar la idea y hacer algo mas claro.
    Saludos.

  2. despues de ordenarla hice una prueba y funciona, solo abria que editar el precedente que el año mes dias hora minuto y segundo mas el nombre de archivo se hace muy largo
    GRACIAS

  3. disculpen queria saber si el script era seguro porque agarre una shell y le cambie de extencion a .jpg y lo subi con el script me di cuenta de que boto unos warning y subio la imagen…
    dejo etos errores
    [code]
    Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG library reports unrecoverable error: in C:\AppServ\www\img\bme_image_uploader.class.php on line 146
    Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: ‘fotos_modelos/06-30-2009-10-57-36_bio.jpg’ is not a valid JPEG file in C:\AppServ\www\img\bme_image_uploader.class.php on line 146
    Warning: imagesx(): supplied argument is not a valid Image resource in C:\AppServ\www\img\bme_image_uploader.class.php on line 147
    Warning: imagesy(): supplied argument is not a valid Image resource in C:\AppServ\www\img\bme_image_uploader.class.php on line 148
    Warning: imagecopyresized(): supplied argument is not a valid Image resource in C:\AppServ\www\img\bme_image_uploader.class.php on line 150
    [/code]
    alguan solucion ?

  4. La clase no se entiende muy bien, pero aun asi tuve algunas ideas, la voy a documentar y a mejora para despues pasarsela, lo que voy a cambiar es q las los thumbsnails no se deformen, cosa que actualmente hace.
    Cuado la tenga la subo.
    Gracias de todas formas.

  5. Que bueno que no leí todos los comentarios antes de probarla… por que seguramente no la habria implementado.
    Pero lo hice y funciona MUY BIEN, les recomiendo lo prueben en un servidor live. Es muy sencillo, pongan los archivos en un folder y dentro de este el folder “galeries” y DENTRO de este, uno que se llame “ss”. Gracias por publicarlo.

Leave a Reply

Your email address will not be published. Required fields are marked *

Proudly powered by WordPress | Theme: Wanderz Blog by Crimson Themes.