Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php

What is the rename() function in PHP?

Behzad Ahmad

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The rename() function in PHP renames an existing file or directory.

Syntax

rename(string $oldname, string $newname, resource $context = ?): bool

Parameters

oldname: This specifies the old name of the file or directory we want to rename.

newname: This specifies the new name of a file or directory.

context: This is an optional parameter that is a set of options able to alter the behavior of a stream.

Return value

rename() returns true if the name is successfully changed. Otherwise, in case of any error, it returns false.

Note:

  • If a file is being renamed and the newname specified already exists, the file is overwritten.
  • If a directory is being renamed and the newname specified already exists as a directory, a warning is produced.

Code

The following code shows how to use the rename() function.

main.php
task2.txt
task1.txt
<?php
echo "contents of task1.txt:\n";
readfile("task1.txt");
echo "\ncontents of task2.txt: \n";
readfile("task2.txt");
rename("task1.txt","task2.txt");
echo "\nAfter rename: ";
readfile("task2.txt");
?>

Explanation

In the code above, there are two text files, task1.txt and task2.txt, and their content is displayed.

Ttask1.txt is renamed to task2.txt, but since task2.txt already exists, it overwrites the original file. Then, when the content of task2.txt is read, the content is the same as task1.txt.

RELATED TAGS

php

CONTRIBUTOR

Behzad Ahmad
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring