Подтвердить что ты не робот

Как проверить, существует ли файл на удаленном сервере с помощью PHP?

Как проверить, существует ли конкретный файл на удаленном сервере с помощью PHP через FTP-соединения?

4b9b3361

Ответ 1

Я использовал это, немного проще:

// the server you wish to connect to - you can also use the server ip ex. 107.23.17.20
        $ftp_server = "ftp.example.com";

// set up a connection to the server we chose or die and show an error
        $conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
        ftp_login($conn_id,"ftpserver_username","ftpserver_password");

// check if a file exist
        $path = "/SERVER_FOLDER/"; //the path where the file is located

        $file = "file.html"; //the file you are looking for

        $check_file_exist = $path.$file; //combine string for easy use

        $contents_on_server = ftp_nlist($conn_id, $path); //Returns an array of filenames from the specified directory on success or FALSE on error. 

// Test if file is in the ftp_nlist array
        if (in_array($check_file_exist, $contents_on_server)) 
        {
            echo "<br>";
            echo "I found ".$check_file_exist." in directory : ".$path;
        }
        else
        {
            echo "<br>";
            echo $check_file_exist." not found in directory : ".$path;  
        };

        // output $contents_on_server, shows all the files it found, helps for debugging, you can use print_r() as well
        var_dump($contents_on_server);

// remember to always close your ftp connection
        ftp_close($conn_id);

Используемые функции: (благодаря middaparka)

  • Войти с помощью ftp_connect

  • Получить список удаленных файлов через ftp_nlist

  • Используйте in_array, чтобы узнать, присутствует ли файл в массиве

Ответ 3

Это оптимизация решения @JohanPretorius и ответ для комментариев о "медленных и неэффективных для больших dirs" @Andrew и других: если вам требуется более одной "проверки файлов", эта функция является оптимальным решением.

ftp_file_exists() кэширование последней папки

  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

Ответ 4

Общее решение было бы:

  • Войти с помощью ftp_connect

  • Перейдите в соответствующий каталог через ftp_chdir

  • Получить список удаленных файлов через ftp_nlist или ftp_rawlist

  • Используйте in_array, чтобы узнать, присутствует ли файл в массиве, возвращаемом ftp_rawlist

Тем не менее, вы можете просто использовать file_exists, если у вас есть соответствующие URL-оболочки. (Дополнительную информацию см. В странице FTP и протоколах FTPS и обертки PHP.)

Ответ 5

Вы можете использовать ftp_nlist для отображения всех файлов на удаленном сервере. Затем вы должны искать в массиве результатов, чтобы проверить, существует ли файл, который вы искали.

http://www.php.net/manual/en/function.ftp-nlist.php

Ответ 6

Просто проверьте размер файла. Если размер -1, его не существует, поэтому:

$fileSize = ftp_size($ftp_connection, "somefile.txt");

if ($fileSize != -1) {
    echo "File exists";
} else {
    echo "File does not exist";
}

Если размер 0, файл существует, это всего лишь 0 байт.

Источник