Skip to content

Instantly share code, notes, and snippets.

@hussnainsheikh
Created July 11, 2024 02:49
Show Gist options
  • Save hussnainsheikh/46ee081e05bf13cf51be222004868f25 to your computer and use it in GitHub Desktop.
Save hussnainsheikh/46ee081e05bf13cf51be222004868f25 to your computer and use it in GitHub Desktop.
Connect FTP server through PHP using "league/flysystem-ftp" package and download file(s).
<?php
/**
*
* I am using `league/flysystem-ftp` package for it
* so make sure you install it before using this code.
* if you are using composer then you can simply install
* it using command `composer require league/flysystem-ftp:^3.0`
* check the latest version on the package documentation.
*
**/
use League\Flysystem\Filesystem;
use League\Flysystem\Ftp\FtpConnectionOptions;
use League\Flysystem\Ftp\FtpAdapter;
use League\Flysystem\Ftp\NoopCommandConnectivityChecker;
use League\Flysystem\Ftp\FtpConnectionProvider;
use League\Flysystem\UnixVisibility\PortableVisibilityConverter;
/**
*
* FTP_FILE = file name which you want to download from server, e.g. products.csv
* LOCAL_FILE = name of the file after downloading on your system
*
**/
ftpGetFile("FTP_HOST", "FTP_USER", "USER_PASS", "FTP_PORT", "FTP_FILE", "LOCAL_FILE");
/* Download any file from server through FTP */
public function ftpGetFile($host, $user, $pass, $port, $ftp_file, $local_file)
{
$adapter = getAdapter($host, $user, $pass, $port);
$filesystem = new Filesystem($adapter);
$path = "./"; //path of directory of remote file
$listing = $filesystem->listContents($path, false); // get file lists
foreach ($listing as $item) {
if($ftp_file == $item->path()) {
$response = $filesystem->readStream($item->path());
$local_path = "{path_of_directory_to_save_file}".'/'.$local_file;
file_put_contents($local_path, $response);
return 1;
}
}
}
public function getAdapter($host, $user, $pass, $port)
{
return new FtpAdapter(
new FtpConnectionOptions(
$host, // host (required)
'/', //path
$user, // username (required)
$pass, // password
$port //port
),
new FtpConnectionProvider(),
new NoopCommandConnectivityChecker(),
PortableVisibilityConverter::fromArray([
'file' => [
'public' => 0640,
'private' => 0604,
],
'dir' => [
'public' => 0740,
'private' => 7604,
],
])
);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment