简体   繁体   中英

How to rename an uploaded file in PHP?

I'm uploading a file to the server in PHP. Now I want to rename the file to the new name, but I couldn't get it done. The proposed new name of file will be composed of the value from one associative array and a variable name. For achieving that I did following code but not able to get the newly named file. My code is as follows:

$test_pack_id  = md5(uniqid($this->hash_secret));


    if(!empty($test_pack_id )){
                  $package_image_file = $form_image_data['test_pack_image']['name'];

                  $nwName = rename($package_image_file,$form_data['test_pack_name'].$test_pack_id);  
                  echo $nwName; die;
                }

Can anyone help me on how to rename a file in PHP? Thanks in Advance.

bool rename ( string $oldname , string $newname [, resource $context ] )

Note: The old name. The wrapper used in oldname must match the wrapper used in newname.

Returns TRUE on success or FALSE on failure.

<?php
rename("old", "new");
?>

Check this link too http://www.codersmount.com/2011/07/smart-way-for-renaming-uploaded-files-using-php/

You should do a print_r or var_dump on $form_data because I suspect that the data being passed to 'test_pack_name' is incorrect and causing the rename to fail. I would also included swapnesh's suggestion to put in a conditional if to report on the success or failure of the rename to provide you additional debugging information.

PHP rename(); function

rename ("123", "abc");
rename ("oldname", "newname");

PHP rename() returns true or false

so u can check if via if statement

if(rename())
echo "Success";
else
echo "failure";

you can use rename as others have suggested. OR just simply rename the file using the time at which it was uploaded. This is what i usually do. Take a look:

//First separate the original file name from its extension
list($txt, $ext) = explode(".", $name);
//rename it with its timestamp.
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;

Hope this helps.

simple and easy way

if( !rename($filePath, $newFileName) ) {

echo "File can't be renamed!";

}

else {

echo "File has been renamed!";

}

Reference

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