PHP include or require

Be warned that parse error in included file doesn’t cause processing halting in PHP versions prior to PHP 4.3.5. Since this version, it does.

<?php
 
include 'somefile.php';        // http://us.php.net/include
require 'somefile.php';        // http://us.php.net/require
include_once 'somefile.php';   // http://us.php.net/include_once
require_once 'somefile.php';   // http://us.php.net/require_once

On a production server, specially if mission critical, I don't see a good reason to use anything other than below:

<?php
 
if (@include 'plan_A.php') {
  // Plan A;
} elseif (@include 'plan_B.php') {
  // Plan B;
} else {
  // Email webmaster;
  // Call 911, Medic, Fire, Police, the president;
  // Change hard drive, server, hosting service;
}

Or handle any possible trouble first if you wish:

<?php
 
if (!@include 'plan_A.php') {
  // Someone has kidnapped/stolen/corrupted Plan_A.php;
  // Email webmaster;
  // Change hard drive, server, hosting service;
} else {
  // Plan A;
}

You may wish to use:

if(@include_once 'file.php') ...

In mission critical apps, you should not use require or require_once because they will cause a fatal error and halt the php script regardless of the '@' sign. The '@' sign just means “don't show/echo the errors” but the errors happen anyway.

Lessons learned

Pearls of PHP wisdom:

  • Begin with <?php : Always put the start/opening php tab <?php as the first characters of the file/line. Otherwise it will give you headaches unimaginable, and waste days of your time. This is particularly important for configuration files.
  • Skip ?> : Don't put the ending/closing php tag ?> at the end of the include/require files unless you want to break out of php and tell the parser to output results. This is particularly important for configuration files.
  • Within function scope, be careful with include_once or require_once : When inside a function, all variables are limited within the function scope, and require_once and include_once will not include the desired file if it has been included/required in/out of the function.