The best suggestion (and apparently the most voted) is ftp_size
, since it neither opens the file nor loads the entire listing of your folder.
I have not tested or compared restrictions, the fopen
should also work elegantly, avoiding the "false negative" of file_exists
(see @Zuul’s comment on @mlemos response) when we analyze errors.
Next we have the suggestion of ftp_nlist, which "kills the ant with elephant", but can have its array curled and then reused in other checks (!), ie, 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 answer (also well approved!) from https://stackoverflow.com/a/9568577/287948
It’s a more convoluted version of @Paulorodrigues' reply, where I added the commented preparation and suggested cache before.
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
Suggestion from @Paulorodrigues to get the remote file via ftp_nlist
... same suggestion of in_array to see if the file is present.
The quick response is "use ftp_size()". The long answer is down below, with considerations about alternatives, including cache suggestion.
– Peter Krauss