當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。