Domanda

Sto facendo una pagina in cui l'utente caricare un file. Voglio un'istruzione if per creare una variabile $ errore se il tipo di file è qualcosa di diverso jpg, gif, e pdf.

Ecco il mio codice:

$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';
}

Sto avendo difficoltà a strutturare l'istruzione if. Come faccio a dirlo?

È stato utile?

Soluzione

Mettere i tipi permessi in un array e utilizzare 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';
}

Altri suggerimenti

modifica

Ho appena realizzato che si desidera consentire i file PDF come bene. In tal caso, controllare classe FileInfo di PHP e funzioni . Ma per quanto riguarda la sicurezza va, ancora non dovrebbe fare affidamento su $_FILES[]['type']:)

ti lascio il resto qui, in caso aiuta qualcun altro che trova questa domanda


Per visualizzare il tipo MIME dell'immagine, $_FILES[]['type'] potrebbe essere pericoloso. Questi dati vengono inviati dal browser e può essere facilmente falsificato.

Si dovrebbe usare la funzione getimagesize() se si desidera solo per permettere le immagini da caricare (nonostante il nome forse fuorviante). Questa funzione non solo darvi la dimensione, ma tutti i dati che sarà probabilmente bisogno di circa l'immagine.

Ho usato il seguente script in una classe di gestione delle immagini:

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

}

Si noti che getimagesize() restituisce un array associativo contenente un indice di 'mimare'. I dati qui è affidabile.

In un'altra funzione che ho controllato il tipo MIME dell'immagine e convertita in PNG con la funzione GD appropriata:

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

}

Probabilmente non avrete bisogno di fare tutto questo, ma si può vedere che cosa mimo tipi appaiono per i tipi di file che hai specificato. Si noti che un jpeg potrebbe avere due tipi MIME differenti.

Spero che questo aiuti.

Si veda anche s 'Zend Framework Zend_File_Transfer_Adapter_Http Zend_Form_Element_File . È possibile aggiungere più validatori differenti come la risoluzione minima dell'immagine, tipo MIME, dimensione minima del file, le estensioni di file consentiti, ecc.

Usa questo semplice codice ...

<?
$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";
}
?>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top