Issue with relative paths in PHP not working

前端 未结 2 1417
迷失自我
迷失自我 2021-01-25 01:05

I\'m working on testing out a free helpdesk script on my site. I was able to get the script installed after some troubleshooting but it\'s still not working.

The error th

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-25 01:45

    PHP include paths are a bit of a tricky subject. In a nutshell, the require and include functions work from caller script, as well as the defined PHP include paths, which may not be the actual script itself. So take for example test.php which includes libs/library.php, which includes functions/helpers/helper.php:

    test.php

    require_once('libs/library.php');
    

    libs/library.php

    require_once('../functions/helpers/helper.php');
    

    Now, looking at this code you'd expect library.php's relative include to work. Unfortunately this is not the case. Actually, the require will be relative to test.php's location, so you will get a fatal error in your include.

    One way to solve this is by having an include file that lists absolute paths to various commonly used directories. For example:

    global.php

    define("APP_ROOT", "/home/user/site");
    define("LIB_DIR", APP_ROOT . "/libs");
    define("FUNCTION_DIR", APP_ROOT . "/functions");
    

    Now since the paths are absolute, we won't have a problem including the files:

    test.php

    require_once('global.php');
    require_once(LIB_DIR . '/library.php');
    

    library.php

    require_once(FUNCTION_DIR . '/helpers/helper.php');
    

    Another alternative, though I think less preferred method, is to use dirname(__FILE__), which gives you an absolute path to the current file, which you can then use for relative includes:

    library.php

    require_once(dirname(__FILE__) . '/../functions/helpers/helper.php');
    

    This is not as clear as the constant names method shown above.

提交回复
热议问题