How to SCP (Secure Copy) files using PHP5

This article will explain how to SCP (Secure Copy) files using PHP5. SCP is a secure method of copying files from one host to another using the SSH protocol. Here is a snippet of working code to help get you started!

$hostname = "target_host";
$username = "root";
$password = "password";
$sourceFile = "test.txt";
$targetFile = "/root/test.txt";
$connection = ssh2_connect($hostname, 22);
ssh2_auth_password($connection, $username, $password)
ssh2_scp_send($connection, $sourceFile, $targetFile, 0777);

This is a very simple script that does 3 things:

1) Connect to the host target_host

2) Authenticate with the host using root as the username and password for the password.

3) Copy the local file test.txt to /root/test.txt on the target machine.
Note:  0777 sets the permission on the target file so that it can be read/write/executed by anyone.

See also  Laravel vs Django for REST API Development

2 thoughts on “How to SCP (Secure Copy) files using PHP5”

  1. I know this is an old post, but just in case…I am getting this error, and I have tried to install the dll and everything I have read about, on both flavours, 64 and 32, but no avail. I can’t get SSH to show up on phpinfo.

    Fatal error: Call to undefined function ssh2_connect()

    That is the error I am getting. I am running PHP 5.6.5

    Thank you

  2. Hello I am also getting a “Fatal error: Call to undefined function ssh2_connect()” message.

    Running PHP 7 within a WordPress 4.9 environment.

Leave a Comment