PHP ftp_delete()函数用法示例和解析

2021年4月9日17:02:39 发表评论 1,111 次浏览

ftp_delete()函数PHP中的内置函数, 用于删除FTP服务器上的文件。

语法如下:

ftp_delete( $ftp_connection, $file )

参数:此函数接受上述和以下所述的两个参数:

  • $ftp_connection:它是必填参数。它指定用于执行FTP命令或功能的现有FTP连接。
  • $file:它是必填参数。它指定要删除的服务器的文件路径。

返回值:成功返回TRUE, 失败返回FALSE。

注意:

  • 此功能可用于PHP 4.0.0和更高版本。
  • 以下示例无法在在线IDE上运行。因此, 请尝试使用适当的ftp服务器名称, 用户名和密码在某些PHP托管服务器或localhost中运行。
  • ★★★确保作为参数删除提供的文件存在并且具有登录ftp连接的ftp用户的删除权限, 否则会产生错误。

例子:

<?php
  
//Connect to FTP server
  
//Assign ftp server to the variable
$ftp_server = "localhost" ;
  
//Use correct ftp username
$ftp_username = "user" ;
  
//Use correct ftp password corresponding
//to the ftp username
$ftp_userpass = "user" ;
   
//Filename or filename with path to specify
//the file on server to be deleted
$file = "test.txt" ;
  
//Establishing ftp connection 
$ftp_connection = ftp_connect( $ftp_server )
         or die ( "Could not connect to $ftp_server" );
  
if ( $ftp_connection ) {
     echo "successfully connected to the ftp server!" ;
      
     //Logging in to established connection with
     //ftp username and password
     $login = ftp_login( $ftp_connection , $ftp_username , $ftp_userpass );
      
     if ( $login ) { 
          
         //Checking whether logged in successfully or not
         echo "<br>logged in successfully!" ;
          
         //ftp_delete() function to delete file from FTP server
         if (ftp_delete( $ftp_connection , $file )) {
             echo "<br>deletion of " . $file . " is successful." ;
         }
         else {
             echo "<br>Error while deleting the file " . $file ;
         }
     }
     else {
         echo "<br>login failed!" ;
     }
      
     //Closeing  connection
     if (ftp_close( $ftp_connection )) {
         echo "<br>Connection closed Successfully!" ;
     } 
}
?>

输出如下:

successfully connected to the ftp server!
logged in successfully!
deletion of ./htdocs/test.txt is successful.
Connection closed Successfully!

如果该文件被删除并再次运行同一程序, 但前提是该文件不存在(已删除), 因此会发生错误。输出看起来像

successfully connected to the ftp server!
logged in successfully!
Error while deleting the file ./htdocs/test.txt
Connection closed Successfully!

参考: https://www.php.net/manual/en/function.ftp-delete.php


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: