Hye伙计们,我已经创建了jquery ajax文件上传器,但我有一个问题,它是服务器端,它将覆盖任何具有相同名称的文件而且我将生成一个随机数,应该是与另一个不同,但我的上传者的代码是
<?php
$target_path = "/var/www/vhosts/grubber.co.nz/httpdocs/developer/_social_development/uploads/blog/";
$target_path = $target_path . basename( $_FILES['img']['name']);
if (file_exists($target_path)) {
echo "The file $filename exists";
$target_path = "/var/www/vhosts/grubber.co.nz/httpdocs/developer/_social_development/uploads/blog/" . basename( $_FILES['img']['name']);
} else {
echo "The file $filename does not exist";
}
if(move_uploaded_file($_FILES['img']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['img']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
问题,我想要检查一个文件是否存在,是否确实生成一个随机数并将其添加到名称中?如果不是继续并写入文件。
答案 0 :(得分:3)
一种解决方案可能是使用一些唯一的编号来添加文件名。
您可以使用uniqid()函数。 http://php.net/manual/en/function.uniqid.php
<?php
$target_path = "/var/www/vhosts/grubber.co.nz/httpdocs/developer/_social_development/uploads/blog/";
$target_path = $target_path . basename( $_FILES['img']['name']);
if (file_exists($target_path)) {
echo "The file $filename exists";
$target_path = "/var/www/vhosts/grubber.co.nz/httpdocs/developer/_social_development/uploads/blog/" .uniqid().basename( $_FILES['img']['name']);
} else {
echo "The file $filename does not exist";
}
if(move_uploaded_file($_FILES['img']['tmp_name'], $target_path)) {
echo "The file ".basename( $_FILES['img']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>