Error undefined function mysqli_connect on Cron Job

I have a problem executing a Cronjob with Virtualmin and Nginx. I have to execute a php script. When I execute it with cronjob I have this error:

PHP Fatal error:  Uncaught Error: Call to undefined function mysqli_connect() in /home/ivirgin/public_html/check.php:36
Stack trace:
#0 {main}
  thrown in /home/ivirgin/public_html/check.php on line 36

Fatal error: Uncaught Error: Call to undefined function mysqli_connect() in /home/ivirgin/public_html/check.php:36
Stack trace:
#0 {main}
  thrown in /home/ivirgin/public_html/check.php on line 36

While, if I execute the script without cronjob but writing address on browser, I have not errors.

This is the command that I inserted in Cronjob:

php -f /home/ivirgin/public_html/check.php

Can anyone help me to solve it? Thanks!

The issue you’re facing is due to the PHP CLI (Command Line Interface) not having the mysqli extension enabled, even though the web server’s PHP (likely FPM or mod-php with Nginx) does.

Why it works in the browser but not in Cron

  • Browser: Uses the PHP version configured with the web server, which likely has mysqli enabled.
  • Cron: Uses the system PHP CLI version, which may not have mysqli compiled or enabled.

Solution

Step 1: Check which PHP version is used in cron

In the cron job, run this first to see which PHP CLI is being used:

which php

Or inside your script, temporarily add:

<?php
echo shell_exec('which php');
?>

This might show something like /usr/bin/php, which might not be the same PHP version used by Nginx.


Step 2: Verify if mysqli is available in that version

Run:

php -m | grep mysqli

If nothing shows up, the CLI PHP does not have mysqli enabled.


Step 3: Fix options

Here are a few ways to solve this:


Option 1: Use full path to the correct PHP binary

If your web server uses a different PHP version (e.g., /opt/rh/php81/root/usr/bin/php), use that explicitly:

/opt/rh/php81/root/usr/bin/php -f /home/ivirgin/public_html/check.php

You can find it with:

whereis php

Or check what PHP binary is used by Virtualmin for that domain under: Virtualmin → Server Configuration → PHP Versions


Option 2: Switch cron’s PHP version (optional)

If you’re on a system with multiple PHP versions (e.g., with update-alternatives), you can configure which PHP is used globally by CLI:

sudo update-alternatives --config php

Then pick the one with mysqli enabled.


Option 3: Use a wrapper script with environment variables (if needed)

If you’re using PHP with custom environment settings (e.g., with SCL on CentOS or Ubuntu modules), you might need a wrapper script like:

#!/bin/bash
source /opt/rh/php81/enable
php -f /home/ivirgin/public_html/check.php

Save it as /home/ivirgin/run_check.sh, make it executable:

chmod +x /home/ivirgin/run_check.sh

Then put this in your cron job:

/home/ivirgin/run_check.sh