How can headers be utilized in PHP to send files to remote servers?
To send files to remote servers using PHP, headers can be utilized to specify the content type and provide necessary information for the server to handle the file correctly. By setting the appropriate headers, the file can be transmitted to the remote server seamlessly.
$file_path = 'path/to/local/file.txt';
$remote_url = 'http://example.com/upload.php';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $remote_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('file' => '@' . $file_path));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if ($response === false) {
echo 'Error: ' . curl_error($ch);
} else {
echo 'File successfully sent to remote server.';
}
curl_close($ch);