require

(PHP 4, PHP 5, PHP 7)

requireinclude 几乎完全一样,除了处理失败的方式不同之外。require 在出错时产生 E_COMPILE_ERROR 级别的错误。换句话说将导致脚本中止而 include 只产生警告(E_WARNING),脚本会继续运行。

参见 include 文档了解详情。

add a note add a note

User Contributed Notes 25 notes

up
90
chris at chrisstockton dot org
10 years ago
Remember, when using require that it is a statement, not a function. It's not necessary to write:
<?php
require('somefile.php');
?>

The following:
<?php
require 'somefile.php';
?>

Is preferred, it will prevent your peers from giving you a hard time and a trivial conversation about what require really is.
up
8
Anonymous
10 years ago
A note that drove me nuts for 2 days!

Be carfull if you have a newline or blank space befor your php tags in the included/required file it will read as html and outputed.

If your running your output through javascript string evaluations which would be sensitive to newlines/white spaces be carfull that the first chars in the file are the php tages eg <?php
up
3
dave at davidhbrown dot us
11 years ago
re: danielm at unb dot br...

$_SERVER['DOCUMENT_ROOT'] is very useful, but it is not available with all web servers. Apache has it; IIS doesn't.

I use the following to make my PHP applications work in more situations:
<?php
if (!defined("BASE_PATH")) define('BASE_PATH', isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : substr($_SERVER['PATH_TRANSLATED'],0, -1*strlen($_SERVER['SCRIPT_NAME'])));
?>

...but even that gets tripped up by symlinks to different mount points, etc. You could substitute realpath($_SERVER['PATH_TRANSLATED']), but that function has been reported not to work on some (Windows) servers. One could use the PATH_TRANSLATED for both servers, but I figure if Apache is going to tell me exactly what I want to know, I should listen.
up
-1
gabe at websaviour dot com
11 years ago
If you are experiencing a bug related to using relative paths with include or require, it may be related to a grandparent directory that is executable but not readable.  It will cause __FILE__ to return a relative path instead of the full path which it is supposed to show.  This manifests itself in interesting ways that can be seemingly unrelated.  For instance, I discovered it using the Smarty {debug} command which failed to find its template due to this issue.  Please see the following for more details:

http://bugs.php.net/bug.php?id=34552
http://shiftmanager.net/~kurt/test/
up
-4
tjeerd
11 years ago
When using symbolic links with PHP, specify a dotslash './page.php' path to ensure that PHP is looking in the right directory with nested requires:

E.g. when the required actual page1.php contains other require statements to, say page2.php, PHP will search the path that the symbolic link points to, instead of the path where the symbolic link lives. To let PHP find the other page2.php in the path of the symbolic link, a require('./page2.php'); statement will solve the puzzle.
up
-9
duccio at getlocal dot it
9 years ago
In response to some dot user at notarealdomain dot com:

This is because require executes the code "as if" it was code written inside of the function, inheriting everything including the scope. But here there is something even more interesting:

<requiredfile.php>:
<?php

$this
->a.=" is visible also under a require\n";
$b="While the variable b is a local variable of the function\n";
function
FunctionUnderRequire() {
    echo
"But the functions declared inside of a require called from a class function, just as when defined from inside any other function, are always global\n";
}
?>

<mainfile.php>:
<?php

error_reporting
(E_ALL|E_STRICT);

class
UserClass {

    protected
$a;

    public function
UserFunction() {
       
$this->a='The class variable a';
        require
'requiredfile.php';
        echo
$this->a; // "The class variable a  is visible also under a require\n"
       
echo $this->b; // Notice: Undefined property: UserClass::$b
       
echo $b; // "While the variable b is a local variable of the function\n"
       
$this->FunctionUnderRequire(); //Fatal error!
       
FunctionUnderRequire(); // "But the functions..."
   
}
}

$UserClass=new UserClass;
$UserClass->UserFunction();
?>

I'm wondering if there is a method for declaring class public/private/protected functions from inside a require/include...
up
-8
moreau dot marc dot web at gmail dot com
3 years ago
Petit script pour résoudre le problème de l'inclusion dans l'inclusion.

