The Wayback Machine - https://web.archive.org/web/20240914111731/https://www.geeksforgeeks.org/php-rename-function/
Open In App

PHP | rename( ) Function

Last Updated : 29 May, 2018
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The rename() function in PHP is an inbuilt function which is used to rename a file or directory. It makes an attempt to change an old name of a file or directory with a new name specified by the user and it may move between directories if necessary.
If the new name specified by the user already exists, the rename() function overwrites it. The old name of the file and the new name specified by the user are sent as parameters to the rename() function and it returns True on success and a False on failure.

Syntax:

rename(oldname, newname, context)

Parameters Used:
The rename() function in PHP accepts three parameter.

  1. oldname : It is a mandatory parameter which specifies the old name of the file or directory.
  2. newname : It is a mandatory parameter which specifies the new name of the file or directory.
  3. context : It is an optional parameter which specifies the behavior of the stream .

Return Value:
It returns True on success and a False on failure.

Errors And Exception

  1. The rename() function generates a Warning if the newname already exists while renaming a directory.
  2. The wrapper used in oldname must match the wrapper used in newname.
  3. If the destination filesystem doesn’t permit chown() or chmod() system calls to be made on files, then rename() function may generate Warnings.

Examples:

Input : $old_name = "gfg.txt" ; 
        $new_name = "newgfg.txt" ; 
        rename( $new_name, $old_name) ;

Output : 1

Input : $old_name = "gfg.txt" ;
        $new_name = "newgfg.txt" ; 
        if(file_exists($new_name))
        { 
           echo "Error While Renaming $old_name" ;
        }
        else
        {
           if(rename( $old_name, $new_name))
           { 
           echo "Successfully Renamed $old_name to $new_name" ;
           }
          else
          {
           echo "A File With The Same Name Already Exists" ;
          }
        }

Output : Successfully Renamed gfg.txt to newgfg.txt

Below programs illustrate the rename() function.

Suppose there is a file named “gfg.txt”

Program 1




<?php 
// Old Name Of The file
$old_name = "gfg.txt" ; 
  
// New Name For The File
$new_name = "newgfg.txt" ; 
  
// using rename() function to rename the file
rename( $old_name, $new_name) ;
  
?>


Output:

1

Program 2




<?php 
// Old Name Of The file
$old_name = "gfg.txt" ; 
   
// New Name For The File
$new_name = "newgfg.txt" ; 
   
// Checking If File Already Exists
if(file_exists($new_name))
 { 
   echo "Error While Renaming $old_name" ;
 }
else
 {
   if(rename( $old_name, $new_name))
     { 
        echo "Successfully Renamed $old_name to $new_name" ;
     }
     else
     {
        echo "A File With The Same Name Already Exists" ;
     }
  }
?>


Output:

Successfully Renamed gfg.txt to newgfg.txt

Related Articles:

Reference:
http://php.net/manual/en/function.rename.php



Similar Reads

