简体   繁体   中英

How to rename a file in php?

I am trying to rename the file if existing, the file will be moved successfully but the new file name will be like 0. the file will be shown only if I add .png manually to the name. I am not able to let the php rename the file correctly.

I have tried many suggested ways here on stack overflow but the file won't be moved either will be renamed as 0. a

It will be appreciated to let me know what is wrong with my code, please don't reply that I have to make my research first then write here, as I did already but I had no luck to figure it out myself.

PHP

$i = 0;
$extension = pathinfo($name, PATHINFO_EXTENSION);
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$original_name = $actual_name;

while(file_exists('../cutomeruploads/'.$actual_name.".".$extension))
{           
$actual_name = (string)$original_name;
$actual_name = $actual_name.(string)$i;
$name = $actual_name.".".$extension;
$i++;
}


if(move_uploaded_file($_FILES['upl']['tmp_name'], '../cutomeruploads/'.$name)){
    $picname = $_FILES['upl']['name'];

    echo '{"status":"success"}';
    exit;
  }

您是否尝试过php的重命名功能?

rename("The existing file name", "the new name");

Renaming a file in php is quite easy.

rename("oldfile.ext","newname.ext");

For more info see this: http://us3.php.net/rename

Try this one.

/*
 * $dir - Directory path to check where the file is exist 
 * $filename - contains only name of the file
 * 
 */
public static function getFileName($dir, $filename) {

    // If name contains any white space replace with '-'
    $filename = str_replace(" ", "-", $filename);

    $filePath = $dir . $filename;

    $fileInfo = pathinfo($filePath);
    $i = 0;
    $flag = false;

    while(file_exists($filePath)) {
        $filePath = $dir . $fileInfo['filename'] . "_" . $i . "." . $fileInfo['extension'];
        $i++;
        $flag = true;
    }
    if($flag === TRUE)
        return $fileInfo['filename'] . "_" . $i . "." . $fileInfo['extension'];
    else
        return $fileInfo['filename'] . "." . $fileInfo['extension'];

}

This is will return new filename if already exist one.

For example, image.jpg already exist, it automatically adding image_1.jpg , image_2.jpg and so on.

These changes renaming the file to xx1.ext xx2.ext

note:xx = $orDi

$actual_name = pathinfo($_FILES['upl']['name'], PATHINFO_FILENAME);
$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
while(file_exists('../cutomeruploads/'.$actual_name.".".$extension))
{ 
 $i++;          
$actual_name = (string)$orDi.(string)$i;
}

if(move_uploaded_file($_FILES['upl']['tmp_name'], '../cutomeruploads/'.$actual_name.".".$extension)){
    $picname = $actual_name.".".$extension;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM