Uploading files with SFTP
To upload files using SFTP (Secure File Transfer Protocol) in PHP, you can use the SSH2 extension, which allows you to connect to an SFTP server and perform various operations such as uploading, downloading, and deleting files.
To upload files using SFTP (Secure File Transfer Protocol) in PHP, you can use the SSH2 extension, which allows you to connect to an SFTP server and perform various operations such as uploading, downloading, and deleting files. Here is an example of how you can use the SSH2 extension to upload a file to an SFTP server:
Example of uploading files using SFTP (Secure File Transfer Protocol) in PHP
<?php
$connection = ssh2_connect('example.com', 22);
if (!$connection) {
exit('Connection failed');
}
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);
$file = '/path/to/local/file.txt';
$remote_file = '/path/to/remote/file.txt';
$stream = ssh2_sftp_fopen($sftp, $remote_file, 'w');
fwrite($stream, file_get_contents($file));
fclose($stream);
?>This example first establishes a connection to the SFTP server using the ssh2_connect function, and then authenticates with a username and password using the ssh2_auth_password function. Next, it opens an SFTP session using the ssh2_sftp function and then uses ssh2_sftp_fopen and fwrite to upload the file.
Note: The ssh2 extension requires the libssh2 library. Install it via your system package manager and PECL (e.g., sudo apt install libssh2-1-dev && pecl install ssh2), or use your PHP distribution's extension manager.
Alternatively, you can use other libraries like phpseclib, which provides an SFTP implementation in pure PHP.
Example of using phpseclib library to upload files using SFTP (Secure File Transfer Protocol) in PHP
<?php
require 'vendor/autoload.php';
use phpseclib3\Net\SFTP;
$sftp = new SFTP('example.com');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
$local_file = '/path/to/local/file.txt';
$remote_file = '/path/to/remote/file.txt';
$sftp->put($remote_file, $local_file, SFTP::SOURCE_LOCAL_FILE);
?>Note: Install phpseclib3 via Composer: composer require phpseclib/phpseclib.
Please note that these are just examples and actual implementation might change depending on your requirements.