Introduction
Uploading files to FTP servers is vital when you want to store sensitive information. An FTP server is a unique computer dedicated to receiving FTP connections/information using the File Transfer Protocol (FTP) address. FTP is a standard network protocol leveraged when transferring computer files between a server and a client on a specified computer network. The protocol is engineered on a powerful client-server architecture and utilizes separate data connections and controls between the server and the client.
Magento offers reliable FTP access and capability that help you download or upload folders and files from a hosting server or local PC. There are many options for uploading files to an FTP server in Magento 2, and one of the simplest is using coding. The use of code comes in handy when you want to share critical information such as Magento 2 reports with shareholders and have their FTP addresses.
This tutorial will help you transfer a file to an FTP server in your Magento 2 website using source codes.
Ready? Let’s get started!
The functions we’ll use belong to this class:
\Magento\Framework\Filesystem\Io\Ftp
As a result, you first declare the mentioned class in a construct.
protected $ftp; public function __construct( \Magento\Framework\Filesystem\Io\Ftp $ftp ){ $this->ftp = $ftp; }
Step 1 – Creating The FTP Connect
An FTP connection is indispensable when uploading files or images to an FTP server. Without this connection, you cannot view or upload files to your server. To create an FTP connection in Magento 2, run the following command:
$open = $this->ftp->open( array( 'host' => 'test.localhost.com', 'user' => 'test', 'password' => 'test', 'ssl' => true, 'passive' => true ) );
This will establish the FTP connection, and you can now commence on transferring the file to an FTP server.
Step 2 – Uploading The File Using The Write Function
Next, use the written function to upload your file to the FTP server. Run the command below to initiate the transfer:
if ($open) { $fileName = 'test.csv'; $content = file_get_contents(DirectoryList::VAR_DIR . '/' . $fileName); $this->ftp->write(self::FILE_NAME_ON_FTP, $content); $this->ftp->close(); }
That’s It!
Conclusion
You have successfully transferred your file to an FTP server using codes. This is a short process that is easy to follow and is one of simplest ways to handle your FTP server on Magento 2.
Check out these top 3 Magento hosting services:
- Your query to the best web hosting can end by clicking on this link.