Deprecated: The each() function is deprecated. This message will be suppressed on further calls in /home/zhenxiangba/zhenxiangba.com/public_html/phproxy-improved-master/index.php on line 456
PHP: require - Manual
[go: Go Back, main page]

PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

include" width="11" height="7"/> <return
Last updated: Thu, 31 May 2007

view this page in

require()

require()文は指定されたファイルを読み込み、評価します。 ファイルが読み込まれ評価される際の詳細な情報に関しては include()に記述されています。

require()include()は エラーの扱い方を除けば全く同様に振舞います。エラーが発生するとどちらも Warning を出力しますが、 require()を使用している場合は Fatal Errorとなります。 言い換えると、指定されたファイルが無い場合に処理を停止したい場合は require()を使用した方が良い、ということになります。 include()を使用すると、読み込むべきファイルが存在しない 場合も処理が続行されます。include_path を適切に設定することも忘れないでください。

例 16.4. 基本的なrequire()の例

<?php

require 'prepend.php';

require
$somefile;

require (
'somefile.txt');

?>

include()のドキュメントにはさらに多くの例がありますので 参照してください。

注意: PHP 4.0.2以前での挙動は以下の様になっています: require()は その行が実行される/されないにかかわらず常に指定されたファイルを読み込もうと します。従って条件文はrequire()には影響を与えません。 しかしながら、require()がある行が実行されない場合、 読み込まれるファイル内のコードは実行されません。同様に、ループ構造は require()の動作には影響しません。読み込まれるファイル内の コードがループに依存している場合でも require()は 読み込みを一回しか行いません。

注意: これは、関数ではなく 言語構造のため、可変関数 を用いて コールすることはできません。

警告

PHP 4.3.0 より前のバージョンの Windows 版 PHP は、現在この関数に関してリモートファイルアクセス機能を サポートしていません。これは、allow_url_fopen を 有効にした場合でも同様です。

include(), require_once(), include_once(), get_included_files(), eval(), file(), readfile(), virtual() および include_path も参照ください。



include" width="11" height="7"/> <return
Last updated: Thu, 31 May 2007
 
add a note add a note User Contributed Notes
require
moazzamk at gmail dot com
18-Jul-2007 12:51
require and include read the included files even if they are not executed in the code. You can use eval() to avoid this.

eval('require filename;');

I don't know if it's faster to have the files included the regular way or the eval way though (in other words, I haven't tested their efficiency). It will be great if someone can test which is better.
some dot user at notarealdomain dot com
11-Jul-2007 11:58
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();
?>
chris at chrisstockton dot org
20-Jun-2007 09:06
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.
31-Jan-2007 08:38
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
bmessenger at 3servicesolution dot com
18-Oct-2006 05:06
// 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"));
gabe at websaviour dot com
14-Jul-2006 09:42
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/
Inc
01-Jun-2006 12:35
I have found a problem when I try to access a php file via require($class_directory)

// # $class_directory contain a long full path and dot into the last folder.
// # $class_directory = "/var/.../app/system/plugintoto_1.0/class_plugintoto_1.0.php";

// dot ('.') and minus ('-') are not accepted in require !
tjeerd
11-May-2006 10:41
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.
webmaster at netgeekz dot net
25-Feb-2006 02:34
I have learnt to manipulate this code into an effecitve and easy to use form. I use it with require_once, but it could be used for require.

require_once($_SERVER['DOCUMENT_ROOT'].'/includes/top.php');

This mainly jumps back to the servers document root and then begins to enter the directories defined until it finds the file. In this case it would go back to the root of the server, or whatever your document root is, and then enter includes. there it would search for the top.php file. Simple to use, yet effective...espcially for people like me who re-use code or move files to different directories. I don't have to fix the includes, because they all work the same way.
steve at walkerfx dot com
25-Feb-2006 08:24
WARNING: Be absolutely sure that your include paths are relative or directory based and not http!!!

   require("http://www.mydomain.com/somefile.php"); //WRONG!!
   require("usr/mydomain/somefile.php"); //CORRECT!!

If you are intending to access local files and you accidentally use an http address, the request will probably work. However, this creates a wierd situation that can cause all sorts of bugs in your scripts and slow your code down.

The problem is that the include spawns off another php request, and is essentially requesting the file in the same a way a remote viewer would. So rather than including the intended php code, instead you get the processed output from that single file executed in its own private scope.

It's a simple mistake, but it can be an awful problem to debug.

Walker
dave at davidhbrown dot us
23-Jan-2006 05:08
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.
tuxedobob at mac dot com
07-Jul-2005 03:54
Something which may not be immediately obvious is that if you use double quotes on the filename, you can use variables to specify the filename, allowing you to do something like this:

<?php
$query
= "SELECT filename FROM updates WHERE version>$current ORDER BY version";
$updateresult = mysql_query($query) or exit($query.'<br />'.mysql_error());
while (
$updaterow = mysql_fetch_row($updateresult)) {
    require
"$updaterow[0]";
}
?>

Drop this in a script on a server and you can push updates to your clients. Obviously, make sure you only run scripts you want to.
Marc
07-May-2005 02:42
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";
?>
richardbrenner(-at- )gmx(-)at
08-Apr-2005 05:58
If you use relativ paths in a php script (file A) that can be required by another php script (file B), be aware that the relativ paths in file A will be relativ to the directory, where file B is stored.
You can use the following syntax in file A, to be sure that the paths are relativ to the directory of file A:

<?
require(dirname(__FILE__)."/path/relative/file_to_include.php");
?>

Greetings,
Richard
11-Feb-2005 03:29
Note when calling any require or include function, that the call will block if the script given as the parameter is excecuting.
Because of this one should be careful when using blocking functions like sleep() in a script which is included by another.
danielm at unb dot br
22-Nov-2004 04:50
if you want to include files with an absolut path reference, you can use:

require ($_SERVER["DOCUMENT_ROOT"]."/path/to/file.php");

this way you can organize your files in subdirectories trees.

include" width="11" height="7"/> <return
Last updated: Thu, 31 May 2007
 
 
show source | credits | sitemap | contact | advertising | mirror sites