First of all, I'm very new to php, so bear with me. I'm wondering if I can upload a file that I have on my desktop to a remote SHH server using php. I have the ip address, port number, username, and password if that helps, but have no clue as to how to approach this problem. I read that using an html post only allows you to upload files to a local server, not a remote one. Any ideas?
Asked
Active
Viewed 332 times
-2
-
You [can](https://stackoverflow.com/questions/4689540/how-to-sftp-with-php) - whether you *should* or not is a different question; there's likely to be a better approach. – CD001 Jul 26 '19 at 10:08
-
@CD001 So, will I put the path of my desktop file in here: $stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r'); – jl1126 Jul 26 '19 at 10:21
-
That `$stream` would be the filesystem stream to the remote server, you'd want to nab the content of the file on your desktop (e.g. `file_get_contents`) and write it to that stream (`fwrite`) to put a copy on the remote server. – CD001 Jul 26 '19 at 10:38
-
@CD001 Do you think you could provide a code sample of that? – jl1126 Jul 26 '19 at 11:29
-
Quick search turned this up: https://stackoverflow.com/questions/9572314/uploading-files-with-sftp - seems there's already a function to do it built-in `stream_copy_to_stream` ... – CD001 Jul 26 '19 at 13:06
-
Possible duplicate of [Uploading files with SFTP](https://stackoverflow.com/questions/9572314/uploading-files-with-sftp) – CD001 Jul 26 '19 at 13:07
1 Answers
0
Phpseclib has a class based interface for interacting with SFTP.
For example:
require __DIR__ . '/vendor/autoload.php';
use phpseclib\Net\SFTP;
$sftp = new SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
// puts a three-byte file named filename.remote on the SFTP server
$sftp->put('filename.remote', 'xxx');
// puts an x-byte file named filename.remote on the SFTP server,
// where x is the size of filename.local
$sftp->put('filename.remote', 'filename.local', SFTP::SOURCE_LOCAL_FILE);
SFTP documentation: http://phpseclib.sourceforge.net/sftp/intro.html

atymic
- 3,093
- 1
- 13
- 26
-
Do you know how to do this with ssh2 functions? And will it allow me to upload from desktop to remote server? – jl1126 Jul 26 '19 at 10:23
-
You can only use the `ssh2` functions if your PHP version includes the extensions. – atymic Jul 26 '19 at 10:24
-