What are the differences between using cURL and file_get_contents in PHP to retrieve and save a file from a URL?
When retrieving and saving a file from a URL in PHP, cURL is often preferred over file_get_contents due to its greater flexibility and functionality. cURL allows for more advanced options such as setting custom headers, handling redirects, and supporting various protocols. On the other hand, file_get_contents is simpler to use but may not offer the same level of control and error handling as cURL.
// Using cURL to retrieve and save a file from a URL
$url = 'https://example.com/file.zip';
$destination = 'downloaded_file.zip';
$ch = curl_init($url);
$fp = fopen($destination, 'w');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
```
```php
// Using file_get_contents to retrieve and save a file from a URL
$url = 'https://example.com/file.zip';
$destination = 'downloaded_file.zip';
file_put_contents($destination, file_get_contents($url));