Web Development Tutorials




  
  

Renaming Files

This section describes how to use PHP to rename files on Windows systems. PHP includes the rename() function for renaming files. The function is defined below:

The following example demonstrates how to delete a file using the rename() function:

filerename.php

<?php

$orig_filename = "C:/Documents and Settings/Administrator/MyFIles/myfile.txt";
$new_filename = "C:/Documents and Settings/Administrator/MyFiles/newfile.txt";
$status = rename($orig_filename, $new_filename) or exit("Could not rename the file");

echo "file renamed successfully";

?>

The first step is to create a variable to hold the full path to the file that will be renamed:

$orig_filename = "C:/Documents and Settings/Administrators/MyFiles/myfile.txt"; 

The second step is to create a variable to hold the full path to the file that will be created when the old file is renamed:

$new_filename = "C:/Documents and Settings/Administrators/MyFiles/newfile.txt"; 

The rename() function is executed, accepting two parameters, the path of the original file - $orig_filename and the path to the file that will be created when the old file is renamed - $new_filename. The rename() function returns a value of true if the file is deleted successfully;otherwise a value of false is returned. The returned value is stored in the variable $status.

$status = rename($orig_filename,$new_filename) or exit("Could not rename file"); 

If the rename() function fails, the exit() function executes displaying an error message. Otherwise, success message is displayed using the echo statement.

echo "file successfully rename";

TOP | NEXT: Collecting Form Data