Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance: file_get_contents(), Relative and Absolute URLs

Tags:

php

Is there any performance advantage if I use relative paths as argument in file_get_contents()?

file_get_contents("../../mypage.php");

v/s

file_get_contents("http://.../mypage.php");

How is file_get_contents() handled internally?

like image 373
Anirudh Ramanathan Avatar asked Dec 20 '22 18:12

Anirudh Ramanathan


2 Answers

There can definitely be a noticeable performance difference in using local files versus remote - even if the "remote" file is on your local server.

When you use a local/relative file such as file_get_contents("../../mypage.php");, it's loaded directly on the server with no need to use network traffic. For remote loads, such as file_get_contents("http://localhost/mypage.php"); or file_get_contents("http://example.org/mypage.php");, a connection to the remote host is established (even when "local"). Additionally, a local read will result in the function returning exactly what's in the file; a remote read will result in the remote-host rendering the contents (if it's PHP) before returning.

The performance for a local/relative file would, by default, be faster than a remote one. The biggest noticeable performance advantage can be seen when attempting to load a remote file from a network that has a slower connection.

The internal implementation of file_get_contents() is similar to you writing fopen() and a loop for fread(), and then closing with fclose(). Then, it returns a string of all of the contents found in the file. Basically, it provides a much friendlier "read from a file" interface.

To read more about the method, you can check out the manual at php.net/manual/en/function.file-get-contents.php

like image 166
newfurniturey Avatar answered Jan 01 '23 14:01

newfurniturey


If there is a performance advantage, it does not depend on php engine. Paths are processed by the web server you query.

But in this case there is going to be a performance advantage in the first case because you get the file from local fs, and in the second case you have to go through the whole network stack(http/tcp/ip) to get the response. Also first case will return php source and the second - a web page, processed by the php engine.

A clearer example:

file_get_contents('../../somefile.ext');

and

file_get_contents('/home/user/somefile.ext');

are going to be equally fast.

like image 38
Sergey Eremin Avatar answered Jan 01 '23 12:01

Sergey Eremin