A requiert B qui requiert C -> l'on doit normalement faire correspondre le requiere de B en fonction de l'endroit ou se trouve A dans l'arborescence du site. Pas de souci, sauf si l'on est amené à requérir B depuis une autre page, impossible alors de faire appel au C -> cela retourne une erreur "fichier non trouvé".

Voici une solution qui marche sur tout type de configuration:

Dans B:

<?php

chdir
(__DIR__); //Sert à indiquer à PHP le dossier de référence de travail

$file_to_require=realpath('./../../adresse_de_C_relative_par_raport_a_B.php'); //Crée l'adresse absolue de C

require($file_to_require); unset($file_to_require);

?>
up
-12
some dot user at notarealdomain dot com
10 years ago
Discovered a bit of weird behavior yesterday involving require() (using PHP 5.2.3).  If you use require() inside a function, the "globals" in the file will be local to the function.  An example of this:

test.php:
<?php
 
function TestFunc()
  {
    require(
'test2.php');
    echo
"<pre>" . print_r($GLOBALS, true) . "</pre>";
  }
?>

test2.php:
<?php
  $MyTestGlobal
= Array();
?>

This happens because require is a statement that _inlines_ the target code - not a function that gets called.

To fix this, use the $GLOBALS superglobal:

test2.php:
<?php
  $GLOBALS
["MyTestGlobal"] = Array();
?>
up
-10
Peter McDonald
10 years ago
re the comment by moazzamk at gmail dot com

As the manual states require and require_once as of PHP 4.02 no longer call the file if the line of code it is on should not be executed.
up
-11
pedro dot evangelista at gmail dot com
9 years ago
Be careful when using symbolic links, because require will search the real path of the file and not the path relative to the symbolic link.

Imagine your script A.php resides on directory /a and you create a symbolic link for it on directory /b/c.
So for the code

<?php
echo realpath("../");
?>

you might expect the directory /b, but actually you get the root directory /.

If you need to include the file /b/B.php inside your A.php, you can't use the following

<?php
require "../B.php";
?>

because it will search the root directory, not the /b directory.

Regards.
up
-12
Marc
12 years ago
This will sound elementary, but for C++ native programmers, be sure NOT to put a '#' in front of your include statements! The parser will not give you an error, but also will not include the file, making for a tedious debugging process.

In short, USE:
<?php
    
include "yourfile.php";
?>

and DON'T use:
<?php
    
#include "yourfile.php";
?>
up
-18
ricardo dot ferro at gmail dot com
9 years ago
Two functions to help:

<?php

function add_include_path ($path)
{
    foreach (
func_get_args() AS $path)
    {
        if (!
file_exists($path) OR (file_exists($path) && filetype($path) !== 'dir'))
        {
           
trigger_error("Include path '{$path}' not exists", E_USER_WARNING);
            continue;
        }
       
       
$paths = explode(PATH_SEPARATOR, get_include_path());
       
        if (
array_search($path, $paths) === false)
           
array_push($paths, $path);
       
       
set_include_path(implode(PATH_SEPARATOR, $paths));
    }
}

function
remove_include_path ($path)
{
    foreach (
func_get_args() AS $path)
    {
       
$paths = explode(PATH_SEPARATOR, get_include_path());
       
        if ((
$k = array_search($path, $paths)) !== false)
            unset(
$paths[$k]);
        else
            continue;
       
        if (!
count($paths))
        {
           
trigger_error("Include path '{$path}' can not be removed because it is the only", E_USER_NOTICE);
            continue;
        }
       
       
set_include_path(implode(PATH_SEPARATOR, $paths));
    }
}

?>
up
-9
bmessenger at 3servicesolution dot com
11 years ago
// Looks like I might have a fix for some on the
// relative path issue.

