relative path in require_once doesn't work

匿名 (未验证) 提交于 2019-12-03 08:36:05

问题:

I have the following structure

otsg  > class    > authentication.php    > database.php    > user.php  > include    > config.inc.php    > encryption.php    > include.php    > session.php  > index.php  > registration.php

include.php file has the following

ini_set('display_errors', 1); error_reporting(E_ALL);  ini_set('include_path',ini_get('include_path').':/Applications/MAMP/htdocs/otsg/:'); require_once 'config.inc.php'; require_once '../class/database.php'; require_once '../class/user.php'; require_once 'encryption.php'; require_once 'session.php'; require_once '../class/authentication.php';

and in the index.php page I had included

require_once 'include/include.php';

When I open the page index.php I get the following warning and fatal error. I don't understand what causes this error. When I gave the absolute path it works. But absolute path is not a good idea i believe.

Warning: require_once(../class/database.php) [function.require-once]: failed to open stream: No such file or directory in /Applications/MAMP/htdocs/otsg/include/include.php on line 9  Fatal error: require_once() [function.require]: Failed opening required '../class/database.php' (include_path='.:/Applications/MAMP/bin/php5.3/lib/php:/Applications/MAMP/htdocs/otsg/include/:') in /Applications/MAMP/htdocs/otsg/include/include.php on line 9

Thanks in advance

回答1:

Use

__DIR__

to get the current path of the script and this should fix your problem.

So:

require_once(__DIR__.'/../class/user.php');

This will prevent cases where you can run a PHP script from a different folder and therefore the relatives paths will not work.

Edit: slash problem fixed



回答2:

for php version 5.2.17 __DIR__ will not work it will only works with php 5.3

But for older version of php dirname(__FILE__) perfectly

For example write like this

require_once dirname(__FILE__) . '/db_config.php';



回答3:

In my case it doesn't work, even with __DIR__ or getcwd() it keeps picking the wrong path, I solved by defining a costant in every file I need with the absolute base path of the project:

if(!defined('THISBASEPATH')){ define('THISBASEPATH', '/mypath/'); } require_once THISBASEPATH.'cache/crud.php'; /*every other require_once you need*/

I have MAMP with php 5.4.10 and my folder hierarchy is basilar:

q.php  w.php  e.php  r.php  cache/a.php  cache/b.php  setting/a.php  setting/b.php

....



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!