我是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;
感谢您对此提供任何帮助, 添
答案 0 :(得分: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);
}
答案 1 :(得分: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;