Matt Clements
Matt Clements

Reputation: 197

PHP - Download from URL and Upload via FTP

Slightly weird concept here... A client of ours wants data pushed to them over FTP/S

The idea is that we download one of our reports by downloading from a URL (a CSV File), then push this to the client over FTP/S. I know I can do this in bash scripts using wget & ftp - but need to add to this over a web interface so PHP is the best way forward.

As this is a background task I can extend time-outs etc.

I know also I can use fopen to download and save a file, then find it and upload it using the PHP FTP library. Just looking for a way to download using fopen, hold the data in memory to upload straight away.

Any help appreciated in advance!

Upvotes: 2

Views: 3644

Answers (2)

Emyr
Emyr

Reputation: 2371

To avoid saving the file to disk and "to upload straight away" i.e. to start pushing to FTP as soon as the first chunk of Data is downloaded?

Try this: http://www.php.net/manual/en/function.stream-copy-to-stream.php

You'll need an FTP server and client library which support resuming uploads

Upvotes: 1

Peter Lindqvist
Peter Lindqvist

Reputation: 10210

To retrieve the data from the URL you have a few options. You say you want the data in memory only to push directly to the FTP host.

One approach (that I find the simplest to use, but lacking in terms of reliability and error handling) is file_get_contents()

Example:

$url = 'http://www.domain.com/csvfile';
$data = file_get_contents($url);

Now you have your csv data in $data, over to how to push this to an ftp server.

Again the simplest way to do this is to use the builtin stream wrappers as used in the get example above. (Note however that this requires PHP 4.3.0)

Simply build up the connection string like this.

$protocol = 'ftps';
$hostname = 'ftp.domain.com';
$username = 'user';
$password = 'password';
$directory = '/pub';
$filename = 'filename.csv';
$connectionString = sprintf("%s://%s:%s@%s%s/%s",
    $protocol,$username,$hostname,
    $password,$directory,
    $filename);


file_put_contents($connectionString,$data);

Have a look at the ftp wrappers manual

If this does not work there are other options.

You could use curl to get the data and the FTP Extension to push it.

Upvotes: 4

Related Questions