Search code examples
phpsshscpopenssh

How do I retrieve a remote file and store it on the local machine on PHP (using OpenSSH/SCP)?


as the title states, I'm having trouble with retrieving a file from a remote SSH server, through PHP.

I am able to retrieve the file through the Command Shell, but when I attempt to do so through PHP, it does not seem to work.

For example, this is how my code looks like on the PHP script:

echo shell_exec(scp $remoteUser@$remoteIP:$remoteFilePath $localFilePath);

For context, this PHP script is for a web page. Before the above command, I also had another SCP command (where I copy a local file to the remote server) and a SSH command, and those were able to execute successfully without any issues (the commands were executed through shell_exec() as well).


Solution

  • I suggest to use a lib which assists SFTP or SCP usage - for example idct/sftp-client: https://github.com/ideaconnect/idct-sftp-client

    Include it in your project, then create an instance:

    use IDCT\Networking\Ssh\SftpClient;
    use IDCT\Networking\Ssh\Credentials;
    $client = new SftpClient();
    

    Then create set up proper credentials - password or public key:

    # password
    $credentials = Credentials::withPassword($username, $password);
    $client->setCredentials($credentials);
    
    # or key:
    $credentials = Credentials::withPublicKey($username, $publicKey, $privateKey, $passphrase = null);
    $client->setCredentials($credentials);
    

    Then connect and download your file:

    $client->connect($host);
    
    # using sftp
    $client->download(ENTER_REMOTE_FILE_NAME);
    
    # or scp
    $client->scpDownload(ENTER_REMOTE_FILE_NAME);
    
    $client->close();
    

    It is much more elegant than using less secure and system dependent shell_exec. You can use also all the methods youself: ssh2_scp_recv, ssh2_connect etc.