Noob
Noob

Reputation: 2927

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()?

Upvotes: 8

Views: 8190

Answers (4)

dynamic
dynamic

Reputation: 48141

They are of course different

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

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

Notice: if you want to retrieve 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');

Upvotes: 16

Chemwile
Chemwile

Reputation: 1

Correction: you cant use local path with file_get_contents:

file_get_contents('/home/user/site/file.html');  <-- will never work.

file_get_contents('http://site.com/file.html');  <-- this should work.

Upvotes: -6

Your Common Sense
Your Common Sense

Reputation: 157989

  1. This is a pointless question. Both of them fast enough. No need to bug yourself with questions out of nowhere.
  2. include('cat.php?catid=1'); will never work
  3. calling your own code via HTTP request is wrong.

So, the code should be

include('cat.php');

Upvotes: -2

Sampson
Sampson

Reputation: 268462

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.

Upvotes: 2

Related Questions