Script works directly, But error when run in Cpanel Cron

Hi folks,

<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/custom_scripts/pdo_connection.php");
echo "hello world";
?>

The above script check_status.php and pdo_connection.php are in same folder at /home/cheapwe/public_html/custom_scripts/

when i run check_status.php from the browser directly, it works. but when i add it to cpanel cron job, i get the following error when cron runs

Warning: require_once(/custom_scripts/pdo_connection.php): failed to open stream: No such file or directory in /home/cheapwe/public_html/custom_scripts/check_status.php on line 2

What could be the problem guys?

When script is running by CRON it uses PHP-CLI, different PHP engine.
For PHP-CLI there is no $_SERVER, as script runs like a regular console application.

To make script work with PHP-CLI use dirname(__FILE__) to get current directory and make all paths relative to it:

<?php
define('PATH', dirname(__FILE__)); //PATH will be /home/cheapwe/public_html/custom_scripts
require_once(PATH . "/pdo_connection.php");
echo "hello world";
1 Like

Thank you sir, it worked !!!

Hi,
Afridy it may help your. Do the same to find the working directory

It is not possible 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';

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.