使用多重上传获取PHP输入的名称

时间:2014-12-01 20:57:43

标签: php file-upload

我很难搞清楚这一点。如何将不同输入的不同图像放入不同的文件目录中。

例如我想" $ _ FILES [' ma'];"去销售/ ma / xxxxxxx.jpg和" $ _ FILES [' ny'];"去销售/ ny / xxxxxxx.jpg,我该如何实现。

非常感谢你的帮助。

这是我非常简单的html

<form action="includes/upload.php" method="post" enctype="multipart/form-data">
    <label for="ma">ma</label>
    <input type="file" name="ma" id="ma" multiple="">
    <label for="ma">ny</label>
    <input type="file" name="ny" id="ny" multiple="">
    <label for="ma">nj</label>
    <input type="file" name="nj" id="nj" multiple="">
    <label for="va">va</label>
    <input type="file" name="va" id="va" multiple="">
    <input type="submit" value="Upload Image" name="submit">
</form>

这是PHP。

<?php           
    $ma_file = $_FILES['ma'];
    $ny_file = $_FILES['ny'];
    $nj_file = $_FILES['nj'];
    $va_file = $_FILES['va'];

    $all_files = array($ma_file,$ny_file,$nj_file,$va_file);

    foreach($all_files as $file) {

        try {
            if (
                !isset($file['error']) ||
                is_array($file['error'])
            )   {
                throw new RuntimeException('Invalid parameters.');
            }

            // Check $_FILES['upfile']['error'] value.
            switch ($file['error']) {
                case "0":
                    break;
                case UPLOAD_ERR_NO_FILE:
                    // throw new RuntimeException('No file sent.');
                    // it's ok to have no file. 
                    break;
                case UPLOAD_ERR_INI_SIZE:
                case UPLOAD_ERR_FORM_SIZE:
                    throw new RuntimeException('Exceeded filesize limit.');
                default:
                    throw new RuntimeException('Unknown errors.');
            }

            if ($file['size'] > 1000000) { // under one mb.
                throw new RuntimeException('Exceeded filesize limit.');
            }

            $finfo = new finfo(FILEINFO_MIME_TYPE);

            if (false === $ext = array_search(
                $finfo->file($file['tmp_name']),
                array(
                    'jpg' => 'image/jpeg',
                    'png' => 'image/png',
                    'gif' => 'image/gif',
                ),
                true
            )) {
                throw new RuntimeException('Invalid file format.');
            }

            if (!move_uploaded_file(
                $file['tmp_name'],
                sprintf('../sale/%s.%s',
                    sha1_file($file['tmp_name']),$ext
                )
            )) {
                throw new RuntimeException('Failed to move uploaded file.');
            }



        }
        catch (RuntimeException $e) {
            echo $e->getMessage();
        }
    }
?>

1 个答案:

答案 0 :(得分:1)

合并$ _FILES有什么意义?

foreach($_FILES as $code => $subfiles) {
                   ^^^^^^^^
    ... $code will be ma/ny/nj/va
    move_uploaded_files(.... "/some/path/$code/whatever/else");
}