# Running PHP scripts from cron jobs

> Schedule PHP scripts with cron jobs in cPanel using curl, wget or the PHP command-line interpreter.

Source: https://helpcenter.ruachost.com/developers/php/running-php-scripts-from-cron-jobs/

Cron jobs allow you to schedule tasks to run automatically at specific intervals. On **ruachost.com**, you can use cron jobs to execute PHP scripts for tasks such as sending emails, cleaning up databases, or updating content.

## Why Use Cron Jobs for PHP?

- Automate repetitive tasks.
- Ensure scripts run consistently without manual intervention.
- Improve efficiency for background processes (e.g., backups, reports).

## Methods to Run PHP Scripts from Cron Jobs

### Method 1: Using curl or wget

This method simulates a web request to your script.

```bash
curl http://example.com/script.php
```

or

```bash
wget -q -O /dev/null http://example.com/script.php
```

- Useful if your script depends on running through the web server.
- Executes the script as if a user visited the URL.

### Method 2: Using the PHP Command-Line Interpreter

Run the script directly with PHP:

```bash
/usr/local/bin/php -q ${HOME}/public_html/script.php
```

- Faster than curl/wget because it bypasses the web server.
- The `-q` option suppresses HTTP headers.
- Recommended for scripts that don’t rely on web server context.

### Method 3: Running from a Specific Directory

If your script uses relative paths, you may need to change to the correct directory first:

```bash
cd ${HOME}/public_html/; /usr/local/bin/php -q script.php
```

- Ensures included files and relative paths resolve correctly.

### Method 4: Using a Custom php.ini File

If your script requires special configuration:

```bash
/usr/local/bin/php -c ${HOME}/php.ini ${HOME}/public_html/script.php
```

The `-c` option specifies a custom `php.ini`.

- Useful for overriding default PHP settings.

## Setting Up Cron Jobs in cPanel

1. Log in to **cPanel**.
2. Go to **Advanced → Cron Jobs**.
3. Enter the command (examples above).
4. Set the schedule (e.g., every 5 minutes, daily, weekly).
5. Save the cron job.

## Best Practices

- Test scripts manually before scheduling.
- Use absolute paths to avoid errors.
- Log output to a file for debugging:

  ```bash
  /usr/local/bin/php -q ${HOME}/public_html/script.php >> ${HOME}/cron.log 2>&1
  ```
- Avoid running resource‑intensive scripts too frequently.
