PHP Function Reference

PHP ftp_rename() Function



The PHP ftp_rename() function renames a file or a directory on the FTP server.

Syntax

ftp_rename(ftp, oldname, newname)

Parameters

ftp Required. Specify the FTP connection to use.
oldname Required. Specify the old file/directory name.
newname Required. Specify the new name.

Return Value

Returns true on success or false on failure. Upon failure (such as attempting to rename a non-existent file), an E_WARNING error will be emitted.

Example:

The example below shows the usage of ftp_rename() function.

<?php
//FTP server to use
$ftp_server = "ftp.example.com";
 
$old_file = 'oldfile.txt';
$new_file = 'newfile.txt';

//username for the FTP Connection
$ftp_user = "user";
  
//password for the user
$ftp_pass = "password";
  
//set up a connection or die 
$ftp = ftp_connect($ftp_server)
    or die("Could not connect to $ftp_server");
   
if($ftp) {
  echo "Successfully connected to $ftp_server!\n";
 
  //trying to login
  if(@ftp_login($ftp, $ftp_user, $ftp_pass)) {
    echo "Connected as $ftp_user@$ftp_server\n";

    //trying to rename $old_file to $new_file
    if (ftp_rename($ftp, $old_file, $new_file)) {
      echo "Successfully renamed $old_file to $new_file\n";
    } else {
      echo "Error while renaming $old_file to $new_file\n";
    }
    
  } else {
    echo "Couldn't connect as $ftp_user\n";
  }
 
  //close the connection
  if(ftp_close($ftp)) {
    echo "Connection closed successfully!\n"; 
  } 
}
?>

The output of the above code will be:

Successfully connected to ftp.example.com!
Connected as user@ftp.example.com
Successfully renamed oldfile.txt to newfile.txt
Connection closed successfully!

❮ PHP FTP Reference