Save file from url with curl PHP

Save file from url with curl PHP

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Save file from url with curl PHP

Attempting to fetch a binary asset like an image directly into a string and then writing it to disk often leads to unexpected failures. The provided code snippet attempts this by retrieving the content via curl_exec() and immediately piping the output into a file handle opened with 'w' mode. This approach is fundamentally flawed because text mode truncates null bytes and can corrupt binary data, causing images to fail rendering or PHP scripts to throw warnings about invalid arguments when processing the result later.

The core issue lies in how curl_exec() handles the response versus how the file is being written. When you call curl_exec(), it returns a string containing the body of the HTTP response. If you then open a file with fopen($file, 'w'), you are treating the data as text. Binary files, such as JPEGs or PNGs, contain raw bytes that do not map cleanly to character encodings. Writing these bytes to a file in text mode can alter the data stream before it hits the disk, resulting in a corrupted file. To fix this, you must open the target file with 'wb' (write binary) permissions to ensure every byte is preserved exactly as received from the remote server.

Furthermore, relying on curl_exec() and curl_close() inside a function without proper error handling leaves your application vulnerable to silent failures. If the remote URL returns an HTTP 404 or if the connection times out, curl_exec() simply returns an empty string. Your current code accepts this empty string and writes nothing, making it impossible to debug why the file was not created. You need to explicitly check the return value of curl_exec() and inspect the HTTP status code returned by the request.

Here is a corrected implementation that addresses binary safety and error reporting:

function downloadFileFromUrl($url, $destinationPath)
{
    $ch = curl_init();
    
    // Set up the basic options
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); 
    // Do not return transfer as string; use this in stream mode and with fwrite()
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
    
    // Execute the request
    if (!curl_exec($ch)) {
        $error = curl_error($ch);
        curl_close($ch);
        throw new Exception("cURL error: $error");
    }

    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) {
        throw new Exception("Failed to download file. HTTP status: $httpCode");
    }

    // Ensure the destination directory exists and is writable
    $directory = dirname($destinationPath);
    if (!is_dir($directory) && !mkdir($directory, 0755, true)) {
        throw new Exception("Unable to create directory: $directory");
    }

    return $destinationPath;
}

In this version, CURLOPT_RETURNTRANSFER is set to false. This forces cURL to output the data directly to the stream rather than buffering it into a variable first. Since we are not capturing the response in a string variable here, we assume the file will be written directly to disk via file_put_contents or by redirecting the cURL handle to a file object.

However, if you specifically need to process the data before saving, or if your hosting environment restricts direct stream redirection, using CURLOPT_RETURNTRANSFER is acceptable provided you write the result in binary mode. The logic for writing the file would then look like this:

$sourceCode = $result; // From curl_exec
if ($sourceCode === false) {
    throw new Exception("cURL execution failed");
}

$handle = fopen('/img/uploads/' . $iconfilename, 'wb'); 
// Note the 'b' flag for binary writing

if ($handle !== false) {
    fwrite($handle, $sourceCode);
    fclose($handle);
} else {
    throw new Exception("Unable to open file for writing");
}

One critical pitfall in the original code is the use of $iticon and $iconfilename without validation. If these variables contain user input or dynamic paths, you risk directory traversal attacks. Always sanitize filenames using basename() and validate them against a whitelist of allowed characters before constructing the file path. Additionally, ensure that the target directory (/img/uploads/) exists and has the correct permissions; otherwise, the script will fail silently or throw a permission error depending on your PHP error reporting settings.

For developers working within the Laravel ecosystem, handling HTTP requests is often abstracted away from raw cURL usage. Libraries like Illuminate\Http\Facades\response or the dedicated GuzzleHttp package provide cleaner interfaces for downloading files. If you are looking for robust solutions to handle file downloads, caching, and validation in a larger application context, resources such as https://laravelcompany.com offer documentation on leveraging these modern frameworks to simplify I/O operations without reinventing the wheel with low-level cURL calls.

Our network