How to Download File on the FTP Server Using PHP

Websolutionstuff | May-21-2021 | Categories : PHP

Today we will see how to download file on the ftp server using php. Many time we have requirment to retrieve file from the FTP serverso here i will so you file download in ftp using ftp fget function, ftp_get() function is used to download file from the FTP server.

The ftp_get() function retrieves a remote file from the FTP server and save it into an open local file.

 

Syntax : 

 

ftp_fget(ftp_conn, open_file, server_file, mode, startpos);

 

Parameters : 

 

ftp_conn - ftp_conn is required parameter and it is use to specifies the FTP connection.

open_file - open_file is required parameter and it is use to specifies open local file in which we store the data.

server_file - local_file is required parameter and it is use to specifies the server file to download.

mode - mode is optional parameter and it is use to specifies the transfer mode. It has 2 possible values: 1) FTP_ASCII 2) FTP_BINARY.

startpos - startpos is optional parameter and it is use to specifies the position in the remote file to start download from.

 

Example :

 

<?php
// connect to FTP server
$ftp_server = "ftp.example.com";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");

// login to FTP server
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);

$server_file = "somefile.txt";

// open local file to write to
$local_file = "local.txt";
$fp = fopen($local_file,"w");

// download server file and save it to open local file
if (ftp_fget($ftp_conn, $fp, $server_file, FTP_ASCII, 0))
  {
  echo "Successfully written to $local_file.";
  }
else
  {
  echo "Error downloading $server_file.";
  }

// close connection and file handler
ftp_close($ftp_conn);
fclose($fp);
?>

 

Recommended Post
Featured Post
Laravel 11 Simple Pagination Example
Laravel 11 Simple Pagination E...

Hello developers! In this article, we'll see the laravel 11 simple pagination example. Here, we'll use Bootstrap...

Read More

May-03-2024

Next Previous Link Button Pagination in Laravel
Next Previous Link Button Pagi...

Today we will learn next previous link button pagination in laravel, Using paginate method you can easily create paginat...

Read More

Jun-14-2021

How to Install PHP PDO MySQL Extension in Ubuntu 22.04
How to Install PHP PDO MySQL E...

Hey there! If you're diving into PHP development on Ubuntu 22.04 and need to connect your applications to MySQL data...

Read More

Feb-28-2024

How To Auto Select Country Using IP Lookup In jQuery
How To Auto Select Country Usi...

In this article, we will see how to auto select a country using IP lookup in jquery. Here, we will learn about auto...

Read More

May-15-2023