Estoy creando una página donde el usuario sube un archivo. Quiero una instrucción if para crear una variable $error si el tipo de archivo es cualquier otro jpg, gif y pdf.
Aquí está mi código:
$file_type = $_FILES['foreign_character_upload']['type']; //returns the mimetype
if(/*$file_type is anything other than jpg, gif, or pdf*/) {
$error_message="Only jpg, gif, and pdf files are allowed.";
$error="yes";
}
Tengo dificultades para estructurar la instrucción if. ¿Cómo diría eso?
Coloque los tipos permitidos en una matriz y use in_array()
.
$file_type = $_FILES['foreign_character_upload']['type']; //returns the mimetype
$allowed = array("image/jpeg", "image/gif", "application/pdf");
if(!in_array($file_type, $allowed)) {
$error_message="Only jpg, gif, and pdf files are allowed.";
$error="yes";
}
editar
Acabo de darme cuenta de que también desea permitir archivos PDF. En ese caso echa un vistazo Clase y funciones de Fileinfo de PHP. Pero en lo que respecta a la seguridad, aún no debe confiar en $_FILES[]['type']
🙂
Dejo el resto aquí por si le sirve a alguien más que encuentre esta pregunta
Para comprobar el tipo mime de la imagen, $_FILES[]['type']
podría ser inseguro. Estos datos son enviados por el navegador y podrían falsificarse fácilmente.
Deberías usar el getimagesize()
función si solo desea permitir que se carguen imágenes (a pesar de su nombre quizás engañoso). Esta función no solo le dará el tamaño, sino todos los datos que probablemente necesitará sobre la imagen.
Usé el siguiente script en una clase de manejo de imágenes:
private function load_image_data($image_file) {
// Firstly, to disambiguate a loading error with a nonexistant file error,
// check to see if the file actually exists.
if( ! file_exists($image_file) ) {
throw new Nonexistent_Image_Exception("The file '{$image_file}' does not exist");
}
// We're going to check the return value of getimagesize, so we don't
// need any pesky warnings or notices popping up, since we're going to
// stop execution of this function if something goes wrong.
$image_data = @getimagesize($image_file);
if( $image_data === false ) {
throw new Load_Image_Exception("Could not get image data from '{$image_file}'");
}
$this->size = new Dimensions($image_data[0], $image_data[1]);
$this->mime = $image_data['mime'];
}
Darse cuenta de getimagesize()
devuelve una matriz asociativa que contiene un índice ‘mimo’. Los datos aquí son confiables.
En otra función verifiqué el tipo mime de la imagen y la convertí a PNG con la función GD apropiada:
private function load_image($image_file) {
// Suppress warning messages because we're going to throw an
// exception if it didn't work instead.
switch( $this->mime ) {
case 'image/jpeg':
case 'image/pjpeg':
$this->image = @imagecreatefromjpeg($image_file);
break;
case 'image/gif':
$this->image = @imagecreatefromgif($image_file);
break;
case 'image/png':
$this->image = @imagecreatefrompng($image_file);
break;
default:
throw new Invalid_Image_Exception("The image was of an invalid type");
}
if( $this->image === false ) {
throw new Load_Image_Exception("Loading of image '{$image_file}' failed");
}
}
Probablemente no necesite hacer todo esto, pero puede ver qué tipos MIME aparecen para los tipos de archivo que ha especificado. Tenga en cuenta que un jpeg podría tener dos tipos de mimo diferentes.
Espero que esto ayude.
Ver también Marco Zend‘s Zend_File_Transfer_Adapter_Http y
Zend_Form_Element_File. Puede agregar múltiples validadores diferentes como resolución mínima de imagen, tipo MIME, tamaño mínimo de archivo, extensiones de archivo permitidas, etc.
Usa este sencillo código…
<?
$path = $_FILES['file']['name']; // file means your input type file name
$ext = pathinfo($path, PATHINFO_EXTENSION);
if ($ext=="jpg" OR $ext=="jpeg" OR $ext=="gif" OR $ext=="png") {
// your code here like...
echo "Upload successful";
}else{
// your invalid code here like...
echo "Invalid image format. Only upload JPG or JPEG or GIF or PNG";
}
?>