1

我是 PHP 新手,并为表单上的文件上传创建了一些代码。

该代码工作正常,但我想知道是否可以使用 foreach 循环实现相同的目的,以便它还可以处理更多文件,而我不必为每个文件编写单独的行。

这里有人可以帮我解决这个问题并告诉我如何正确编写它。

我的代码(工作):

session_start();

$varUID = $_POST['UID'];
$varSender = $_SESSION['email'];

$varFile1 = $_FILES["file1"]["name"];
$varExt1 = pathinfo($varFile1, PATHINFO_EXTENSION);
$varFile2 = $_FILES["file2"]["name"];
$varExt2 = pathinfo($varFile2, PATHINFO_EXTENSION);
$varFile3 = $_FILES["file3"]["name"];
$varExt3 = pathinfo($varFile3, PATHINFO_EXTENSION);

move_uploaded_file($_FILES["file1"]["tmp_name"], "uploads/" . $varUID . "_1" . "." . $varExt1);
move_uploaded_file($_FILES["file2"]["tmp_name"], "uploads/" . $varUID . "_2" . "." . $varExt2);
move_uploaded_file($_FILES["file3"]["tmp_name"], "uploads/" . $varUID . "_3" . "." . $varExt3);

echo $varUID;

感谢您对此的任何帮助,蒂姆

4

2 回答 2

5
foreach ($_FILES as $key => $file) {
    $name = $file["name"];
    $ext = pathinfo($name, PATHINFO_EXTENSION);
    preg_match('/(\d+)$/', $key, $match); // get 2 out of "file2"
    $nr = $match[1];
    move_uploaded_file($file["tmp_name"], "uploads/" . $varUID . "_" . $nr . "." . $ext);
}
于 2013-10-09T11:19:20.717 回答
3
$varUID = $_POST['UID'];
$varSender = $_SESSION['email'];

$i = 1;

foreach ($_FILES as $key => $file) {
    $varFile = $file[$key]["name"];
    $varExt = pathinfo($varFile, PATHINFO_EXTENSION);
    move_uploaded_file($file[$key]["tmp_name"], "uploads/" . $varUID . "_" . $i . "." . $varExt);
    $i++;
}

echo $varUID;
于 2013-10-09T11:21:07.443 回答