Ervin
Ervin

Reputation: 2452

fopen on file through FTP URL

I am trying to download a file using PHP from an FTP URL, which looks like ftp://username:password@domain/file.zip . The URL is good, because I can download the file pasting it into any browser. Fopen supports this kind of file streaming, just saw it here: fopen . Here's my code:

[...]
$destination_folder = '../importmlsupload/';    
$url = "ftp://user:password@domain/file.zip";
$newfname = $destination_folder . basename($url);
$file = fopen($url, "rb");
if ($file) {
    $newf = fopen($newfname, "wb");
    while(!feof($file)) {
        $s = fread($file, 1024);
        fwrite($newf, $s, 1024 );
    }
}

if (!empty($file)) {
    fclose($file);
}

if (!empty($newf)) {
    fclose($newf);
}

The problem is that I get an ampty file downloaded. I have made some verifications and I got the following results: the file is been created successfully on the server, but the while loop (!feof(...)) ends after the first step. So it reads 1024 bytes and it exits from the loop. By other words feof returns true after the first 1024 bytes or reading.

TRYING WITH HTTP URL RESULTS SUCCESSFUL IMPORT, BUT FTP URL DOESN'T

Am I doing something wrong?

Upvotes: 3

Views: 8043

Answers (2)

Raul Pinto
Raul Pinto

Reputation: 1105

Hi Ervin and sorry for the late answer!

I just had the same problem and I found actually two answers. First I tried file_get_contents. This works like this:

$input = file_get_contents($url);
$writtenChars = file_put_contents($newfname, $input);

Very simple and works, but I guess just for ASCII and if you have quite some memory as this reads the whole file before writing it. I liked your approach with buffer. So I did the following:

$source = fopen($url, 'r');
$destination = fopen($newfname, 'w+');
while($data = fread($source, 1024)) {
    fwrite($destination, $data);
}

This works fine for the XML file I'm downloading. Your binary should be fine when you do your 'wb' in the mode parameter of fopen.

I don't know why your feof doesn't work, sorry. But as you see in my code, you don't need it anyway.

Upvotes: 1

Jigar
Jigar

Reputation: 3320

I did not try your code, but if you have ftp details, you can use FTP functions instead. This might not be the appropriate answer i know. :)

Upvotes: 2

Related Questions