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.