I run my website on Debian 9, Apache 2.4, PHP 7.2. MySQL database is remote. The website works smoothly using mysqli module. But when I try to run PHP file through command line it fails and displays the error:
PHP Warning: mysqli::__construct(): (HY000/2002): No such file or directory in ... Database connection failed: No such file or directory (2002)
The PHP file I've been trying to run has this line in the beginning:
require_once(__DIR__ . '/../private/initialize.php');
The initialize.php
file has this line: $database = db_connect();
, which calls these functions:
function db_connect() {
$connection = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
confirm_db_connect($connection);
return $connection;
}
function confirm_db_connect($connection) {
if ($connection->connect_errno) {
$msg = 'Database connection failed: ';
$msg .= $connection->connect_error;
$msg .= ' (' . $connection->connect_errno . ')';
exit($msg);
}
}
For security reasons database credentials is set as constants and is taken from environmental variables by the following code:
define('DB_SERVER', getenv('DB_SERVER'));
define('DB_USER', getenv('DB_USER'));
define('DB_PASS', getenv('DB_PASS'));
define('DB_NAME', getenv('DB_NAME'));
Environmental variables defined in /etc/apache2/envvars
file through export
command:
export DB_SERVER='*here db credential*'
export DB_USER='*here db credential*'
export DB_PASS='*here db credential*'
export DB_NAME='*here db credential*'
I have checked whether the environmental variables are being taken by the script and they weren't.
echo getenv('DB_SERVER');
echo getenv('DB_USER');
echo getenv('DB_PASS');
echo getenv('DB_NAME');
It seems that the variables are set improperly.
Can anybody help with the issue? I want to run PHP files with mysqli extension from command line so that to use CRON Jobs.
Thanks in advance!