PHP Get file from FTP and store to variable

This code example demonstrates the use of PHP's ftp commands to retrieve a file from a remote server, then store it's contents in a variable.

This is often more desirable than storing the file on the local machine, then reading the file contents.

Note the use of the ftp_pasv() function to put the connection into PASSIVE mode. You'll need to try it with and without this option to see which works.
$server = '';
$username = 'myusername';
$password = 'mypassword';
$remoteFile = 'the-product-feed.csv';
$conn = ftp_connect($server);
if (@ftp_login($conn, $username, $password)) {
	echo "Connected to FTP as $username\n";
else {
	echo 'Could not authenticate on FTP server';
ftp_pasv($conn, true); /* try it with and without this line to see which works (depends on server) */
ftp_get($conn, 'php://output', $remoteFile, FTP_ASCII);
$data = ob_get_contents();
var_dump($data);  // output data
Posted by
Snippet Viewed 11160 times.

Share your PHP code snippets:

  • Get some recognition & a link back to your site.
  • Create your own code library.
  • Help your fellow developers, as they have helped you.


Submit | Browse

Most Recent php snippets

Most Viewed