John Davidson

How to put files in SFTP using PHP yii2

0 comments
Message:


I want to put these files to my SFTP server


Array
(
[0] => admin/web/uploads/invoice/21-1623165946--invoice.pdf
[1] => admin/web/uploads/invoice/4-1623166165--invoice.pdf
[2] => admin/web/uploads/invoice-csv/Created-2021-06-15_05-34-22.csv
)

with the all permissions eg.0777 in the folder
the folder structure will be like this



root
|--test
|--|--(create a directory current date in Y-m-d format and give all permission eg.0777)
|--|--|--inside that folder the list of files must be uploaded

I have configured my project and installed PHP yii2 extension from yii2-gftp and have done all the things as per installation guide


I have searched everywhere and haven't find a single demo code for this, have anyone faced this kind of problem please let me know how you solved this.



My Answer:
To put files in SFTP using PHP yii2, you can use the yii2-gftp extension. Here is an example code snippet to achieve this:

php
use yii\gftp\SftpClient;

// Array of files to upload
$files = [
'admin/web/uploads/invoice/21-1623165946--invoice.pdf',
'admin/web/uploads/invoice/4-1623166165--invoice.pdf',
'admin/web/uploads/invoice-csv/Created-2021-06-15_05-34-22.csv'
];

// Connect to SFTP server
$client = new SftpClient('sftp.example.com', 'username', 'password');

// Create directory with current date in Y-m-d format
$directory = date('Y-m-d');
$client->mkdir('/test/' . $directory, 0777);

// Upload files to the created directory
foreach ($files as $file) {
$client->put('/test/' . $directory . '/' . basename($file), $file);
}

// Close the connection
$client->disconnect();


Make sure to replace 'sftp.example.com', 'username', and 'password' with your SFTP server details. This code snippet will create a directory with the current date in Y-m-d format inside the '/test' directory on the SFTP server and upload the files from the array to that directory with permissions set to 0777.

Rate this post

4 of 5 based on 5814 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us