如何使用PHP检查远程服务器上是否存在文件? [英] How can I check if a file exists on a remote server using PHP?

查看:100
本文介绍了如何使用PHP检查远程服务器上是否存在文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

我用了这个,有点简单:

I used this, a bit easier:

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

Functions used: (thanks to middaparka)

  1. 使用 ftp_connect

通过 ftp_nlist

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

Use in_array to see if the file was present in the array

这篇关于如何使用PHP检查远程服务器上是否存在文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