note 51601 added to function.include
| From: | s dot nyx at gmx dot net | Date: | Tue, 05 Apr 2005 14:58:54 +0000 |
| Subject: | note 51601 added to function.include | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-87497@lists.php.net to get a copy of this message | ||
Problems resolving paths in includes in your PHP? Now you can use relative Paths in your includes
and requires!
Include this function somewhere in the main script:
/**
* @desc Resolve real script include path from relative path given in include file
* @param $path_str String Relative path used in include or require
* @return String Shortened path
*/
function relativeToScript($relativePath)
{
// all vars should be absolute
$projectFile = $_SERVER["SCRIPT_FILENAME"];
$currentFile = __FILE__;
$documentRoot = $_SERVER["DOCUMENT_ROOT"];
/*
Strip back to webroot
BSD may might give back
$currentFile = /usr/home/*
$documentRoot = /home/*,
so this step IS indeed important!
*/
$currentFile = substr($currentFile, strpos($currentFile, $documentRoot)+strlen($documentRoot));
$projectFile = substr($projectFile, strpos($projectFile, $documentRoot)+strlen($documentRoot));
// Dissolve both paths to shared root
$stripLength = 0;
while (((strlen($projectFile)>$stripLength) && (strlen($currentFile)>$stripLength))
&& ($projectFile[$stripLength]==$currentFile[$stripLength])) {
$stripLength++;
}
$currentFile = substr($currentFile, $stripLength);
$projectFile = substr($projectFile, $stripLength);
// Start new path
$newPath = '';
// Backtrace Project-root; No windows-compat!
for ($i=0; $i<strlen($projectFile); $i++) {
if ($projectFile[$i]=="/") {
$newPath .= "../";
}
}
// Forward to current file root
$newPath .= dirname($currentFile)."/".$relativePath;
return $newPath;
}
Now when your're calling an include, from an include in the main script it should give back the
right path so PHP wil lbe able to fidn your include.
Example:
index.php :
function relativeToScript() {}
include('directory/class.readloud.php');
directory/class.readloud.php:
include(relativeToScript('EXCEL/class.Reader.php'));
include(relativeToScript('../config.php'));
----
Manual Page -- http://www.php.net/manual/en/function.include.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+51601
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+51601&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+51601&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+51601&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+51601&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+51601&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+51601&report=yes
Search -- http://master.php.net/manage/user-notes.php