move_uploaded_file() php 函数不适用于多次上传
Posted
技术标签:
【中文标题】move_uploaded_file() php 函数不适用于多次上传【英文标题】:move_uploaded_file() php function not working for multiple uploads 【发布时间】:2021-08-05 22:03:38 【问题描述】:我正在尝试上传 3 个单独的图像以上传到服务器上使用。该代码不会引发任何错误,但只会上传第一张图片。其他两张图片没有上传到服务器,但它的名字被插入到数据库中。
这是我上传图片的代码:
<?php
include("common_code.php");
include("database_connection.php");
$property_id = $_POST['id'];
if (!$_FILES['file1']['size'] == 0)
$temp = explode(".", $_FILES["file1"]["name"]);
$extension = end($temp);
$fileName1= mt_rand(). "_". time(). "." .$extension;
$image_tmp_name = $_FILES['file1']['tmp_name'];
$folder = "images/property_images/";
$folder = $folder . $fileName1;
move_uploaded_file($image_tmp_name, $folder);
$uploadQuery = "INSERT INTO property_photos (filenames,property_id) VALUES ('$folder','$property_id')";
$run = mysqli_query($connection, $uploadQuery);
if (!$_FILES['file2']['size'] == 0)
$temp2 = explode(".", $_FILES["file2"]["name"]);
$extension2 = end($temp2);
$fileName2= mt_rand(). "_". time(). "." .$extension2;
$image_tmp_name = $_FILES['file2']['tmp_name'];
$folder2 = "images/property_images/";
$folder2 = $folder2 . $fileName2;
move_uploaded_file($image_tmp_name2, $folder2);
$uploadQuery2 = "INSERT INTO property_photos (filenames,property_id) VALUES ('$folder2','$property_id')";
$run2 = mysqli_query($connection, $uploadQuery2);
if (!$_FILES['file3']['size'] == 0)
$temp3 = explode(".", $_FILES["file3"]["name"]);
$extension3 = end($temp3);
$fileName3= mt_rand(). "_". time(). "." .$extension3;
$image_tmp_name = $_FILES['file3']['tmp_name'];
$folder3 = "images/property_images/";
$folder3 = $folder3 . $fileName3;
move_uploaded_file($image_tmp_name3, $folder3);
$uploadQuery3 = "INSERT INTO property_photos (filenames,property_id) VALUES ('$folder3','$property_id')";
$run3 = mysqli_query($connection, $uploadQuery3);
header("Location:property_reg_successful.php?id=$property_id");
只有 file1 被上传到服务器! 文件 2 和文件 3 未上传。
【问题讨论】:
这感觉就像一个循环可以代替。move_uploaded_file
在失败时返回 false,请务必检查,并 echo
输出值,以便您可以看到最终的字符串
好建议@Chris Haas,循环是对这段代码的明确改进,有助于避免像这样的琐碎的复制和粘贴错误。
【参考方案1】:
您刚刚遇到了一个简单的变量命名错误:
$image_tmp_name = $_FILES['file2']['tmp_name'];
[...]
move_uploaded_file($image_tmp_name2, $folder2);
注意不同的变量名“$image_tmp_name”和“$image_tmp_name2”。
【讨论】:
以上是关于move_uploaded_file() php 函数不适用于多次上传的主要内容,如果未能解决你的问题,请参考以下文章
使用 move_uploaded_file() 时如何在 PHP 中创建目标(文件夹)?