In PHP, ftp_fget() downloads a file from the FTP server and writes it into an open local file handle. It is the stream version of ftp_get().
Instead of giving a local file name, you open a file or memory stream yourself and pass the handle. This lets you save to php://temp, php://memory, or any other stream you like.
Syntax
Call ftp_fget() with the values you need. Start with this line.
Starts reading the remote file from byte 1024 (resume position).
The handle must be opened for writing, for example with fopen('file.txt', 'w'). From PHP 8.1 the first argument is an FTP\Connection object. After the call, the handle is not rewound, so use rewind() before you read it back.
Library declarations
PHP
ftp_fget(FTP\Connection $ftp, resource $stream, string $remote_filename, int $mode = FTP_BINARY, int $offset = 0): bool
Parameters
Parameter
Description
ftp
Required. The FTP\Connection object returned by ftp_connect() or ftp_ssl_connect().
stream
Required. An open, writable file pointer where the downloaded data is written.
remote_filename
Required. The path of the file on the FTP server to download.
mode
Optional. The transfer mode, FTP_ASCII or FTP_BINARY. The default is FTP_BINARY.
offset
Optional. The position in the remote file to start downloading from. The default is 0.
Return Value
Return Value
Description
bool
true on success, false on failure.
PHP Examples
Example 1 — Download Into a Local File Handle
Open a local file for writing and let ftp_fget() fill it. The host and login are placeholders.
We open the local file and run ftp_fget() in binary mode.
The handle is closed right after the transfer so everything is flushed to disk.
On success, filesize() reports how many bytes were saved.
On failure, unlink() removes the empty file so we do not keep a broken copy.
Frequently Asked Questions
It downloads a remote file from an FTP server and writes it into an open local file handle that you provide.
ftp_get() takes a local file name and saves the file for you. ftp_fget() takes an open file handle, which gives you more control, for example saving to memory.
Yes, if you want to read the data back. After the download the pointer is at the end, so call rewind() first.
Use FTP_ASCII for plain text and FTP_BINARY for everything else, such as images, PDFs and ZIP files.
It tells the server which byte to start from in the remote file. It is useful for resuming an interrupted download.