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 Create Middleware For XSS Protection
Laravel 9 Create Middleware Fo...

In this article, we will see laravel 9 create middleware for XSS protection. Cross-site scripting is a type of...

Read More

Apr-30-2022

Laravel 11 Import Export CSV and Excel File
Laravel 11 Import Export CSV a...

Hello, Laravel developers! In this article, I'll show you how to easily import and export CSV and Excel files in Lar...

Read More

Sep-13-2024

How To Solve The Page Expired 419 Error In Laravel
How To Solve The Page Expired...

In this article, we'll learn how to resolve the "419 page expired" error in Laravel. You might have encoun...

Read More

Jun-28-2020

Routing - Laravel 7/8 Routing Example
Routing - Laravel 7/8 Routing...

In this article, we will give you information about the basic route, named route, and advanced route in laravel 7 and la...

Read More

Nov-01-2020