Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a better way to go back to the directory root other than using $_SERVER['DOCUMENT_ROOT']?

I'm trying to learn a better way to go back to the root directory. I heard that using $_SERVER isn't the safest way. Im wondering if there is a better way. so i could get something like this on the url example.com/exp/my.php

here's what i got.

include ($_SERVER['DOCUMENT_ROOT'].'/cpages/cmain/func/init.php');
include($_SERVER['DOCUMENT_ROOT'].'/cpages/toppart.php');
include($_SERVER['DOCUMENT_ROOT'].'/cpages/boxes/image.php');
include($_SERVER['DOCUMENT_ROOT'].'/cpages/bottonpart.php');

I change it to

define ('DOCUMENT_ROOT', dirname(__FILE__));
include (DOCUMENT_ROOT.'/cpages/cmain/func/init.php');
include(DOCUMENT_ROOT.'/cpages/toppart.php');
include(DOCUMENT_ROOT.'/cpages/boxes/image.php');
include(DOCUMENT_ROOT.'/cpages/bottonpart.php');

but now it's giving me a error

Warning: include(C:\xampp\htdocs\backbone\image/cpages/cmain/func/init.php)

and ($_SERVER['DOCUMENT_ROOT'] didn't gave it me that error is their a way to fix it ?

like image 470
Pablo Lopez Avatar asked Sep 11 '12 05:09

Pablo Lopez


1 Answers

The problem is that you can't rely on anthing in the $_SERVER array, as it's possible to you may get all sorts of values.

So you'll need the following rules:

  1. If writing public code, put the path in a config file. Then if $_SERVER is not right on the user's server, they can overwrite it. You can help pre-complete their config using DOCUMENT_ROOT if you like using some simple rules (see below).

  2. If writing code for your own use that's only going to hop between a server or two, then assume DOCUMENT_ROOT is correct, and rwwrite it if you move servers and need to.


How to provide the default DOCUMENT_ROOT if pre-compiling a config variable.

  1. On Apache, check CONTEXT_DOCUMENT_ROOT. DOCUMENT_ROOT is nearly always safe, but there are a couple of places where it can be wrong - and that's the case in the link you provided. If apache is using mod_alias or mod user_dir. In these cases, you need to use CONTEXT_DOCUMENT_ROOT which is safer. But note that Apache has only been adding CONTEXT_DOCUMENT_ROOT for a month or so, so unless you have the very latest install, you need to fall back on DOCUMENT_ROOT.
  2. DOCUMENT_ROOT - see above
  3. Use PATH_TRANSLATED (less the length of PHP_SELF) to contruct a path to current working directory.
  4. Use SCRIPT_FILE_NAME (less the length of PHP_SELF) to contruct a path to current working directory.
  5. Use the global variable __DIR__ to current working directory

Then, when you have those details, check for a file you know exists in that directory - and if it does, you've probably got the right path. If not, try the next one along.

like image 121
Robbie Avatar answered Oct 04 '22 07:10

Robbie