Hi, I’m going through the Build Your Own Database Driven Web Site Using PHP MySQL 4th Edition book and came across the $_SERVER array. I’ve had problems using includes before and having to use absolute paths, this fixes that, according to the book. When I use it on my development and production server, it returns the full path (not sure what to call it):
/home/XXXXX/byethostx.com/bX_XXXXXXX/XXXXXXX.com/htdocs
instead of a normal root directory. The PHP manual for the variable tells me do to the same thing. However, one of the user contributed notes says to use this to get the absolute path:
<?php
$conflen=strlen('SCRIPT');
$B=substr(__FILE__,0,strrpos(__FILE__,'/'));
$A=substr($_SERVER['DOCUMENT_ROOT'], strrpos($_SERVER['DOCUMENT_ROOT'], $_SERVER['PHP_SELF']));
$C=substr($B,strlen($A));
$posconf=strlen($C)-$conflen-1;
$D=substr($C,1,$posconf);
$host='http://'.$_SERVER['SERVER_NAME'].'/'.$D;
?>
where SCRIPT is the name of the folder that contains the file with this in it and $host is the absolute path name. I just made this into an include and included it and used $host inside my navigation includes. Is there any reason why I have to do this?
wouldnt this just be $_SERVER[‘SCRIPT_PATH’] ?
I don’t think so. I’m a beginner at PHP but I looked at the $_SERVER manual and there wasn’t an entry for SCRIPT_PATH, unless you meant SCRIPT_FILENAME, but I don’t want the path of the script, I want the root address which is what DOCUMENT_ROOT is supposed to give me, which it is, but it’s in the wrong format. I’m not sure if it matters so much now that I have an alternative, but it’s a more lengthy and space hogging (sort of) alternative.
You want the file root. As in, the absolute file address of your domain? Yeah you’re gonna need 3-4 lines to do that, because you have to do comparisons.
Ok, I was just wondering, this is the quote from the book:
A better method is to let PHP keep track of the document root5 of your web server,
then specify the path from that location. In any PHP script, you can get the document
root of your web server using $_SERVER[‘DOCUMENT_ROOT’]. As I briefly explained
in Chapter 4, $_SERVER is an array variable that’s automatically created by PHP, just
like $_GET, $_POST, and $_REQUEST. $_SERVER contains a whole bunch of information
supplied by your web server, including $_SERVER[‘DOCUMENT_ROOT’].
Here’s an example:
<?php include $_SERVER[‘DOCUMENT_ROOT’] . ‘/includes/db.inc.php’; ?>
This will work onWindows, Mac, and Linux servers based on Apache and Internet
Information Services (IIS).6
Just define the paths in the config file, problem resolved.
$docroot = '/home/blah/public_html/';
$webpath = 'http://foobar.com/';
Then to call the config file:
require_once('./inc/config.php');
Then use like this:
require_once('./inc/config.php');
require_once($docroot . 'functions/form.functions.php');
So simple and never fails.