How can I check if a file exists on a remote server using PHP?

后端 未结 6 1260
时光取名叫无心
时光取名叫无心 2020-12-02 20:47

How can I check if a specific file exists on a remote server using PHP via FTP connections?

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 21:12

    This is an optimization of @JohanPretorius solution, and an answer for comments about "slow and inefficient for large dirs" of @Andrew and other: if you need more than one "file_exist checking", this function is a optimal solution.

    ftp_file_exists() caching last folder

      function ftp_file_exists(
          $file, // the file that you looking for
          $path = "SERVER_FOLDER",   // the remote folder where it is
          $ftp_server = "ftp.example.com", //Server to connect to
          $ftp_user = "ftpserver_username", //Server username
          $ftp_pwd = "ftpserver_password", //Server password
          $useCache = 1  // ALERT: do not $useCache when changing the remote folder $path.
      ){
    
          static $cache_ftp_nlist = array();
          static $cache_signature = '';
    
          $new_signature = "$ftp_server/$path";
    
          if(!$useCache || $new_signature!=$cache_signature) 
              {
                  $useCache = 0;
                  //$new_signature = $cache_signature;
                  $cache_signature = $new_signature;
                   // setup the connection
                   $conn_id         = ftp_connect($ftp_server) or die("Error connecting $ftp_server");
                   $ftp_login           = ftp_login($conn_id, $ftp_user, $ftp_pwd);
                   $cache_ftp_nlist = ftp_nlist($conn_id, $path);
    
                   if ($cache_ftp_nlist===FALSE)die("erro no ftp_nlist");
              }
    
            //$check_file_exist = "$path/$file";
            $check_file_exist = "$file";
    
            if(in_array($check_file_exist, $cache_ftp_nlist)) 
                {
                    echo "Found: ".$check_file_exist." in folder: ".$path;
                } 
            else 
                {
                    echo "Not Found: ".$check_file_exist." in folder: ".$path;  
                };
            // use for debuging: var_dump($cache_ftp_nlist);
            if(!$useCache) ftp_close($conn_id);
        } //function end
    
        //Output messages
        echo ftp_file_exists("file1-to-find.ext"); // do FTP
        echo ftp_file_exists("file2-to-find.ext"); // using cache
        echo ftp_file_exists("file3-to-find.ext"); // using cache
        echo ftp_file_exists("file-to-find.ext","OTHER_FOLDER"); // do FTP
    

提交回复
热议问题