Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
ftp_fget() function in PHP
The ftp_fget() function downloads a file from an FTP server and saves it directly into an open local file resource. This function is useful when you need to download files from a remote FTP server and store them locally.
Syntax
ftp_fget(con, open_file, server_file, mode, startpos);
Parameters
con − The FTP connection resource created by
ftp_connect()open_file − An open file resource where the downloaded data will be stored
server_file − The path to the file on the FTP server to download
mode − The transfer mode (
FTP_ASCIIorFTP_BINARY)startpos − The position in the remote file to start downloading from (optional, added in PHP 4.3.0)
Return Value
The ftp_fget() function returns TRUE on success and FALSE on failure.
Example
The following example demonstrates downloading a server file "demo.txt" and saving it to an open local file "new.txt" −
<?php
$ftp_server = "192.168.0.4";
$ftp_user = "amit";
$ftp_pass = "tywg61gh";
// Connect to FTP server
$con = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($con, $ftp_user, $ftp_pass);
$my_serverfile = "demo.txt";
$local_file = "new.txt";
// Open local file for writing
$file_pointer = fopen($local_file, "w");
// Download file from server to local file
if (ftp_fget($con, $file_pointer, $my_serverfile, FTP_ASCII, 0)) {
echo "Written to $local_file!";
} else {
echo "Error in downloading the $my_serverfile!";
}
// Close connections
ftp_close($con);
fclose($file_pointer);
?>
Key Points
The local file must be opened with
fopen()before usingftp_fget()Use
FTP_BINARYmode for binary files (images, executables) andFTP_ASCIIfor text filesAlways close both the FTP connection and file pointer after use
The function requires an active FTP connection established with
ftp_connect()andftp_login()
Conclusion
The ftp_fget() function provides an efficient way to download files from FTP servers directly into local file resources. Remember to handle errors properly and close all connections when finished.
