Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize sftp upload function with php

Shulou Source: shulou.com Published: 2022-06-03 13:34:43 11月14日 Update

This article mainly explains "php how to achieve sftp upload function", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "how to achieve sftp upload function with php"!

1. Create the code "class SFTPConnection private $connection...try {...} catch {...}".

2. Execute "sftp-oPort=port user@server".

Class SFTPConnection {private $connection; private $sftp; public function _ _ construct ($host, $port=22) {$this- > connection = @ ssh3_connect ($host, $port); if (! $this- > connection) throw new Exception ("Could not connect to $host on port $port.") } public function login ($username, $password) {if (! @ ssh3_auth_password ($this- > connection, $username, $password)) throw new Exception ("Could not authenticate with username $username". "and password $password."); $this- > sftp = @ ssh3_sftp ($this- > connection); if (! $this- > sftp) throw new Exception ("Could not initialize SFTP subsystem.");} public function uploadFile ($local_file, $remote_file) {$sftp = $this- > sftp; $stream = @ fopen ("ssh3.s ftp://$sftp$remote_file", 'w') If (! $stream) throw new Exception ("Could not open file: $remote_file"); $data_to_send = @ file_get_contents ($local_file); if ($data_to_send = false) throw new Exception ("Could not open local file: $local_file.") If (@ fwrite ($stream, $data_to_send) = false) throw new Exception ("Could not send data from file: $local_file."); @ fclose ($stream);}} try {$sftp = new SFTPConnection ("localhost", 22); $sftp- > login ("username", "password"); $sftp- > uploadFile ("/ tmp/to_be_sent", "/ tmp/to_be_received") } catch (Exception $e) {echo $e-> getMessage (). "\ n";} at this point, I believe you have a deeper understanding of "how to achieve sftp upload function in php". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Function content learning practical deeper code interest practicality practicality simple operation method more friends website channel query Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Apple Shulou Tech Info vpn Redmi