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 9 Vue JS Search Example
Laravel 9 Vue JS Search Exampl...

In this article, we will see a laravel 9 vue js search example. Here, we will learn how to live search in laravel 9 usin...

Read More

Dec-14-2022

How to Create Trait in Laravel 10 Example
How to Create Trait in Laravel...

Hello developers! 👋 Today, let's dive into the wonderful world of Laravel 10 and explore one of its handy featu...

Read More

Feb-09-2024

Carbon Add Years To Date In Laravel
Carbon Add Years To Date In La...

In this article, we will see examples of carbon adding years to date in laravel. Here we will laravel add...

Read More

Dec-07-2020

Angular 13 Crop Image Before Upload With Preview
Angular 13 Crop Image Before U...

In this article, we will see the angular 13 crop image before uploading with a preview. we will give you a sim...

Read More

May-10-2022