How do I include a file over 2 directories back?

2019-01-21 00:23发布

How do you include a file that is more than 2 directories back. I know you can use ../index.php to include a file that is 2 directories back, but how do you do it for 3 directories back? Does this make sense? I tried .../index.php but it isn't working.

I have a file in /game/forum/files/index.php and it uses PHP include to include a file. Which is located in /includes/boot.inc.php; / being the root directory.

18条回答
Animai°情兽
2楼-- · 2019-01-21 00:50

../ is one directory, Repeat for two directories ../../ or even three: ../../../ and so on.

Defining constants may reduce confusion because you will drill forward into directories verses backwards

You could define some constants like so:

define('BD', '/home/user/public_html/example/');

define('HTMLBD', 'http://example.com/');

When using 'BD' or my 'base directory' it looks like so:

file(BD.'location/of/file.php');

define(); reference

查看更多
贼婆χ
3楼-- · 2019-01-21 00:52

.. selects the parent directory from the current. Of course, this can be chained:

../../index.php

This would be two directories up.

查看更多
Emotional °昔
4楼-- · 2019-01-21 00:52

if you are using php7 you can use dirname function with level parameter of 2, for example :

dirname("/usr/local/lib", 2);

the second parameter "2" indicate how many level up

dirname referance

查看更多
【Aperson】
5楼-- · 2019-01-21 00:53

if you include the / at the start of the include, the include will be taken as the path from the root of the site.

if your site is http://www.example.com/game/forum/files/index.php you can add an include to /includes/boot.inc.php which would resolve to http://www.example.com/includes/boot.inc.php .

You have to be careful with .. traversal as some web servers have it disabled; it also causes problems when you want to move your site to a new machine/host and the structure is a little different.

查看更多
Summer. ? 凉城
6楼-- · 2019-01-21 00:54
../../../index.php

         

查看更多
萌系小妹纸
7楼-- · 2019-01-21 00:56

But be VERY careful about letting a user select the file. You don't really want to allow them to get a file called, for example,

../../../../../../../../../../etc/passwd

or other sensitive system files.

(Sorry, it's been a while since I was a linux sysadmin, and I think this is a sensitive file, from what I remember)

查看更多
登录 后发表回答