bradi
bradi

Reputation: 39

difference between readfile() and fopen()

These two codes both do the same thing in reading files , so what's the main difference ?

1-First code :

$handle = fopen($file, 'r');
$data = fread($handle, filesize($file));

2-Second code :

readfile($file);

Upvotes: 2

Views: 3043

Answers (2)

Sherif
Sherif

Reputation: 11943

There's a significant difference between fread() and readfile().

First, readfile() does a number of things that fread() does not. readfile() opens the file for reading, reads it, and then prints it to the output buffer all in one go. fread() only does one of those things: it reads bytes from a given file handle.

Additionally, readfile() has some benefits that fread() does not. For example, it can take advantage of memory-mapped I/O where available rather than slower disk reads. This significantly increases the performance of reading the file since it delegates the process away from PHP itself and more towards operating system calls.

Errata

I previously noted that readfile() could run without PHP (this is corrected below).

For truly large files (think several gigs like media files or large archive backups), you may want to consider delegating the reading of the file away from PHP entirely with X-Sendfile headers to your webserver instead (so that you don't keep your PHP worker tied up for the length of an upload that could potentially take hours).

So you could do something like this instead of readfile():

<?php
/* process some things in php here */
header("X-Sendfile: /path/to/file");
exit; // don't need to keep PHP busy for this

Upvotes: 4

Markus Zeller
Markus Zeller

Reputation: 9135

Reading the docs, readfile reads the whole content and writes it into STDOUT.

$data = fread($handle, filesize($file));

While fread puts the content into the variable $data.

Upvotes: 2

Related Questions