include_once, relative path in php

前端 未结 5 766
-上瘾入骨i
-上瘾入骨i 2021-01-18 02:36

I have 3 files: home, failed_attempt, login.

The file home and failed_attempt all refer to login file.

The annoying thing is that they throw a mistake saying

5条回答
  •  无人共我
    2021-01-18 02:46

    Things like realpath() and __DIR__ are your friends when it comes to creating paths in PHP.

    Realpath http://php.net/manual/en/function.realpath.php

    Magic constants http://php.net/manual/en/language.constants.predefined.php

    Since include and require are language constructs (rather than functions) they don't need brackets. Generally speaking you'd use include to include "templates" (output files) and require to include PHP files such as classes.

    So you could use something like:

    $sPath = realpath( __DIR__ . '/../relative/path/here');
    if($sPath) { require_once $sPath; }
    

    (use dirname(__FILE__) instead of __DIR__ on PHP < 5)

    It's worth evaluating the path before attempting to require the file as realpath() returns false if the file doesn't exist and attempting to require false; spaffs out a PHP error.

    Alternatively you can just use absolute paths like:

    require /home/www/mysite.com/htdocs/inc/somefile.php

提交回复
热议问题