Current Location: Home> Latest Articles> How to Use PHP to Implement Cross-Server File Transfer on Linux Servers

How to Use PHP to Implement Cross-Server File Transfer on Linux Servers

M66 2025-07-08

1. Introduction

In cross-server file transfers, we often need to move files from one server to another. This article will show you how to use a PHP script to perform cross-server file transfer on Linux servers, complete with a detailed code example.

2. Preparations

Before writing the PHP script, make sure that your server is set up with the following environment:

  • Install PHP: Ensure that PHP is installed on your Linux server and the version meets the requirements for the script.
  • Set file directory permissions: Make sure the directory containing the files has read and write permissions for file reading and writing operations.
  • Configure SSH: Ensure that SSH key authentication is set up between the servers for secure file transfer.

3. Writing the PHP Script

Here is an example PHP script to implement cross-server file transfer on Linux servers:

<?php
// Source server information
$sourceServer = array(
    'host' => 'Source server IP address',
    'port' => 'SSH port (default 22)',
    'username' => 'Source server username',
    'password' => 'Source server password',
);
// Target server information
$targetServer = array(
    'host' => 'Target server IP address',
    'port' => 'SSH port (default 22)',
    'username' => 'Target server username',
    'password' => 'Target server password',
);
// Source file path
$sourceFile = '/path/to/source/file';
// Target file path
$targetFile = '/path/to/target/file';
// Create SSH connection (source server)
$sshSource = ssh2_connect($sourceServer['host'], $sourceServer['port']);
ssh2_auth_password($sshSource, $sourceServer['username'], $sourceServer['password']);
// Create SSH connection (target server)
$sshTarget = ssh2_connect($targetServer['host'], $targetServer['port']);
ssh2_auth_password($sshTarget, $targetServer['username'], $targetServer['password']);
// Execute file transfer (from source server to target server)
if (ssh2_scp_recv($sshSource, $sourceFile, $targetFile)) {
    echo 'File transfer successful';
} else {
    echo 'File transfer failed';
}
// Close SSH connection
ssh2_disconnect($sshSource);
ssh2_disconnect($sshTarget);
?>

4. Conclusion

With this PHP script example, you can achieve file transfer between Linux servers. You can modify and optimize the code based on your specific needs.

For enhanced security, it is recommended to use SSH key authentication instead of password authentication when making the connection for file transfer.