PHP

How to copy files in PHP using SCP – Step-by-Step

Updated

php copy files

ssh2_connect() does not verify the server’s host key, and nothing in the usual PHP SCP recipe adds that check. Add it yourself before you authenticate, or every “secure” transfer you write is one DNS answer away from handing your credentials to a stranger. The hazard is not specific to PHP, only its shape is: in Ruby, Net::SSH raises HostKeyMismatch and the usual mistake is rescuing it away, which leaves the same hole by a different route:

$expected = 'ABFD4ED7BB392E3B7AB6889619974D97E3AA13A2';   // your server's key, recorded once
$c  = ssh2_connect('remote.server.com', 22);
$fp = ssh2_fingerprint($c, SSH2_FINGERPRINT_SHA1 | SSH2_FINGERPRINT_HEX);
if (!hash_equals($expected, $fp)) {
    throw new RuntimeException("host key mismatch: $fp");
}
ssh2_auth_pubkey_file($c, 'username', '/path/id_ed25519.pub', '/path/id_ed25519');

What happens without that check

I ran a real OpenSSH server on this machine, recorded its fingerprint, then replaced its host key and restarted it — the same thing a reader would see if someone got between them and their server. The ssh client refused to proceed, exiting 255:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

PHP, using the usual recipe without a fingerprint check, did not:

connected to imposter: yes
fingerprint:           8EAC64DE981A79B3729432339BDDED265A6DCD6D   (was ABFD4ED7...)
auth against imposter: SUCCEEDED
scp_send to imposter:  SUCCEEDED

No warning, no error, file delivered. With ssh2_auth_password() the plaintext password is what gets handed over. There is no known-hosts file behind ssh2_connect(); the fingerprint comparison above is the entire defence.

ssh2_scp_send() speaks the protocol OpenSSH deprecated

Since OpenSSH 9.0 the scp command has used SFTP underneath. Its own manual page says -O exists to “Use the legacy SCP protocol for file transfers instead of the SFTP protocol.” I watched both from the server side. Plain scp logs:

Starting session: subsystem 'sftp' for [user] from 127.0.0.1

while scp -O logs Starting session: command. PHP’s ssh2_scp_send() and ssh2_scp_recv() log Starting session: command too — they are on the old path. Switching to the SFTP calls in the same extension moves you to the subsystem channel, and this wrapper syntax does work:

$sftp = ssh2_sftp($c);
$fh   = fopen("ssh2.sftp://$sftp/remote/path/file.txt", 'w');
fwrite($fh, file_get_contents('/local/path/file.txt'));
fclose($fh);
ssh2_disconnect($c);          // not unset($connection)

unset($connection) is not how you close the session — ssh2_disconnect() is, and it exists. And the extension is not something you enable with a line in php.ini: ssh2 is not bundled with PHP. It is PECL ssh2, latest stable 1.5.0 released 2026-04-04, which I compiled here against PHP 8.5.8 and libssh2 1.11.1 to run these tests. If you cannot install PECL extensions on your host, phpseclib (3.0.56, 3 August 2026) is pure PHP and needs no extension.

The command-line traps, checked against OpenSSH 10.3p1

-P is the port; -p preserves timestamps. ssh uses lowercase -p for the port and scp and sftp use uppercase -P. Getting it backwards produces a message that names neither problem: scp -p 52222 file host:/dest fails with scp: stat local "52222": No such file or directory, exit 255, because 52222 was parsed as a filename.

A trailing slash on the source does nothing. This is the opposite of rsync, and advice gets copied between the two. scp -r tree host:dest and scp -r tree/ host:dest both produced dest/tree/f1.txt here — identical results. If you want the contents rather than the directory, name them: scp -r tree/. host:dest, or use rsync, which does honour the slash.

Without -r, a directory is an error, not a silent skip. scp: local "…/tree" is not a regular file, exit 1.

Quoting rules inverted in OpenSSH 9.0. The advice you will find everywhere is to double-quote remote paths containing spaces, once for your shell and once for the remote shell. With the SFTP backend there is no remote shell, so that now breaks: scp host:"'/path/my file.txt'" . fails with No such file or directory — the quotes are taken as part of the filename. Quote once, for your local shell only, and it works. Under -O neither form worked on this build: unquoted split on the space into two missing files, and the double-quoted form was rejected with protocol error: filename does not match request. Remote globs like host:'/dir/*.log' still expand correctly and copied exactly the two matching files.

Prefer rsync for anything repeated

scp re-sends the whole file every time and cannot resume. For deployments, backups or any cron job, rsync -a --delete -e ssh src/ host:dst/ transfers only differences and gives you --dry-run before it deletes anything. Note that macOS 26 ships openrsync (protocol 29) rather than GNU rsync, so some long options differ; check rsync --version on both ends. From PHP, shelling out to rsync or scp via proc_open() with an argument array — never a concatenated string — is a legitimate and often better choice than the extension.

What was executed and what was not

Executed here: an OpenSSH 10.3p1 sshd on a loopback port with its own host key, every scp behaviour above against it with the server log as evidence, a build of PECL ssh2 1.5.0 against PHP 8.5.8, and every PHP snippet including the host-key swap. The fingerprints are from that throwaway server; yours will differ. A loopback sshd on a free port with a freshly generated host key is what /verify/copy-files-with-scp.sh starts in order to stage the host-key swap and run the scp commands described above, with a client key and known_hosts file of its own; nothing it creates outlives the run.

Not tested: transfers over a real network, so nothing here speaks to throughput or resumption; SFTP servers other than OpenSSH’s; Windows PHP builds. That OpenSSH switched scp to SFTP at 9.0 comes from the scp(1) page shipped with 10.3p1, not from testing a 9.0 build.

One edit to the output above: the account name in every command result on this page has been replaced with [user]. Nothing else is altered — the commands, their output, the permissions, the timings and the errors are exactly as they ran.

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.