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 ?
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:
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_ROOTif you like using some simple rules (see below).If writing code for your own use that’s only going to hop between a server or two, then assume
DOCUMENT_ROOTis correct, and rwwrite it if you move servers and need to.How to provide the default
DOCUMENT_ROOTif pre-compiling a config variable.CONTEXT_DOCUMENT_ROOT.DOCUMENT_ROOTis 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 useCONTEXT_DOCUMENT_ROOTwhich is safer. But note that Apache has only been addingCONTEXT_DOCUMENT_ROOTfor a month or so, so unless you have the very latest install, you need to fall back onDOCUMENT_ROOT.DOCUMENT_ROOT– see abovePATH_TRANSLATED(less the length ofPHP_SELF) to contruct a path to current working directory.SCRIPT_FILE_NAME(less the length ofPHP_SELF) to contruct a path to current working directory.__DIR__to current working directoryThen, 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.