How To Rename A File in PHP
Hi, This is a very basic and simple tutorial on how to rename file in PHP. So, I hope you gonna like this video as you can understand how the function is working and what are the parameters of this function to rename a file in PHP.
In this post, I will explain you the following things.
- rename() function in PHP
- Parameters of rename() function in PHP
- Syntex of rename() function
- An example of rename() function in PHP
Rename file in PHP using rename() function
rename() function is nothing but an inbuilt function in PHP. This function can rename any file in PHP. But besides that, it can also be used to rename a directory.
I am going to show you only renaming a file. The syntax :
rename(oldfilename, newfilename, context)
The very first two parameters are mandatory and the last one is optional here.
Parameters of rename() function in PHP
In this post, I will just show you how to rename a file in PHP. So I will use the first two compulsory parameters. That means the oldfilename and the newfilename.
- oldfilename – this is the name of the file which you want to rename with a new name.
- newfilename – this is your desired file name. That means the new name of the file.
If you set the newfilename to a file name which already exists in that directory than PHP will generate a warning. ( remember this is a warning, not an error, so the file will be overwritten in this case.
Syntax of rename() function in PHP
The syntax is:
rename(oldname, newname, context)
The old name is nothing but the present name of the file. And the newname is the name which you want to set renaming the file.
rename() function in PHP – Example
<?php $old_file_name = "iamold.txt" ; $new_file_name = "iamnew.txt" ; rename( $old_file_name, $new_file_name) ; ?>
If everything goes fine then you will get an output of 1.