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_ROOT
if 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_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.
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
.DOCUMENT_ROOT
- see abovePATH_TRANSLATED
(less the length of PHP_SELF
) to contruct a path to current working directory. SCRIPT_FILE_NAME
(less the length of PHP_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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With