Pregunta

Estoy haciendo una página donde el usuario sube un archivo.Quiero una instrucción if para crear un $variable de error si el tipo de archivo no es otra cosa 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';
}

Estoy teniendo dificultad para estructurar la instrucción if.Cómo iba yo a decir eso?

¿Fue útil?

Solución

Ponga los tipos permitidos en una matriz y utilizar 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';
}

Otros consejos

editar

Me acabo de dar cuenta que desea permitir que los archivos PDF también.En ese caso, echa un vistazo PHP de la clase Fileinfo y funciones.Pero en lo que a seguridad se va, aún no se basan en $_FILES[]['type'] :)

Voy a dejar el resto aquí por si ayuda a alguien que se encuentra esta pregunta


Para comprobar el tipo mime de la imagen, $_FILES[]['type'] podría ser peligrosa.Estos datos son enviados por el navegador y pueden ser fácilmente falsificados.

Usted debe utilizar el getimagesize() la función si usted sólo desea que las imágenes se cargan (a pesar de que tal vez su nombre engañoso).Esta función no sólo el tamaño, pero todos los datos que usted probablemente tendrá sobre la imagen.

He utilizado la siguiente secuencia de comandos en una imagen de manejo de la clase:

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'];

}

Observe que getimagesize() devuelve un array asociativo que contiene un 'mime' índice.Aquí los datos son confiables.

En otra función que comprueba el tipo mime de la imagen y convertir a PNG con la correspondiente de la DG de la función:

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");
    }

}

Usted probablemente no tiene que hacer todo esto, pero usted puede ver lo que los tipos mime aparecen para los tipos de archivos que usted haya especificado.Observe que un jpeg podría tener dos diferentes tipos mime.

Espero que esto ayude.

Zend Framework 's Zend_File_Transfer_Adapter_Http Zend_Form_Element_File . Se pueden añadir varios validadores diferentes como resolución mínima imagen, tipo MIME, tamaño de archivo mínimo, las extensiones de archivo permitidos, etc.

Utilice este código simple ...

<?
$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";
}
?>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top