所以我刚刚开始使用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值处理先前存在的文件。我假设我会将其改为不同的If值来更改名称?谢谢你的帮忙!
发布于 2015-01-19 18:52:55
如果上载的文件已经存在,可以重命名文件。
if (file_exists($target_file)) {
$target_file=$target_file."2";//Rename file by concating any other string
$uploadOk = 1;
}
发布于 2015-01-19 18:46:09
更改这一行:
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
至:
$target_file = $target_dir . 'this_is_my_new_name_whooah.txt';
发布于 2015-01-19 19:02:15
这就是我们如何处理相同命名的图像。
$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);
希望这能帮到你!
https://stackoverflow.com/questions/28031324
复制相似问题