Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to SFTP with PHP?

Tags:

php

sftp

I have came across many PHP scripts for web FTP clients. I need to implement a SFTP client as a web application in PHP. Does PHP support for SFTP? I couldn't find any samples. Can anyone help me with this?

like image 822
indranama Avatar asked Jan 14 '11 09:01

indranama


People also ask

How do I SFTP to my website?

To establish an SFTP connection to your account, first go to your Site Tools > Devs > SSH Keys Manager and generate a new SSH key pair. You should replace /Users/youruser/private_key with the location of your private key text file.

What is SFTP and how do I use it?

SFTP is a method of transferring data over an SSH channel and works as a subsystem of SSH. This is particularly useful for VPS users! It’s the only file transfer protocol that protects against attacks at any point in the data transfer process, making it the preferred protocol.

What is the PHP SFTP library?

The library provides what it refers to as a “pure- PHP implementation of SFTP ” and supports the most widely used versions of SFTP. To initiate a connection a new object of SFTP is created with the address of the remote server passed to the constructor.

How do I get a list of files in SFTP?

The SFTP class provides methods for SFTP similar to those provided by PHP ’s FTP extension. For example, to get a list of files for the current directory we use nlist () (equivalent of ftp_nlist ):- This saves the remote_file to local_file.

What is the difference between ssh2_scp_send () and SFTP functions?

ssh2_scp_send () has an additional parameter which you can specify what the file permission should be on the remote server when the file is copied. More functionality is available with the SFTP functions; you can change file or directory permissions, fetch information about a file, create directories, rename items, remove items, etc.


2 Answers

PHP has ssh2 stream wrappers (disabled by default), so you can use sftp connections with any function that supports stream wrappers by using ssh2.sftp:// for protocol, e.g.

file_get_contents('ssh2.sftp://user:[email protected]:22/path/to/filename'); 

or - when also using the ssh2 extension

$connection = ssh2_connect('shell.example.com', 22); ssh2_auth_password($connection, 'username', 'password'); $sftp = ssh2_sftp($connection); $stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r'); 

See http://php.net/manual/en/wrappers.ssh2.php

On a side note, there is also quite a bunch of questions about this topic already:

  • https://stackoverflow.com/search?q=sftp+php
like image 104
Gordon Avatar answered Sep 18 '22 16:09

Gordon


The ssh2 functions aren't very good. Hard to use and harder yet to install, using them will guarantee that your code has zero portability. My recommendation would be to use phpseclib, a pure PHP SFTP implementation.

like image 31
calgaryhit Avatar answered Sep 17 '22 16:09

calgaryhit