php rename files – How to Rename a File Using PHP?

php rename files : Introduction to the PHP rename file function · $native_file is the name of the file that you want to rename. · $duplicate_name is the new name of the file.

php rename files

This function works perfectly with files. Using the built-in rename() function, i can rename a file or directory. If you need to rename file in folder php code then i can use “rename()” function of php.

Free Live Chat for Any Issue

How to Rename a File Using PHP?

<?php
rename ('documentation.txt', 'duplicated.txt');
?>

Example : Rename directory name

<?php
$native_file = './profiles';
$duplicate_name = './documentations’;
 
if(rename($native_file, $duplicate_name)){
   echo "Good Job, Folder has been renamed";
} else {
   echo "sorry, Fail to rename directory";
}
?>

<?php

if (file_exists('first_version.txt'))
{
	$renamed= rename('first_version.txt', 'duplicater.txt');

	if ($renamed)
	{
		echo "The file has been successfully renamed";
	}
	else
	{
		echo "sorry, The file has not been successfully renamed";
	}
}
else
{
	echo "The Native file that you want to rename doesn't exist";
}

?>

PHP rename() Function
Rename a folder + a file:

<?php
rename("profiles","pictures");
rename("/welcome/demo_v1.txt","/home/docs/example.txt");
?>

Don’t Miss : PHP rename uploaded file keep extension

Also Read This 👉   Generate alphanumeric random number in php

Example

<?php

if ($handle = opendir('/path/to/files')) {
    while (false !== ($doc_fl_name = readdir($handle))) {
        $display_name = str_replace("JDK#","",$doc_fl_name);
        rename($doc_fl_name, $display_name);
    }
    closedir($handle);
}
?>

Moving files with rename()

Example

<?php
    $doc_fl_name_new = $doc_fl_name . '.old';
    rename($doc_fl_name, $doc_fl_name_new);
?>

Use the rename function to move a file

<?php
$native_file = './documentation.txt';
$duplicate_name = './pakainfo_v1/documentation.txt';
 
if(rename($native_file, $duplicate_name)){
   echo "File has been moved";
} else {
   echo "Fail to move documentation";
}
?>

I hope you get an idea about php rename files.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.