如何使用 PHP 检查远程服务器上是否存在文件?

新手上路,请多包涵

如何通过 FTP 连接使用 PHP 检查远程服务器上是否存在特定文件?

原文由 Ahmad Badpey 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 531
2 个回答

我用这个,更容易一点:

 // 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)

  1. 使用 ftp_connect 登录

  2. 通过 ftp_nlist 获取远程文件列表

  3. 使用 in_array 查看文件是否存在于数组中

原文由 Drmzindec 发布,翻译遵循 CC BY-SA 3.0 许可协议

一些建议:

  • 使用 ftp_size ,如果不存在则返回 -1: http ://www.php.net/manual/en/function.ftp-size.php
  • 使用 fopen ,例如 fopen(” ftp://user:password@example.com/somefile.txt “, “r”)
  • 使用 ftp_nlist ,检查您想要的文件名是否在列表中: http ://www.php.net/manual/en/function.ftp-nlist.php

原文由 mrbellek 发布,翻译遵循 CC BY-SA 2.5 许可协议

推荐问题