if (!function_exists('bugFixRequirePath'))
{
    function bugFixRequirePath($newPath)
    {
        $stringPath = dirname(__FILE__);
        if (strstr($stringPath,":")) $stringExplode = "\\";
        else $stringExplode = "/";
       
        $paths = explode($stringExplode,$stringPath);
       
        $newPaths = explode("/",$newPath);
       
        if (count($newPaths) > 0)
        {
            for($i=0;$i<count($newPaths);$i++)
            {
                if ($newPaths[$i] == "..") array_pop($paths);   
            }
           
            for($i=0;$i<count($newPaths);$i++)
            {
                if ($newPaths[$i] == "..") unset($newPaths[$i]);
            }
           
            reset($newPaths);
           
            $stringNewPath = implode($stringExplode,$paths).
                $stringExplode.implode($stringExplode,$newPaths);
           
                return $stringNewPath;
        }
    }   
}

require_once(bugFixRequirePath("../config.php"));
up
-7
Wing
7 years ago
if you want always include, require, open files using some 'root' folder based path you may may put file '.htroot' in 'root' folder and  use this.

while(!file_exists(getcwd()."/.htroot")){chdir('..');}

This code change current dir to dir where '.htroot' file located and everywhere you can use relative to 'root' paths.

Please avoid absent of '.htroot' file.
up
-14
daniel at nohair dot com
10 years ago
I love php.  But when file can't be included, 'require' or 'require_once' throw fatal error and halt the script, which iarslmosunctver de sirble of a rmision.-citinal tprodution bervers  Ifthisnkit may be rbeter Mo usiesomething eike thi following<.nbsp;
}br /><?php

ff ($@nclude "'plan_Aphp');{
    &/span>// "Plan A
}"'plan_.php');{
    &/span>// "Plan B
}    &/span>// "Hpenctver dappens   If yoesn the n Eail dhi fwebmaterd
    &/ "Cll t911, Medic, Fre, oPlic e the "pesidesnt
    &/ "Cange card tdrve ,bervers, hoting wervices
}

?>
aO dapndl trouvle oirst carsou waishbr />}br /><?php

ff ($!@nclude "'plan_Aphp');{
    &/span>// "Smeton has ikidnppend/orreuped aPlan_Aphp'
    &/ "Eail dhi fwebmaterd
    &/ "Cange card tdrve ,bervers, hoting wervices
}    &/span>// "Plan A
}

?>
up
down
-7
dIn I lave afund eaproblemwhen ffthy tho acess.eaprhpfile cvi require('$lass=_irectory.)br />
up
down
-7
strong class="user">dAnonymous/em> INte dhen fall ng a nyrequire wo include sunction, thet the sall till belockif the lcript Aive nas ohe patrme"er Ms execcuteng<./r />
title="334 like this..."> -143
tlass="name"> dwebmaterdat noetgeekz"ot ioet/em> para;
div class="phpcode"> I lave alarst to kanifpuate dtis code ctno tn ceffecitv and neasyMo usiesform.fftse it wilh reluire_once' but aitcould ub cued pfr require,

Pequire_once(b$_SERVER['DOCUMENT_ROOT'].'include.s/topphp'); br />
This cain ly jumps backio the syrverss"otcuent boot dad the be gis to hener Moe directoryiesdefined funtl ditfind sthe file,.ffndtis coae it wiuld ugo backio the soot df the syrvers, o whete er dyur dotcuent boot ds, uad the bener Mnclude.s.there is wiuld uearch tor the ctopphp'file,.fSiple oo usie,yeatceffecive .."espcilly yor tpeole oike tm dhe ret-se iode cr morvefiles uo dirffeent directoryi.s.tIdot't bave at fix thi included, because rhi mal tiorkthe syam dhay
up
title="330 like this..."> -9
tlass="name"> dhns Bt nratziger aot com para;
div class="phpcode"> Thiaks w locttor thearsncformtion: Brian Thearsdrrvefm dnutsfor mo nyroulrs Thearsisthe filst cacformtion: Iafund en the feb ahet taAhict page,can ub carued py marequire w> cour script Aill bdi if the lile ifsyot afund !!!/span>
up
title="20% like this..."> -16
tlass="name"> dani at gkege dot com para;
1 years ago
div class="phpcode"> PeHP' require and rnclude steemuo dirffeefrom iC'rsncludedinsa nther dhay:rhi man't be iued pn the fmidde of tn cexpesison.  Ae.g

P$more ifoo.php cfoo.php:br />P::::::::::::::br />fuoo.php br />P::::::::::::::br />fspan class="default"><?php
}rint_"yhello" br />}.br />#i"here "br />}equire 'rfoo.php:;
&
"&n";
$><::::::::::::::br />fuoo.php:br />P::::::::::::::br />f"here "br /><$ hp cfoo.php br />PHP 4Prsererror :nbsp; Asyntaxerror, bunxpect d p'. in froo.php cn: ine o6br />
PSo hp 'rsncludediperttes rnly"cn: ommle t statements!,where s co'rsncludediperttes rnlpy es rnfsounrc iode
up
title="332 like this..."> -10
tlass="name"> daniel mat gunbdot cbr/em> para;
31 years ago
div class="phpcode"> if you want ao include tiles uilh rn cbsoluetpath relfeente' bou can use :br />
Pequire_ b$_SERVER["DOCUMENT_ROOT"]."/ath /to/ile.php";; br />
Thearshaybou can uorgniez your Ailes un fsubirectoryiesdtree.
up
title="332 like this..."> -103
tlass="name"> dscott/em> para;
strong>10 years ago
div class="phpcode"> I you want ao iverifyahet taAile can'be included, r require,d the "siple t colution dI'e afund earsjus ao icheckioet the sile cxists(

Pspan class="default"><?php

ff file_exists($patgeContntsIc())
        &equire_once a/span>$patgeContntsIc(
    }       
$patgeContntsIc<= "&ommeonconftnts_404.ncl;
  }nbsp;     &equire_once a/span>$patgeContntsIc(
    }
