我的HTML代码是;
<form action="post_photo.php" method="post" enctype="multipart/form-data">
<tr>
<td class="trow1" width="10%">Select Image:</td>
<td class="trow1" width="90%"><input type="file" name="image[]" multiple="multiple" tabindex="1"></td>
</tr>
<tr>
<td class="trow2" align="left">
<input type="hidden" name="action" value="do_post_photo" />
<input type="hidden" name="uid" value="{$uid}" />
<input type="submit" class="button" name="submit" value="Upload Photos" tabindex="2">
</td>
</tr>
</form>
我的post_photo.php文件包含此代码;
if(isset($_FILES['image']))
{
foreach($_FILES['image']['tmp_name'] as $key => $tmp_name )
{
$file_size = $_FILES['image']['size'][$key];
$file_tmp = $_FILES['image']['tmp_name'][$key];
$ext = get_extension($_FILES['image']['name'][$key]);
$allowed_ext = explode(",","png,gif,jpg,jpeg");
if(!in_array($ext,$allowed_ext))
{
error("Invalid extension.");
}
if($file_size > 2097152)
{
error("File size must be less than 2 MB.");
}
$file_name = "photo_".TIME_NOW.".".$ext;
$insert_array = array(
"uid" => $uid,
"image" => $file_name,
"approved" => '1',
"likes" => '',
"dateline" => time()
);
if(is_dir("uploads/photos/".$file_name)==false)
{
move_uploaded_file($file_tmp,"uploads/photos/".$file_name);
}
$db->insert_query("photos", $insert_array);
}
}
redirect("post_photo.php?action=post_photo", "Photos have been posted successfully.");
问题是,如果我选择4张图片,它会将2张图片上传到./uploads/photos/文件夹。但是它在photos
sql表中插入了4条记录(这是正确的,因为我选择了4张图像),所有这些记录也是正确的(我的意思是所有这些记录都有单独的数据,每个图像都是正确的)。如果我选择2个图像,那么它只会将一个上传到./uploads/photos/文件夹,但它会在sql表中插入2条记录。
为什么会显示此问题?请帮忙!
答案 0 :(得分:0)
你说数据库中添加了4条记录,只上传了2张图像。 这是问题所在:
if(is_dir("uploads/photos/".$file_name)==false)
{
//1
move_uploaded_file($file_tmp,"uploads/photos/".$file_name);
}
//2
$db->insert_query("photos", $insert_array);
如您所见,始终执行步骤// 2,但仅当此条件为真时才执行步骤// 1:“is_dir(”uploads / photos /".$ file_name)== false“。< / p>
解决方案:在执行sql语句之前检查是否(move_uploaded_file(......))。
答案 1 :(得分:0)
将您的PHP代码更改为此内容;
if(isset($_FILES['image']))
{
$count = 0;
foreach($_FILES['image']['name'] as $key => $tmp_name)
{
$file_size = $_FILES['image']['size'][$key];
$file_tmp = $_FILES['image']['tmp_name'][$key];
$ext = get_extension($_FILES['image']['name'][$key]);
$allowed_ext = explode(",","png,gif,jpg,jpeg");
if(!in_array($ext,$allowed_ext))
{
error("Invalid extension.");
continue;
}
if($file_size > 2097152)
{
$size_in_kb = $file_size/1000;
error("File size must be less than 2MB.");
continue;
}
if(move_uploaded_file($file_tmp,"uploads/photos/".$tmp_name))
{
$insert_array = array("uid" => $uid, "image" => $tmp_name, "approved" => '1', "likes" => '', "dateline" => TIME_NOW);
$db->insert_query("photos", $insert_array);
$count++;
}
}
}
redirect("post_photo.php?action=post_photo", "Photos have been posted successfully.");
它应该有用!