Master PHP’s rename() Function: Rename Files & Directories Easily

This article explains how to use PHP's rename() function to rename files and directories, covering its syntax, parameters, return values, practical code examples for both files and folders, and important permission considerations.

php Courses
php Courses
php Courses
Master PHP’s rename() Function: Rename Files & Directories Easily

Introduction

In PHP, the rename() function is used to rename files or directories. It provides a simple way to change the name of a file or directory 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, 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 renamed successfully!";
} else {
    echo "File rename failed!";
}
?>

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!";
}
?>

Notes

The rename() function may be limited by file system permissions. Ensure you have sufficient rights, and that the source exists; otherwise the function returns FALSE.

Summary

The rename() function is a powerful PHP tool for renaming files and directories by specifying source and target names, with examples demonstrating its usage.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Tutorialfile 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

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.