php image type detection

后端 未结 1 1098
攒了一身酷
攒了一身酷 2021-01-29 08:12

Unable to detect mime type. if I remove ($mime==\"image/jpeg\" || $mime==\"image/pjpeg\"), it could upload the image successfully.

$mime = $_FILES[\         


        
相关标签:
1条回答
  • 2021-01-29 08:50

    The name and type information for uploaded files should be seen as purely informational and never be used for anything serious, since it's user supplied information and can easily be spoofed. You should only ever look at the tmp_name, error and size fields to determine if you want to accept a file. To find the actual MIME type of a file, use PHP's built-in functions:

    if ($file['error'] == UPLOAD_ERR_NO_FILE) {
        die('No file uploaded');
    }
    
    if ($file['error'] != UPLOAD_ERR_OK) {
        die('Error during upload');
    }
    
    if (!$file['size'] || !is_uploaded_file($file['tmp_name'])) {
        die('File is weird');
    }
    
    $extensions = array(IMAGETYPE_GIF => '.gif', IMAGETYPE_JPEG => '.jpg', IMAGETYPE_PNG => '.png');
    $exifType = exif_imagetype($file['tmp_name']);
    if (!isset($extensions[$exifType])) {
        die('Unsupported file type');
    }
    
    $ext = $extensions[$exifType];
    $targetDir = '/somewhere/else/';
    
    do {
        $target = $targetDir . uniqid() . $ext;
    } while (file_exists($target));
    
    if (!move_uploaded_file($file['tmp_name'], $target)) {
        die('Something went wrong');
    }
    
    echo 'Yay, uploaded!';
    

    Not that you should necessarily use that many die() statements though, that's just for demonstration purposes.

    0 讨论(0)
提交回复
热议问题