Question

I use PHP and file_get_contents. It was really slow even when I tried to speed it up with this:

$opts = array(
    'http'=> array(
    'header' => 'Connection: close'
    )
);
$context = stream_context_create($opts);
$contents = file_get_contents('http://www.example.com/file.txt', false, $context);

I also tried cURL. Same issue.

I've read that include should be slower than file_get_contents. That seems only to be true when NOT including the whole URL but including the relative path, like this...

file_get_contents('../file.txt');

My question is... Why is the relative path much faster than the full URL?

Was it helpful?

Solution

file_get_contents doesn't accept a relative URI. It takes either an absolute URI or a file path.

Using a file path is faster because:

  • Reading from the file system

is less work than:

  • Making an HTTP request
  • Reading the request
  • Loading a file from the file system (possibly executing PHP on the way)
  • Putting it in an HTTP response
  • Sending the response
  • Reading the response
  • Getting the file data out of the response body
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top