Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is faster: include() or file_get_contents()?

I am working on a SEO system for my project and am optimizing all links with a single page.

Excerpt from .htaccess file:

RewriteRule ^(.+)$ seo.php [L,QSA]

This SEO file (seo.php) will get the requested path and parse it to be as valid url into my script.

I am using include('cat.php?catid=1') at the end of seo.php and everything is working fine, but I wonder which is faster: include() or file_get_contents()?

When I use file_get_content('cat.php?catid=1'), it displays the source of the PHP file, but when I use file_get_content('http://localhost/cat.php?catid=1'), it displays the normal page.

So, which is faster: file_get_content() or include()?

like image 815
Noob Avatar asked May 02 '12 19:05

Noob


2 Answers

They are of course different

  • Include will parse PHP code inside it
  • file_get_contents will return just the content

So if yuo want just to retrive the html content of page use file_get_contents otherwise if you need to parse PHP code use include();

Notice: if you want to retrive the content of a page hosted on your website you should use local path not web path to your resource, ie:

  • Do: file_get_contents('/home/user/site/file.html');
  • Do Not: file_get_contents('http://example.com/file.html');
like image 196
dynamic Avatar answered Sep 20 '22 09:09

dynamic


If you're loading your own local files as part of the template, use either require, or include. Of course you could use require_once or include_once, but don't use file_get_contents for local files.

This doesn't have anything to do with performance, it's about purpose. file_get_contents doesn't exist for dynamically loading in template dependencies. Not unless you need to parse their content prior to showing, or they're on some other domain, which would be very unlikely.

like image 42
Sampson Avatar answered Sep 21 '22 09:09

Sampson