0

嘿伙计们,我已经创建了 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!";
}
?>

问题,我希望它检查文件是否存在以及是否生成随机数并将其添加到名称中?如果不只是继续并写入文件。

4

1 回答 1

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!";
}
?>
于 2012-10-20T07:09:04.053 回答