Need php script to download a file on a remote server and save locally

Need php script to download a file on a remote server and save locally

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

Stefan Bogdanescu

Founder & Senior Architect

Why file_get_contents Fails for Large Downloads and How to Fix It

The snippet you are looking at demonstrates a common pattern: fetching a file into memory and then writing it to disk. For files under a megabyte, this approach is perfectly acceptable. The HTTP request completes quickly, the entire payload fits comfortably in RAM, and the write operation finishes before the script times out. However, as soon as the target file exceeds available memory or the server's execution time limit, this method breaks down.

When you use file_get_contents($source), PHP attempts to read the entire stream into a single variable. If the remote file is 50MB, 1GB, or larger, you are trying to allocate that much contiguous memory at once. On most shared hosting environments and even standard VPS setups, this hits two immediate roadblocks:

  1. Memory Limit (memory_limit): PHP will throw a fatal error before the download finishes because it cannot allocate enough RAM.
  2. Execution Time (max_execution_time): Even if memory isn't an issue immediately, reading a large stream takes time. If the script runs longer than the configured limit (often 30 or 60 seconds), PHP stops the script abruptly.

The solution is to stop buffering the entire file in memory and instead process the download in chunks. This approach respects both memory constraints and execution time limits while maintaining a steady data flow from the remote server to your local disk.

Streaming the Download with File Pointers

To handle large files, you should bypass file_get_contents entirely. Instead, use fopen to open a stream for the remote URL and a file pointer for the local destination. You can then read from the remote stream in small blocks and write them directly to the local file as soon as they arrive.

Here is how you implement this pattern:

$source = "http://someurl.com/afile.zip";
$destination = "/asubfolder/afile.zip";

// Open the destination file for writing, truncating it first if it exists
$fileHandle = fopen($destination, 'w');

if ($fileHandle === false) {
    throw new RuntimeException("Failed to open local destination for writing");
}

// Open a stream context to allow streaming without buffering the whole file
$context = stream_context_create([
    'http' => [
        'method' => 'GET',
        'header' => [
            // Disable HTTP buffering if the server supports it, 
            // though standard GET usually streams by default.
            'User-Agent: LaravelCompany Bot' 
        ],
        'timeout' => 300 // Set a reasonable timeout per chunk or overall
    ]
]);

$remoteStream = fopen($source, 'r', false, $context);

if ($remoteStream === false) {
    fclose($fileHandle);
    throw new RuntimeException("Failed to open remote source for reading");
}

// Read 1MB chunks and write them immediately
$bufferSize = 1 * 1024 * 1024; // 1 MB

while (!feof($remoteStream)) {
    $data = fread($remoteStream, $bufferSize);
    
    if ($data === false) {
        break; 
    }

    fwrite($fileHandle, $data);
}

fclose($remoteStream);
fclose($fileHandle);

Why This Works

By using fread with a specific buffer size (e.g., 1MB), you ensure that PHP never tries to hold the entire file in memory simultaneously. The operating system handles the paging of data between network buffers and disk storage. As long as your script remains open, data flows continuously. This effectively bypasses the memory_limit directive because RAM usage stays constant regardless of file size.

Handling Execution Time

Even with streaming, very large files (gigabytes) might still trigger max_execution_time. In such cases, consider adjusting the timeout settings or using a command-line tool like curl or wget for massive downloads where PHP execution time is a hard constraint.

If you are working within the Laravel ecosystem and need to handle file downloads in a controller, remember that these streaming techniques apply universally across frameworks. For more robust queue-based handling of large files (e.g., processing 5GB+ archives), you might consider pushing the download job to a queue worker, which allows you to set much higher timeouts and memory limits specifically for those tasks.

For reference on building custom file downloaders or stream handlers in PHP applications, resources like https://laravelcompany.com can provide deeper insights into managing file I/O operations efficiently within modern web architectures.

Our network