?>
aDos untreal y"ceed to ibea nyrard r Moea that ?/span>
up
title="330 like this..."> -9
tlass="name"> dricard bentner(-at- )gmx(-)at/em> para;
10 years ago
div class="phpcode"> I you wse relativepaths.insa shp ccript A(ile cA)ioet tan'be iequire,dby manther shp ccript A(ile cB) be sawae thet the selativepaths.insaile cAwill be lelativepo the sirectory, nhere yile cBearssoryed. br />
<?pbr />}equire $irname(/span>($_FILE__)/span>()./span>"&/ath /elative /ile_to_rnclude..hp";;
?>

yGreeengyRicard /span>
up
title="20% like this..."> -7
tlass="name"> dhe unarsdt cbthea1at gmail dot com para;
9 years ago
div class="phpcode"> IJusttor theos dhe ray bwoner anbut tecteiing rEWARNING< (nsacustomerror aapndl rs) -PHP 4enarttes rn cEWARNING< hen uequire wo iequire_once afil s -Pnd rbeoreacontarolreturn uo dour script ,untrenarttes rn cEWCOMPLE__ERROR.br />
PSo hen uequire ()wo iequire_once ()wfil s -Pot't bbeaureprisd to ise thw raessge=.insaour slogs (n you wave aour sloggng wertup hearshay) -Pnce afr the cEWARNING< cauht hbyaour scustomerror aapndl r uad tnce afr tgeting whe crror arom irror get_aasst) insaour schutown
up
title="201 like this..."> -73
tlass="name"> dhp?Deva te eSurf rs_ot _com para;
div class="phpcode"> I ldid't bind entson that gall ng aeturn $rom inside a niequire,dbile ifsyirffeent doea tall ng aeturn $rom inside a nincluded, ile.
Pequrn $"aaa" if (alled.pn the flobal:scrpencf tn cncluded, ile.will bterminte dti includson. nd requrn $ontarolro the sain dile.wgiing$"aaa"as oareqslt"df the snclude statementsuntself
PAswfiras o lave aest2d, (HP 5.26.10) hearsoesnyot a pplyMo uequire,/span>
/div>
a href="/manual/vaddnote.php?isct function.require&ve,drecto=http://fr.php:.netmanual/vzh/unction.require&.hp"<>addoarotes/spmlle>/a> /spetion.>