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.
Before writing the PHP script, make sure that your server is set up with the following environment:
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);
?>
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.