PHP: How do I read a .txt file from FTP server into a variable?

Solution 1:

The file_get_contents is the easiest solution:

$contents = file_get_contents('ftp://username:pa‌​ssword@hostname/path/to/file');

If it does not work, it's probably because you do not have URL wrappers enabled in PHP.


If you need greater control over the reading (transfer mode, passive mode, offset, reading limit, etc), use the ftp_fget with a handle to the php://temp (or the php://memory) stream:

$conn_id = ftp_connect('hostname');

ftp_login($conn_id, 'username', 'password');

ftp_pasv($conn_id, true);

$h = fopen('php://temp', 'r+');

ftp_fget($conn_id, $h, '/path/to/file', FTP_BINARY, 0);

$fstats = fstat($h);
fseek($h, 0);
$contents = fread($h, $fstats['size']); 

fclose($h);
ftp_close($conn_id);

(add error handling)

Solution 2:

If you've already opened a connection via ftp_connect, this would probably be the best answer:

ob_start();
$result = ftp_get($conn_id, "php://output", $file, FTP_BINARY);
$data = ob_get_contents();
ob_end_clean();