我有一个php文件上传程序。我想在程序中再添加一个功能,即检查目录中是否存在相同的文件。
我想在我的代码中添加类似的内容:
if (file_exists("directory_name/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
这是我的php文件上传代码:
<?php
$valid_formats = array("jpg", "png", "gif", "JPEG", "bmp", "JPG", "PNG", "GIF");
$max_file_size = 1024*500; //100 kb
$path = "images/$_POST[fol]/"; // Upload directory
$count = 0;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files
foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 4) {
continue;
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue;
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue;
}
else{
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name))
$count++;
}
}
}
}
?>
如何将两者结合起来?有人可以帮忙吗?
答案 0 :(得分:1)
在移动文件之前检查文件是否存在。 尝试像
这样的东西 else{
if (file_exists($path.$name)
{
file already exixts
}
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name))
$count++;
}
答案 1 :(得分:1)
这是解决方案。
else{
if(!file_exists($path.$name))
{
move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name);
$count++; // Number of successfully uploaded file
}
else{
echo "File exists";
}
}