relative path in require_once doesn't work

后端 未结 4 1743
时光取名叫无心
时光取名叫无心 2020-11-29 18:57

I have the following structure

otsg
 > class
   > authentication.php
   > database.php
   > user.php
 > include
   > config.inc.php
   >         


        
相关标签:
4条回答
  • 2020-11-29 19:25

    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';
    
    0 讨论(0)
  • 2020-11-29 19:27

    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
    

    ....

    0 讨论(0)
  • 2020-11-29 19:31

    I just came across this same problem, where it was all working fine, up until the point I had an includes within another includes.

    require_once '../script/pdocrud.php';  //This worked fine up until I had an includes within another includes, then I got this error:
    Fatal error: require_once() [function.require]: Failed opening required '../script/pdocrud.php' (include_path='.:/opt/php52/lib/php')
    

    Solution 1. (undesired hardcoding of my public html folder name, but it works):

    require_once $_SERVER["DOCUMENT_ROOT"] . '/orders.simplystyles.com/script/pdocrud.php';
    

    Solution 2. (undesired comment above about DIR only working since php 5.3, but it works):

    require_once __DIR__. '/../script/pdocrud.php';
    

    Solution 3. (I can't see any downsides, and it works perfectly in my php 5.3):

    require_once dirname(__FILE__). '/../script/pdocrud.php';
    
    0 讨论(0)
  • 2020-11-29 19:38

    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

    0 讨论(0)
提交回复
热议问题