How to Rename a file in PHP ? See Example

Renaming a file in PHP is done using the built-in rename() function. This function can also be used to move a file from one directory to another. Renaming is useful when you need to update filenames, organize uploads, or change extensions.

Syntax of rename()

rename(string $oldName, string $newName);

Parameters

  • $oldName — The current name or path of the file.
  • $newName — The new name or new path for the file.

Return Value

  • Returns true on success.
  • Returns false on failure.

Example: Renaming a File

<?php
$oldName = "data.txt";
$newName = "backup-data.txt";

if (rename($oldName, $newName)) {
    echo "File renamed successfully!";
} else {
    echo "Error: Unable to rename the file.";
}
?>

Example: Moving & Renaming a File

You can also rename while moving the file:

<?php
$oldPath = "uploads/image.jpg";
$newPath = "archive/old-image.jpg";

if (rename($oldPath, $newPath)) {
    echo "File moved and renamed successfully!";
} else {
    echo "Failed to move the file.";
}
?>

Common Causes of rename() Failing

1. File does not exist

Make sure the file path is correct.

2. Permission issues

The directory must allow read/write operations.

3. File is in use

Some servers lock files while they are being processed.

4. Incorrect path

Use absolute paths if relative paths fail.


Practical Use Cases

Renaming uploaded files

When users upload images, you may rename them to avoid duplicate names.

Timestamp-based names

$newName = time() . ".jpg";

Changing file extensions

rename("note.txt", "note.md");

Output Example

Before: report.txt
After: report-old.txt


Citations

🔗 View other articles about PHP:
http://savanka.com/category/learn/php/

🔗 External PHP Documentation:
https://www.php.net/manual/en/

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *