所以我刚刚开始使用PHP,我从网上提取了一个脚本。它的设置方式是,如果文件已经存在,它将不会上传它。我希望能够重命名文件,以便接受所有照片。
继承守则:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
有一个if值可以处理Pre existing files。我假设我将更改为不同的If值来更改名称?谢谢你的帮助!
答案 0 :(得分:1)
更改此行:
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
要:
$target_file = $target_dir . 'this_is_my_new_name_whooah.txt';
答案 1 :(得分:1)
如果正在上传的文件已存在,您可以重命名文件。
if (file_exists($target_file)) {
$target_file=$target_file."2";//Rename file by concating any other string
$uploadOk = 1;
}
答案 2 :(得分:1)
这就是我们如何处理相同的命名图像
$fileCount = count (glob ("uploads/*.jpg"));
$name = ( $fileCount + 1) . '.jpg';
$newName = "uploads/" . $name;
$tf = fopen($newName, 'w');
fclose($tf);
move_uploaded_file($_FILES['fileField']['tmp_name'], $newName);
希望这会帮助你!
答案 3 :(得分:1)
当前的解决方案没有考虑多个类似命名的文件,这是一个快速可扩展的解决方案。
if (file_exists($target_file))
{
$filecounter = 0; // initialize file count.
// runs loop increasing filecount and appending to filename until untaken filename is found.
do
{
$filecounter++;
$target_file .= " - $filecounter";
}
while( file_exists($target_file) );
}
答案 4 :(得分:0)
// Check if file already exists
if (file_exists($target_file)) {
//echo "Sorry, file already exists.";
//$uploadOk = 0;
rename($target_file, 'your_new_filename');
}