Downloading Remote Files in PHP Using fopen and Stream
This article explains how to use PHP's fopen function and stream handling to download remote files efficiently without loading the entire file into memory, provides a complete code example, outlines important considerations, and also includes a notice for an upcoming PHP training class.
In PHP you can use the fopen() function to open a remote file and stream its contents to a local file, which avoids loading the entire file into memory and prevents possible memory overflow.
Below is a complete example:
<code>$url = 'http://example.com/file.zip';
$local_file = '/path/to/local/file.zip';
// Open remote file
$remote_file = fopen($url, 'r');
// Open local file
$fp = fopen($local_file, 'w');
// Stream download
while (!feof($remote_file)) {
fwrite($fp, fread($remote_file, 1024));
}
// Close files
fclose($remote_file);
fclose($fp);
</code>The code opens both the remote and local files, reads the remote file in 1 KB chunks with fread() , writes each chunk to the local file with fwrite() , and finally closes both handles.
When using stream downloads, ensure the server permits remote access; otherwise errors may occur.
Key points to consider when downloading files with streams:
Make sure the server allows remote access.
If the local file already exists it will be overwritten; use append mode ( 'a' ) to avoid overwriting.
Large downloads may take time; consider showing a progress bar.
Handle cases where the remote file does not exist or access fails.
You can use HTTP headers to control caching, content type, and download behavior.
Ensure both remote and local files are successfully opened before proceeding.
Use feof() to detect the end of the remote file and avoid infinite loops.
Be aware of bandwidth limits and network conditions that may slow the download.
Enable allow_url_fopen in php.ini ; it is enabled by default.
【Class Announcement】
PHP中文网《第23期PHP线上培训班》 will start on 2023‑03‑09. Seats are limited, so register quickly.
Register now to receive three practical courses for free: High Concurrency, Laravel, and Uniapp (limited to the first 50 participants).
Contact via QQ: 27220243 (钟老师) or WeChat: phpcn01 (月月老师) for enrollment.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.