Check if a file exists on the remote machine via FTP in PHP

4

How can I check if a file exists on the remote machine using PHP through the functions of FTP in order to act accordingly?

<?php
$ficheiro = 'public_html/banana.xml';

$id_ligacao = ftp_connect($servidor_ftp);

$login = ftp_login($id_ligacao, $utilizador, $password);

// verificar se ficheiro existe
if (ficheiro_existe($ficheiro)) { // função para ilustrar o conceito
  echo "existe!";
} else {
  echo "não existe!";
}

ftp_close($conn_id);
?>
    
asked by anonymous 04.03.2014 / 22:17

4 answers

2

I believe that using the file_exists function can solve your problem in a simpler way:

if(file_exists('ftp://usuario:[email protected]:porta/caminho/do/arquivo')) ...
    
05.03.2014 / 07:30
2

The best suggestion (and apparently top rated ) is ftp_size , since it does not open the file or load the entire listing of your folder.

I have not tested or compared constraints, fopen should also work fine, avoiding the "false negative" of file_exists (see @Zuul's comment on @mlemos's response) when we analyze errors .

Next we get the suggestion of ftp_nlist, which "kills ant with elephant", but can have its array cached and then reused in other checks (!), that is, it can be an optimal solution in certain cases.

ftp_file_exists() with last folder cache

The use of specialized FTP functions requires some preparation. Here I copy a part of the (also well approved!) Response from link

This is a more elaborate version of @PauloRodrigues' response, where I added the commented preparation and cache suggested above.

  function ftp_file_exists(
      $file,                     // o arquivo que se procura
      $path = "/SERVER_FOLDER/", //pasta onde ele está
      $ftp_server = "ftp.example.com",
      $ftp_user = "ftpserver_username", $ftp_senha = "ftpserver_password",
      $useCache = 1
  ) {

      static $cache_ftp_nlist=array();
      static $cache_assinatura='';

      $nova_assinatura = "$ftp_server$path";
      if (!$useCache || $nova_assinatura!=$cache_assinatura) {
          $useCache = 0;
          $nova_assinatura=$cache_assinatura;
           // setup da conexão
           $conn_id = ftp_connect($ftp_server) or die("Não pode conectar em $ftp_server");
           ftp_login($conn_id,$ftp_user,$ftp_senha);
           $cache_ftp_nlist = ftp_nlist($conn_id, $path);
           if ($cache_ftp_nlist===FALSE) die("erro no ftp_nlist");
      }

// verificando se o arquivo existe:
        $check_file_exist = $path.$file;
        if (in_array($check_file_exist, $cache_ftp_nlist)) {
            echo "EXISTE, achei: ".$check_file_exist." na pasta : ".$path;
        } else {
            echo $check_file_exist." não está na pasta : ".$path;   
        };
        // para debug: var_dump($cache_ftp_nlist);
// lembrar de fechar a conexão ftp
        if (!$useCache) ftp_close($conn_id);
        } //func
  // CUIDADO: o cache não pode ser usado se a pasta está sendo alterada!

Functions used:

  • Login ftp_connect

  • @PauloRodrigues' suggestion to get the remote file via ftp_nlist

  • ... same hint of in_array to see if the file is present.

  • 05.03.2014 / 11:05
    0

    What about ftp_nlist ?

    $contents = ftp_nlist($id_ligacao, "public_html");
    
    if (in_array($ficheiro, $contents)) {
        // existe
    } else {
        // não existe
    }
    
        
    04.03.2014 / 22:25
    -1

    You can use ftp_mlsd which will return the list of files and directories. Then just go through this list and check if the desired directory is contained in it.

        
    18.12.2018 / 17:57