Node.js fsPromises.rename() Method
The fsPromises.rename() method is used to asynchronously rename a file at the given old path to a given new path. It will overwrite the destination file if it already exists. It resolves the Promise with no arguments upon success. Syntax: fsPromises.rename( oldPath, newPath ) Parameters: This method accept two parameters as mentioned above and desc
2 min read
How to operate callback-based fs.rename() method with promises in Node.js ?
The fs.rename() method is defined in the File System module of Node.js. The File System module is basically to interact with hard-disk of the user’s computer. The rename() method is used to rename the file at the given old path to a given new path. If the new path file already exists, it will be overwritten and if there exists a directory at new pa
5 min read
How to rename the collection name of MongoDb using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON ( similar to JSON f
2 min read
Node fs.rename() Method
The `fs.rename()` method is employed for the asynchronous renaming of a file, moving it from the specified old path to a designated new path. If a file already exists at the new path, it will be overwritten by the operation. Syntax: fs.rename( oldPath, newPath, callback )Parameters: This method accepts three parameters as mentioned above and descri
2 min read
How to Rename an Object Key by the use of the Ternary Operator in JavaScript ?
Renaming object keys in JavaScript is a crucial task. To conduct key renaming conditionally, the ternary operator offers a succinct solution. Using the ternary operator, will provide versatility, especially in complicated circumstances, and enhance readability and maintainability into account when using this method for key renaming. These are the f
2 min read
How to Rename Branch in Git?
Renaming branches in Git is important for keeping your repository organized and understandable, especially when collaborating with others. Clear and descriptive branch names improve project management and help team members identify the purpose of each branch. Renaming branches also ensures consistency and clarity throughout the development process.
1 min read
Rename Object Key in JavaScript
In JavaScript, objects are used to store the collection of various data. It is a collection of properties. A property is a "key: value" pair where Keys are known as 'property name' and are used to identify values. Since JavaScript doesn't provide an inbuilt function to rename an object key. So we will look at different approaches to accomplish this
4 min read
How To Rename A Repository on GitHub?
Renaming a repository on GitHub is a simple task that might be necessary for several reasons: action may include project renaming, consolidation of repositories, improper naming conventions or, in general, redundancy and clarity. In this detailed guide, each of the steps involved in renaming a repository on GitHub will be explained in detail, along
6 min read
How to Rename Images and Media Files in WordPress?
Renaming images and media files in WordPress can be used for SEO and organization purposes. When you rename an image file, you can improve its relevance to your content and make it easier for search engines to understand the context of the image. Additionally, renaming media files can help you better organize your media library. In this article, we
3 min read
How to Rename Your WordPress Blog?
Renaming your WordPress blog can be an exciting opportunity to refresh your brand, reach a new audience, or simply make a change for personal preference. Fortunately, WordPress makes this process simple. In this article, we'll go through the steps to rename your WordPress blog, including the best practices to ensure a smooth transition. Why Rename
4 min read
How the User-Defined Function differs from Built-in Function in PHP ?
In PHP, functions are blocks of reusable code that perform specific tasks. They enhance code readability, modularity, and maintainability by encapsulating logic into named units. PHP functions can be categorized into two main types: user-defined functions and built-in functions. User-Defined FunctionsUser-defined functions are functions created by
2 min read
PHP 5 vs PHP 7
PHP is a server side scripting language designed for web development by Rasmus Lerdorf in 1994. Since its launch in 1994 PHP has become an industry standard supporting almost 80% of the websites ( 79.8% to be precise) with its closest competitor being ASP.Net at 19.8% and others like Ruby, Java trailing far behind. The PHP development team released
4 min read
How to include content of a PHP file into another PHP file ?
Including the content of a PHP file into another file reduces the complexity of code by reducing the code and improving its modularity by splitting the code into different files so that it is easy to understand and manage. There are two ways to do it by using the following PHP functions. PHP include() Function: It will show the warning if the file
2 min read
What is New in PHP Type Hinting Support in PHP 8?
PHP 8 introduced several enhancements and new features related to type hinting. That will check the code for their respective type so that we can use our code efficiently. These are the following features used in PHP Type Hitting Support: Table of Content Union TypesMixed TypeStatic Return TypeInheritance of Contravariant ParametersInheritance of P
3 min read
PHP | imagecreatetruecolor() Function
The imagecreatetruecolor() function is an inbuilt function in PHP which is used to create a new true-color image. This function returns a blank image of the given size. Syntax: resource imagecreatetruecolor( $width, $height ) Parameters: This function accepts two parameters as mentioned above and described below: $width: This parameter is used to s
2 min read
PHP fpassthru( ) Function
The fpassthru() function in PHP is an inbuilt function which is used to read data from a current position from a specified file until end of file and then write the result to the output buffer. The file which has to be read is sent as a parameter to the fpassthru() function and it returns the number of characters passed on success or FALSE on failu
2 min read
PHP | ImagickDraw getTextAlignment() Function
The ImagickDraw::getTextAlignment() function is an inbuilt function in PHP which is used to get the alignment applied when annotating with text. It helps to format the text by making it stick to left, right or middle. Syntax: int ImagickDraw::getTextAlignment( void ) Parameters: This function doesn’t accept any parameter. Return Value: This functio
2 min read
PHP | Ds\Sequence last() Function
The Ds\Sequence::last() function is an inbuilt function in PHP which is used to return the last element from the sequence. Syntax: mixed abstract public Ds\Sequence::last( void ) Parameters: This function does not accept any parameters. Return value: This function returns the last element from the sequence. Below programs illustrate the Ds\Sequence
1 min read
PHP | array_udiff_uassoc() Function
The array_udiff_uassoc() Function is an inbuilt function in PHP and is used for distinguishing between two or more array. The function computes the differences array by use of two user-defined functions with the additional index key. It compares both data and index by use of callback functions and returns the difference. Syntax : array_udiff_uassoc
5 min read
PHP | geoip_continent_code_by_name() Function
The geoip_continent_code_by_name() function is an inbuilt function in PHP which helps to generate a two-letter continent code(Each continent has assigned a two-letter code. For example - AF for Africa, AS for Asia, and many more). The function takes the hostname or IP Address as an argument and generates the two-letter continent code. Syntax : stri
1 min read
PHP | GmagickPixel setcolor() function
The GmagickPixel::setcolor() function is an inbuilt function in PHP which is used to set the color of the GmagickPixel object. Syntax: GmagickPixel GmagickPixel::setcolor( string $color ) Parameters:This function accepts a single parameter $color which holds the color. Return Value: This function returns GmagickPixel object on success. Exceptions:
1 min read
PHP | opendir() Function
The opendir() function in PHP is an inbuilt function which is used to open a directory handle. The path of the directory to be opened is sent as a parameter to the opendir() function and it returns a directory handle resource on success, or FALSE on failure. The opendir() function is used to open up a directory handle to be used in subsequent with
2 min read
PHP | cal_to_jd() Function
The cal_to_jd() function is an inbuilt function in PHP which is used to converts a specified date into Julian Day Count. The cal_to_jd() function calculates the Julian day count for a date in the specified calendar. This function supports CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH calendars.Syntax: int cal_to_jd( $calendar, $month, $day,
2 min read
PHP | stream_get_transports() Function
The stream_get_transports() function is an inbuilt function in PHP which is used to get the list of registered socket transports. This function returns the indexed array containing the name of all available socket. Syntax: array stream_get_transports( void ) Parameters: This function does not accept any parameter. Return Value: This function return
1 min read
PHP | Ds\Deque pop() Function
The Ds\Deque::pop() function is an inbuilt function in PHP which is used to remove the last element from Deque (if Deque is not empty) and return it. If Deque is empty then it throws an exception. Syntax: public Ds\Deque::pop( void ) : mixed Parameters: This function does not accept any parameter. Return Value: This function returns the removed las
2 min read
PHP | SimpleXMLElement children() Function
Pre-requisite: Read XML BasicsThe SimpleXMLElement::children() function is an inbuilt function in PHP which returns children of a given node in a SimpleXML object. Syntax: SimpleXMLElement SimpleXMLElement::children( $namespace, $is_prefix ) Parameter: This function accepts two parameters as mentioned above and described below: $namespace: It is op
3 min read
PHP | array_intersect_ukey() Function
The array_intersect_ukey() function is an inbuilt function in PHP which is used to compute the intersection of two or more array against keys with the help of user-defined function and the function return an array. The returned array is the first array, which is matching keys and present in all parameters is the final output. Syntax: array array_in
5 min read
PHP | is_numeric() Function
The is_numeric() function is an inbuilt function in PHP which is used to check whether a variable passed in function as a parameter is a number or a numeric string or not. The function returns a boolean value. Syntax: bool is_numeric ( $var ) Parameters: The function accepts a single parameter which is mandatory and described below: $var: This inpu
2 min read
PHP | Imagick adaptiveSharpenImage() Function
The Imagick::adaptiveSharpenImage() function is an inbuilt function in PHP which provides an adaptive sharpen image feature to the image. The intensity of an adaptive sharpen image depends on dramatically decreased at the edge of the image. Syntax: bool Imagick::adaptiveSharpenImage ( $radius, $sigma, $channel ) Parameters: This function accepts th
1 min read
PHP | isset() Function
The isset() function is an inbuilt function in PHP which is used to determine if the variable is declared and its value is not equal to NULL. Syntax: bool isset( mixed $var [, mixed $... ] ) Parameters: This function accept one or more parameter as mentioned above and described below: $var: It contains the variable which need to check. $...: It con
2 min read