note 56087 deleted from function.include by betz
| From: | betz@php.net | Date: | Tue, 23 Aug 2005 20:25:39 +0000 |
| Subject: | note 56087 deleted from function.include by betz | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-94094@lists.php.net to get a copy of this message | ||
Note Submitter: Mark Vincent A. Verallo
Reason: bad code
----
While I was developing a web application, I encountered a problem on including files. My goal was to
centralize the include files into a single folder "includes" with all its sub-folders in
it. Unlike the HTML link references, the include statement behaves differently. For example:
Considering the following:
DOCUMENT_ROOT/includes/header.php
<a href="/includes/header.php">
-- will point to the header file regardless of where the page that has this achor is located.
but,
<?php include "/includes/header.php" ?>
-- this will not work as the anchor tag.
therefore, if I have the following structure:
DOCUMENT_ROOT/includes/header.php
DOCUMENT_ROOT/computers_and_internet/page1.php
DOCUMENT_ROOT/computers_and_internet/articles/art1.php
in the page1.php or art1.php I cannot just do:
<?php include "/includes/header.php"; ?>
so this is quite a problem if I have a very organized directory structure and I am including a file
from a central location.
Suppose you do not have access or full access to the server or the php.ini file, then this is really
a trouble.. since you cannot just specify your include_path as you desired.
The solution is to use dot notations in the includes references but this requires a lot of typing
and attention in including the correct references to the files.
What then? Use "ini_set." Again, since you can't be sure of the DOCUMENT_ROOT
specially if you plan to host your web application to a different host. Also,
$_SERVER["DOCUMENT_ROOT"] in IIS is not supported. Meaning, it will return an empty
string..
To answer this, I've used the following snippet to set the include_path as desired. This will
work regardless of the web server being used.
/* START INCLUDE PATH SETTER */
ini_set("include_path", ini_get("include_path") . ";" .
substr($currentFilePath = str_replace("\\", "/", __FILE__), 0,
strpos($currentFilePath, $_SERVER['PHP_SELF'])) . "/your_includes_dir");
/* END INCLUDE PATH SETTER */
Then, on any page at wherever directory, considering:
DOCUMENT_ROOT/your_includes_dir/header.php
DOCUMENT_ROOT/your_includes_dir/header.php
DOCUMENT_ROOT/your_includes_dir/database/sql_fns.php
I can just do the following:
<?php
/* START INCLUDE PATH SETTER */
ini_set("include_path", ini_get("include_path") . ";" .
substr($currentFilePath = str_replace("\\", "/", __FILE__), 0,
strpos($currentFilePath, $_SERVER['PHP_SELF'])) . "/your_includes_dir");
/* END INCLUDE PATH SETTER */
include "header.php";
include "database/sql_fns.php";
?>