0
//array of image file types
    $fileType_array = array(IMAGETYPE_JPEG, IMAGETYPE_PNG);

    //getimagesize to determine the file_type of the image
    $getImage_thumbnail = getimagesize($_FILES[$thumbnail_fieldname]['tmp_name']);
        $getImage_thumbnail_type = $getImage_thumbnail[2];
    $getImage_desktop_1280x800 = getimagesize($_FILES[$desktop_fieldname_1280x800]['tmp_name']);
        $getImage_desktop_1280x800 = $getImage_desktop_1280x800[2];
    $getImage_desktop_1366x768 = getimagesize($_FILES[$desktop_fieldname_1366x768]['tmp_name']);
        $getImage_desktop_1366x768 = $getImage_desktop_1366x768[2];
    $getImage_desktop_1920x1080 = getimagesize($_FILES[$desktop_fieldname_1920x1080]['tmp_name']);
        $getImage_desktop_1920x800 = $getImage_desktop_1920x1080[2];

    if(in_array($getImage_thumbnail_type, $fileType_array, TRUE)){
        echo "<p>Thumbnail is an image.</p>";
        }

以上是我检查选择上传的文件是否为图像的代码,我想做的是只使用一次 in_array 而不是几个 if 语句/in_array 来检查文件类型是否存在于数组中。这个怎么可能?

4

1 回答 1

1

您将需要检查所有这些值。但是可以通过使用数组来简化任务。

$fileType_array = array(IMAGETYPE_JPEG, IMAGETYPE_PNG);

$filenames = array($thumbnail_fieldname, $desktop_fieldname_1280x800, ...);
$files = array();
foreach ($filenames as $filename) {
    if (isset($_FILES[$filename]['tmp_name'])) {
        $resource = getimagesize($_FILES[$filename]['tmp_name']);
        $type = $resource[2];
        if (in_array($type, $fileType_array, TRUE)) {
            $files[$filename] = $resource;
        }
    }
}

这样,只有具有可接受文件类型的文件才会存储在$files其中,当您想要更改正在使用的文件时,您只需更新$filenames.

于 2013-11-13T00:47:57.387 回答