How to Rename Files and Directories in PHP Using rename()

This guide explains the PHP rename() function, covering its syntax, required parameters, return values, practical code examples for renaming both files and directories, and important permission considerations to ensure successful renaming operations.

php Courses
php Courses
php Courses
How to Rename Files and Directories in PHP Using rename()

Syntax

The rename() function is declared as:

bool rename(string $source, string $target)

Parameters

$source

: The name of the existing file or directory to be renamed (required). $target: The new name for the file or directory (required).

Return Value

On success, rename() returns TRUE; on failure it returns FALSE.

Examples

Renaming a File

<?php
$old_name = "old_file.txt";
$new_name = "new_file.txt";
if (rename($old_name, $new_name)) {
    echo "File renamed successfully!";
} else {
    echo "File rename failed!";
}
?>

This script attempts to rename old_file.txt to new_file.txt and prints a success or failure message.

Renaming a Directory

<?php
$old_name = "old_directory";
$new_name = "new_directory";
if (rename($old_name, $new_name)) {
    echo "Directory renamed successfully!";
} else {
    echo "Directory rename failed!";
}
?>

The code works the same way for directories, changing the name of old_directory to new_directory.

Important Considerations

The rename() operation may be restricted by file‑system permissions; ensure the executing script has sufficient rights to modify the target. If the source file or directory does not exist, rename() will return FALSE.

Summary

The PHP rename() function provides a straightforward way to change the name of files or directories by specifying the current name and the desired new name. With the provided examples, developers can quickly integrate file‑renaming capabilities into their projects while being mindful of permission constraints.

file-handlingdirectoryrename
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

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.