<< PHP Write to File | PHP Tutorials | PHP Delete a File >>

PHP Rename a File

Renaming a file in PHP is the simplest thing you can do. There are just a few things you have to remember. First of all, you don't need to open a file handle to rename a file. Secondly there can't be any handles open for the file you are trying to rename. Therefore you must close your handles using the fclose() function before using the rename() function.

The rename() Function

The function used to rename files in PHP is the rename() function and it only requires two parameters: the file name to change and the new name. Here is an example:

<?php
rename('example.txt', 'example2.txt');
?>

There, that's the entire function. You may also want to add a little error handling in case it doesn't work for some reason:

<?php
rename('example.txt', 'example2.txt') or die('Error renaming file.');
?>

<< PHP Write to File | PHP Tutorials | PHP Delete a File >>