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 10 Apexcharts Bar Chart Example
Laravel 10 Apexcharts Bar Char...

In this article, we will see the laravel 10 apexcharts bar chart example. Here, we will learn about how to create a bar...

Read More

May-24-2023

How To Add Datepicker In Angular 15 Material
How To Add Datepicker In Angul...

In this tutorial, I will guide you through the process of adding a datepicker component to your Angular 15 application u...

Read More

Jun-28-2023

How to Run Specific Seeder in Laravel 8
How to Run Specific Seeder in...

In this example, we will learn how to run a specific seeder in laravel 8. If you want to run only one seeder in laravel...

Read More

Jan-19-2022

How To Create Custom Login Page In Django
How To Create Custom Login Pag...

In this article, we will see how to create a custom login page in django. how to allow user registration, login, an...

Read More

May-14-2022