How to Download a File from URL and Save It to Server Using PHP cURL
Sometimes you need to download a file from a remote URL and save it on your server automatically. This is very useful for file sharing websites, backup systems, and automation tools.
In this tutorial, we will create a simple PHP script that:
- Creates a download folder automatically
- Fetches file headers first
- Detects the correct file name
- Downloads the file
- Saves it to the server
Complete Working PHP Code
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
set_time_limit(0);
/*
|--------------------------------------------------------------------------
| SETTINGS
|--------------------------------------------------------------------------
*/
$url = "https://example.com/file.zip"; // Replace with your file URL
$saveDir = __DIR__ . "/downloads/";
/*
|--------------------------------------------------------------------------
| Ensure the downloads directory exists
|--------------------------------------------------------------------------
*/
if (!file_exists($saveDir)) {
mkdir($saveDir, 0755, true);
}
/*
|--------------------------------------------------------------------------
| STEP 1: Get headers to detect file name
|--------------------------------------------------------------------------
*/
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
if (!$response) {
echo "<p style='color:red;'>Error: " . curl_error($ch) . "</p>";
curl_close($ch);
exit;
}
/*
|--------------------------------------------------------------------------
| Convert headers into array
|--------------------------------------------------------------------------
*/
$headers = [];
$lines = explode("\n", $response);
foreach ($lines as $line) {
$line = trim($line);
if (strpos($line, ":") !== false) {
list($key, $value) = explode(":", $line, 2);
$headers[trim($key)] = trim($value);
}
}
/*
|--------------------------------------------------------------------------
| Default file name from URL
|--------------------------------------------------------------------------
*/
$fileName = basename(parse_url($url, PHP_URL_PATH));
/*
|--------------------------------------------------------------------------
| Check Content-Disposition header
|--------------------------------------------------------------------------
*/
if (isset($headers['Content-Disposition'])) {
$contentDisposition = $headers['Content-Disposition'];
if (preg_match('/filename="([^"]+)"/', $contentDisposition, $matches)) {
$fileName = $matches[1];
} elseif (preg_match("/filename=([^;]+)/", $contentDisposition, $matches)) {
$fileName = trim($matches[1]);
}
}
$fileName = urldecode($fileName);
curl_close($ch);
/*
|--------------------------------------------------------------------------
| STEP 2: Download the file
|--------------------------------------------------------------------------
*/
$savePath = $saveDir . $fileName;
$fp = fopen($savePath, "w+");
if (!$fp) {
die("Cannot create file: " . $savePath);
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if (curl_exec($ch)) {
echo "<p style='color:green;'>File successfully saved to:</p>";
echo "<b>" . $savePath . "</b>";
} else {
echo "<p style='color:red;'>Download Error:</p>";
echo curl_error($ch);
}
curl_close($ch);
fclose($fp);
?>
How This Script Works
1. Create Download Folder Automatically
if (!file_exists($saveDir)) {
mkdir($saveDir, 0755, true);
}
If the folder does not exist, it will be created automatically.
2. Fetch Headers First
curl_setopt($ch, CURLOPT_NOBODY, true);
This tells cURL to get only headers before downloading the file. This helps detect the correct file name.
3. Detect File Name from Header
Some servers send the real file name in the header:
Content-Disposition: attachment; filename="movie.mp4"
The script extracts the file name automatically.
4. Download the File
curl_setopt($ch, CURLOPT_FILE, $fp);
This tells cURL to save the file directly to disk instead of memory. This is important for large files.
Example Output
File successfully saved to:
/home/user/downloads/file.zip
Use Cases
- File sharing websites
- Remote upload tools
- Backup systems
- Downloader scripts
- Automation servers
- API integrations
Important Notes
- Works best with direct file links
- Supports large files
- Automatically detects file name
- Creates download folder if missing
Conclusion
In this tutorial, we learned how to download and save files from a URL using PHP cURL. This method is reliable, fast, and suitable for automation systems and file sharing websites.
