Read Remote File via FTP with PHP

Asked

Viewed 1,607 times

2

Hello, I would like your help to solve the following problem. And if possible help me to understand what happens

Code:

$FTP_HOST = "ftp.exemplo.com";
$FTP_USER = "usuario";
$FTP_PASS = "senha";

$cHandle = ftp_connect($FTP_HOST) or die("O Servidor não pode se conectar ao FTP");

$login_result = ftp_login($cHandle, $FTP_USER, $FTP_PASS) or die("O Servidor não pode logar-se no FTP!");

$user['Nome'] = 'ftp://usuario:[email protected]/diretorio/arquivo.ini'; //aqui está o meu problema.

if (!file_exists($user['Nome'])) {
     echo 'Arquivo Inexistente!';
} else
{
    echo 'Arquivo Existente!';
}

Well, this is the code that should work, but it doesn’t work. If I type in my browser: ftp://usuario:[email protected]/directory/file.ini The file opens and shows the data contained in it. If I last in php he doesn’t even recognize that the file is there, I wonder how I can solve this.

To check if the file exists I could use:

$cHandle = ftp_connect($FTP_HOST) or die("O Servidor não pode se conectar ao FTP");

$login_result = ftp_login($cHandle, $FTP_USER, $FTP_PASS) or die("O Servidor não pode logar-se no FTP!");
ftp_login($cHandle,"usuario","senha");

$dir = "/diretorio/";

$arq= "arquivo.ini";

$check_file_exist = $dir.$arq;

$contents_on_server = ftp_nlist($cHandle, $dir);

if (!in_array($check_file_exist, $contents_on_server)) 
{
    echo 'Arquivo Inexistente';
}else 
{
    echo ' Arquivo Existente';
}

It works, only that in this second way, it just checks the existence of the file and I would like it to not only open the file as it would open in the first option, I already searched, I made attempts and I could not so if anyone can help me thank.

So.. How can I make php open and read the file via ftp, the same way it opens on the first try above?

1 answer

2


To open an existing file on an FTP server, you would need to have it locally. Then you will use PHP to download the file from the server.

$server = "endereco_do_servidor.com.br";
$FTP_HOST = "ftp.exemplo.com";
$FTP_USER = "usuario";
$FTP_PASS = "senha";
$cHandle = ftp_connect($FTP_HOST) or die("O Servidor não pode se conectar ao FTP");
$login_result = ftp_login($cHandle, $FTP_USER, $FTP_PASS) or die("O Servidor não pode logar-se no FTP!");
ftp_get($cHandle, "diretorio_destino/arquivo.ini", "diretorio_origem/arquivo.ini", FTP_BINARY);

After that the file can be opened, only locally. You can direct the user to the address of the file.

header("Location: diretorio_destino/arquivo.ini")

I hope I helped. More questions you can ask in: http://php.net/manual/en/book.ftp.php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.