使用 PHP 重命名图像名称

Renaming Image name with PHP

所以我刚开始使用 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 值以更改名称?感谢您的帮助!

更改此行:

$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

收件人:

$target_file = $target_dir . 'this_is_my_new_name_whooah.txt';

如果正在上传的文件已经存在,您可以重命名文件。

if (file_exists($target_file)) {
    $target_file=$target_file."2";//Rename file by concating any other string
    $uploadOk = 1;
}
// Check if file already exists
if (file_exists($target_file)) {
    //echo "Sorry, file already exists.";
    //$uploadOk = 0;
    rename($target_file, 'your_new_filename');
}

这就是我们处理相同命名图像的方式

$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); 

希望对您有所帮助!

当前解决方案不考虑多个类似命名的文件,这是一个快速可扩展的解决方案。

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) );
}