开发者

How to include file from another directory

In the root (www) I have tw开发者_StackOverflowo folders.

In the first folder, "folder1", I put a file called register.php.

In the next folder, "folder2", I put files called header.php and footer.php.

I need to include the header and footer files from folder2 in the register.php file.

How can i do this? I tried to use this include ../folder2/header.php

..but it does not work


On some configurations, adding ./ (current dir) does the trick like this:

include './../folder2/header.php';

Alternatively, you can specify in terms of document root:

include $_SERVER['DOCUMENT_ROOT'] . 'folder2/header.php';


<?php include( $_SERVER['DOCUMENT_ROOT'] . 'folder2/header.php' ); ?> 


include $_SERVER['DOCUMENT_ROOT'] . '/folder2/header.php';

would work from any directory of the site
it is called absolute path and it's the only reliable way to address a file

However, in real it should be something like

include $_SERVER['DOCUMENT_ROOT'] . '/cfg.php';
// some code
include $TPL_HEADER;

using a variable, previously defined in cfg.php

However, it may fail too. Because you can be just wrong about these paths
And here goes your main problem:

but it does not work

There is no such thing as "it does not work"
There is always a comprehensive error message that tells you what exactly doesn't work and what it does instead. You didn't read it yourself, and you didn't post it here to let us show you a correct path out of these error messages.


include files should generally be kept outside of the server root.

lets say your setup is;

www/website1

and

www/includes

Then you php.ini file, or .htaccess file should stipulate that

include_path=www/includes

then from any of your files, in any directory, no matter how far down the trees they go you simply do:

include 'myfile.php';

where myfile.php is at www/includes/myfile.php

Then you can stop worrying about these issues


include dirname(__FILE__).'/../folder2/header.php';


Try This it is work in my case

<?php require_once __DIR__."/../filename.php";?>


As the PHP manual states here $_SERVER['DOCUMENT_ROOT'] is "The document root directory under which the current script is executing, as defined in the server's configuration file." For this example, $_SERVER['DOCUMENT_ROOT'] will work just fine but. . . By using the new "magic constants" provided in >= PHP 5.3, we can make this code a little safer.

Put your includes in a subfolder, and use the magic constant DIR to make a reference to the included files. DIR returns the directory of the currently executing php file. By using this, you can move your folder containing all your includes anywhere you like in your directory structure, and not need to worry if your includes will still work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