What are some common methods for uploading files to external servers using PHP scripts?

Uploading files to external servers using PHP scripts can be achieved using methods like cURL, FTP, or APIs provided by cloud storage services like Amazon S3 or Google Cloud Storage. These methods allow you to securely transfer files from your server to an external server without exposing sensitive information.

// Using cURL to upload a file to an external server
$filePath = '/path/to/file.jpg';
$uploadUrl = 'http://example.com/upload.php';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uploadUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
    'file' => new CURLFile($filePath)
]);
$response = curl_exec($ch);

if ($response === false) {
    echo 'Error uploading file';
} else {
    echo 'File uploaded successfully';
}

curl_close($ch);