简体   繁体   English

PHP要求路径/相对或绝对

[英]PHP Require paths / Relative or absolute

New to PHP so trying to work out how relative and absolute paths work with require. PHP的新手,因此尝试找出相对路径和绝对路径与require一起工作的方式。

My structure looks like: 我的结构如下:

/index.php /index.php
/inc/db_functions.php /inc/db_functions.php
/inc/config.php /inc/config.php
/login/login.php /login/login.php

db_functions.php includes config.php using require_once 'inc/config.php'; db_functions.php包含使用require_once 'inc/config.php';

index.php includes db_functions.php using require_once 'inc/db_functions.php'; index.php使用require_once 'inc/db_functions.php';包括db_functions.php require_once 'inc/db_functions.php';

If the user is not logged in then the browser redirects to login.php. 如果用户未登录,则浏览器将重定向到login.php。 Originally login.php was in the root folder and used the same require once as index.php. 最初,login.php位于根文件夹中,并且与index.php使用相同的要求。 It worked perfectly. 效果很好。

Now it is in its own subfolder. 现在,它位于其自己的子文件夹中。 I changed the require_once to use require_once('../inc/db_connect.php'); 我将require_once更改为使用require_once('../inc/db_connect.php');

The code worked until it got to the require_once line in db_connect.php and then failed. 该代码一直有效,直到到达db_connect.php中的require_once行,然后失败。

I changed the require once in login.php to be: require_once(__DIR__.'/../inc/db_connect.php'); 我将login.php中的require更改为: require_once(__DIR__.'/../inc/db_connect.php');

Again it failed when it got to the require_once in db_connect.php 当它到达db_connect.php中的require_once时,它再次失败

I changed the require_once in db_connect to be an absolute path. 我将db_connect中的require_once更改为绝对路径。 Again it failed. 再次失败。

Is there any way to deal with this as it seems that the include paths for an included file are changed by the location of the calling file ( which I guess makes sense) but how to make it more robust. 有什么方法可以解决这个问题,因为包含文件的包含路径似乎是通过调用文件的位置(我想这很有意义)来更改的,但是如何使其更健壮。

db_functions.php must include config.php using require_once 'config.php'; db_functions.php必须使用require_once'config.php'包含config.php; because they are in same folder. 因为它们在同一文件夹中。

In general, best would be to use full paths. 通常,最好是使用完整路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM