Download file via FTP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
wiggst3r
Forum Newbie
Posts: 10
Joined: Wed Apr 09, 2008 10:59 am

Download file via FTP

Post by wiggst3r »

Hi all.

On my FTP server I have a list of files, which I want to get the last uploaded file and download to my machine.

I've been able to successfully get the last file that was uploaded and print the file name to the screen.

What i want to do is, download this file to my machine.

I've used the ftp_get function, but I keep getting errors:
Warning: ftp_fget() expects parameter 2 to be resource, boolean given in /Users/mac/workspace/download_csv/test.php on line 33
There was a problem while downloading Transfer_20080619.txt to test.txt
My code is:

Code: Select all

<?php
require_once('config.php');
 
    $ftp_server = "www.example.com";
    $ftp_user_name = "xxxxxxxx";
    $ftp_user_pass = "xxxxxxxxx";
    $fromDir = "folder";
    $toDir = "/Users/mac/workspace/download_csv/download";
 
 
    $conn_id = ftp_connect($ftp_server);
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
 
    if((!$conn_id) || (!$login_result))
    {
        echo "Could not Connect to the FTP Server";
        exit();
    }
 
    $contents = ftp_nlist($conn_id, $fromDir); // Compiles an array of all files in folder
    sort($contents);
    $last_file = $contents[count($contents) - 23]; // gets last file that was added
    //print $last_file;
 
    if(!file_exists($toDir)) // If our local directory doesn't exists let's create it
    mkdir($toDir);
 
    $handle = fopen($local_file, 'w');
 
    $local_file = 'test.txt';
    $remote_file = $last_file;
 
    if (ftp_fget($conn_id, $handle, $remote_file, FTP_ASCII, 0))
    {
    echo "successfully written to $local_file\n";
    }
    else
    {
    echo "There was a problem while downloading $remote_file to $local_file\n";
    }
 
    // close the connection
    ftp_close($conn_id);
 
?>
Any ideas?
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Download file via FTP

Post by Christopher »

I would guess that fopen($local_file, 'w'); is failing.
(#10850)
Post Reply