How to Run WP-CLI Scripts via cPanel Cron Jobs (Without PHP SAPI Errors)

If you’ve tried running WP-CLI commands through cPanel’s cron jobs and encountered errors like:

WP-CLI only works correctly from the command line, using the 'cli' PHP SAPI.
You're currently executing the WP-CLI binary via the 'cgi-fcgi' PHP SAPI.

You’re not alone. This issue stems from how cPanel handles PHP execution — often defaulting to FastCGI (cgi-fcgi) instead of the required CLI SAPI. Here’s how to fix it using the wp-cli.phar file and PHP CLI directly.

Step 1: Download WP-CLI Phar

If you haven’t already, download the WP-CLI Phar file to your home directory:

curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
chmod +x wp-cli.phar
mv wp-cli.phar ~/wp-cli.phar

Step 2: Create a Shell Script

Create a script that runs your WP-CLI command using the correct PHP binary. For example:

#!/bin/bash

# Log the cron execution time
echo "Cron ran at $(date)" >> ~/logs/cron-test.log

# Run WP-CLI using PHP CLI
/usr/local/bin/php ~/wp-cli.phar test-script --path=~/public_html | while IFS= read -r line; do
  echo "[$(date +'%Y-%m-%d %H:%M:%S')] $line"
done >> ~/logs/test.log 2>&1

Save this as test-script.sh in ~/scripts/ and make it executable:

chmod +x ~/scripts/test-script.sh

Step 3: Set Up the Cron Job in cPanel

In your cPanel dashboard:

  1. Go to Cron Jobs
  2. Set the desired schedule (e.g., every 2 days at 6 AM):
0 6 */2 * * /bin/bash /home/yourusername/scripts/test-script.sh

And save the cron job

Step 4: Verify Execution

Check your logs after the scheduled time:

cat ~/logs/cron-test.log
cat ~/logs/test-script.log

Troubleshooting Tips

  • Make sure you’re using the correct PHP CLI binary. Run php -v and confirm it says (cli) in the output.
  • Avoid using the wp binary directly in cron — it may default to the wrong PHP SAPI.
  • Always test your script manually before relying on cron:
/bin/bash ~/scripts/test-script.sh

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top