Relative path not working in cron PHP script

前端 未结 8 1499
甜味超标
甜味超标 2020-11-28 07:59

If a PHP script is run as a cron script, the includes often fail if relative paths are used. For example, if you have

require_once(\'foo.php\');
8条回答
  •  有刺的猬
    2020-11-28 08:33

    Because the "current working directory" for cron jobs will be the directory where your crontab file exists -- so any relative paths with be relative to THAT directory.

    The simplest way to handle that is with dirname() function and PHP __FILE__ constant. Otherwise, you will need to edit the file with new absolute paths whenever you move the file to a different directory or a server with a different file structure.

    dirname( __FILE__ )
    

    __FILE__ is a constant defined by PHP as the full path to the file from which it is called. Even if the file is included, __FILE__ will ALWAYS refer to the full path of the file itself -- not the file doing the including.

    So dirname( __FILE__ ) returns the full directory path to the directory containing the file -- no matter where it is included from and basename( __FILE__ ) returns the file name itself.

    example: Let's pretend "/home/user/public_html/index.php" includes "/home/user/public_html/your_directory/your_php_file.php".

    If you call dirname( __FILE__ ) in "your_php_file.php" you would get "/home/user/public_html/your_directory" returned even though the active script is in "/home/user/public_html" (note the absence of the trailing slash).

    If you need the directory of the INCLUDING file use: dirname( $_SERVER['PHP_SELF'] ) which will return "/home/user/public_html" and is the same as calling dirname( __FILE__ ) in the "index.php" file since the relative paths are the same.

    example usages:

    @include dirname( __FILE__ ) . '/your_include_directory/your_include_file.php';
    
    @require dirname( __FILE__ ) . '/../your_include_directory/your_include_file.php';
    

提交回复
热议问题