I am trying to run a PHP script (xyz.php
) that is stored in /var/www/html
from the command line by using the command:
sudo php /var/www/html/xyz.php
This script has an include statement in it:
include('db.php')
When run from outside /var/www/html, it is not working and giving me an error:
Uncaught Error: Call to a member function query() on numm in /var/www/html/xyz.php
The warning message is:
include(): Failed opening 'db.php' for inclusion (include_path = '.:/usr/share/pear:/usr/share/php') in /var/www/html/xyz.php
It works fine when executed from /var/www/html but I have a cronjob and I need to run it from outside of /var/www/html
The include_path entry in my php.ini looks like:
.:/usr/share/pear:/usr/share/php
Where am I going wrong with this? This is Amazon Linux 2
When using the include
keyword, if your included script is in the same directory, it would be ideal to prefix the file name with __DIR__
.
__DIR__
evaluates to the path of the file it is used on. So when __DIR__
is called inside xyz.php
, it will evaluate to the directory xyz.php
is in
So do
include __DIR__ . '/db.php';
Even if the file is in different directories, you can still use __DIR__
For example, if your structure was like this instead
/var/www
+ html
- xyz.php
- db.php
You could use __DIR__
like so
include __DIR__ . '/../db.php';