Backend Development 4 min read

PHP rename() Function: Syntax, Parameters, Return Values, Examples, and Notes

This article explains PHP's rename() function, detailing its syntax, required source and target parameters, return values, and provides practical code examples for renaming both files and directories while highlighting important permission considerations.

php中文网 Courses
php中文网 Courses
php中文网 Courses
PHP rename() Function: Syntax, Parameters, Return Values, Examples, and Notes

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 name and the target name.

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.

Examples

Below are examples demonstrating how to use rename() to rename files and directories.

Rename a File

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

if (rename($old_name, $new_name)) {
    echo "文件重命名成功!";
} else {
    echo "文件重命名失败!";
}
?>

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

Rename a Directory

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

if (rename($old_name, $new_name)) {
    echo "目录重命名成功!";
} else {
    echo "目录重命名失败!";
}
?>

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

Notes

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

Summary

The rename() function is a powerful PHP tool for renaming files or directories. By specifying the source and target names, you can easily perform rename operations, as demonstrated in the example code snippets.

backendPHPfilesystemfile handlingrename
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.