PHP FTP函数

PHP ftp_rename() 函数重命名 FTP 服务器上的文件或目录。

语法

ftp_rename(ftp, oldname, newname) 

    参数

    ftp必填。 指定要使用的 FTP 连接。
    oldname必填。 指定旧文件/目录名称。
    newname必填。 指定新名称。

    返回值

    成功时返回 true,失败时返回 false。失败时(例如尝试重命名不存在的文件),将发出 E_WARNING 错误。

    示例:

    下面的示例显示了 ftp_rename( ) 函数。

    <?php
    //要使用的FTP服务器
    $ftp_server = "ftp.example.com";
     
    $old_file = 'oldfile.txt';
    $new_file = 'newfile.txt';
    
    //FTP 连接的用户名
    $ftp_user = "user";
      
    //用户密码
    $ftp_pass = "password";
      
    //建立连接或者连接失败
    $ftp = ftp_connect($ftp_server)
        or die("Could not connect to $ftp_server");
       
    if($ftp) {
      echo "Successfully connected to $ftp_server!\n";
     
      //尝试登录
      if(@ftp_login($ftp, $ftp_user, $ftp_pass)) {
        echo "Connected as $ftp_user@$ftp_server\n";
    
        //尝试将 $old_file 重命名为 $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";
      }
     
      //关闭连接
      if(ftp_close($ftp)) {
        echo "Connection closed successfully!\n"; 
      } 
    }
    ?> 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    上述代码的输出将是:

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