Backend Development 4 min read

Using PHP rename() Function to Rename Files and Directories

This article explains the PHP rename() function, its syntax, parameters, return values, and provides clear examples for renaming both files and directories while noting permission considerations and common pitfalls.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP rename() Function to Rename Files and Directories

In PHP, the rename() function is used to rename a file or directory, offering a straightforward way to change names for single files or entire directories by specifying the source and target names.

Syntax: bool rename ( string $source , string $target )

Parameters:

$source : required, the name of the source file or directory.

$target : required, the name of the target file or directory.

Return value: Returns TRUE on success and FALSE on failure.

Example – Renaming a file:

<?php
$old_name = "old_file.txt";
$new_name = "new_file.txt";

if (rename($old_name, $new_name)) {
    echo "File rename successful!";
} else {
    echo "File rename failed!";
}
?>

This script renames old_file.txt to new_file.txt and outputs a success or failure message.

Example – Renaming a directory:

<?php
$old_name = "old_directory";
$new_name = "new_directory";

if (rename($old_name, $new_name)) {
    echo "Directory rename successful!";
} else {
    echo "Directory rename failed!";
}
?>

This script renames the directory old_directory to new_directory with similar success/failure feedback.

Notes: The rename() function may be restricted by file system permissions; ensure you have sufficient rights. If the source file or directory does not exist, rename() will return FALSE .

Summary: The rename() function is a powerful PHP tool for renaming files and directories by simply providing the source and target names, and with the provided examples you can easily incorporate it into your projects.

BackendPHPfilesystemfile managementrename
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.