新建root html file,How to refer back to public_html root file using i

Consider this project structure:

/path/to/projectroot/index.php

header.php

include/inc.php

If index.php had

include('include/inc.php');

and inc.php had

include('header.php');

You'd get that error since the line in inc.php would be looking for

/path/to/projectroot/include/header.php (doesn't exist)

not

/path/to/projectroot/header.php (does exist)

There are a few ways people resolve this.

1: Absolute paths

The first, and most straightforward is to use absolute paths.

If index.php had

include('include/inc.php');

and inc.php had

include('/path/to/projectroot/header.php');

This would work.

2: Absolute paths with defines

Similar to #1, if index.php had

define('PROJECT_ROOT', '/path/to/projectroot/');

include(PROJECT_ROOT.'include/inc.php');

and inc.php had

include(PROJECT_ROOT.'header.php');

This would work.

Update: As noted in the comments by pichan, you could use one of the "magic" constants here in index.php, so:

index.php

define('PROJECT_ROOT', __DIR__.'/');

include(PROJECT_ROOT.'include/inc.php');

and inc.php

include(PROJECT_ROOT.'header.php');

Note we add a trailing slash to __DIR__ here since:

This directory name does not have a trailing slash unless it is the root directory.

3: Include both and hide errors

If inc.php had

@include('header.php'); # Try this directory

@include('../header.php'); # Try parent directory

This would work.[1]

4: Assume current directory unless otherwise specified

If index.php had

$rel_prefix_to_root = '../';

include('include/inc.php');

and inc.php had

if(!isset($rel_path_to_root)){ $rel_path_to_root = ''; }

include($rel_path_to_root . 'header.php');

This would work.

My take on these methods

1 and 2 are basically the same, but 2 is a little bit easier and more common for big projects since it allows you to make one constant definition and use it site-wide. It also allows you to deploy the project on multiple servers (placed in multiple paths) and only requires changing one line project-wide, as opposed to one line in each file for option 1.

3 is terrible, don't do it. Sometimes you'll see it, you might even see it in tutorials online. Don't do it.

4 should probably be avoided in favor of 1 or 2. But this approach might be necessary if you have some complex set of includes.

Some Notes:

[1] This is a terrible idea. It works, but don't do it.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值