当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


PHP ftp_delete()用法及代码示例


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



相关用法


注:本文由纯净天空筛选整理自gekcho大神的英文原创作品 PHP | ftp_delete() function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。