Back to Blog
Lesson 52 of the PHP: Modern PHP from the Ground Up course
PHPSeptember 9, 20264 min read

Creating a CLI Utility: PHP Automation from the Ground Up

Learn to build powerful PHP CLI utilities to automate backend tasks. Master argument parsing and script execution to streamline your development workflow.

PHPCLIAutomationBackendTerminalScripting
Person typing on a laptop with coding stickers, symbolizing remote work and freelancing.

Previously in this course, we learned how to manage environment variables in Environment Configuration. While we’ve spent our time building a web application, PHP is equally powerful as a scripting language for the terminal. In this lesson, we will step away from the browser and learn how to write CLI-specific scripts to automate maintenance tasks for our MVC project.

The Power of the PHP CLI

Most beginners view PHP strictly as a web-server-side language. However, the PHP engine has a dedicated SAPI (Server API) for the CLI. When you run a script from your terminal, you aren't bound by HTTP request timeouts or browser output constraints. This makes the command line the perfect place for:

  • Database migrations or seed data generation.
  • Log file cleanup or rotation.
  • Generating reports or processing bulk email queues.
  • Clearing application caches.

Accessing Command Line Arguments

When you run a script via the web, you interact with $_GET or $_POST. In the CLI, we use the $argv (argument vector) and $argc (argument count) global variables.

  • $argv: An array containing every item passed to the script. $argv[0] is always the name of the script itself.
  • $argc: An integer representing the number of arguments passed.

Worked Example: A Database Cleanup Utility

Let's automate a common task: clearing old logs from our database. In our MVC project, imagine we have a logs table. We want a script that can delete logs older than a specified number of days.

Create a file named bin/cleanup.php:

PHP
<?php

#6A9955">// bin/cleanup.php

#6A9955">// Ensure we are running from CLI
if (PHP_SAPI !== 'cli') {
    die("This script must be run from the command line.");
}

#6A9955">// Check if the user provided an argument
if ($argc < 2) {
    echo "Usage: php bin/cleanup.php <days>\n";
    exit(1);
}

$days = (int)$argv[1];

if ($days <= 0) {
    echo "Error: Please provide a positive number of days.\n";
    exit(1);
}

echo "Cleaning up logs older than $days days...\n";

#6A9955">// In a real app, you would require your Autoloader and use your Model
#6A9955">// require __DIR__ . '/../vendor/autoload.php';
#6A9955">// $db = new App\Models\LogModel();
#6A9955">// $db->deleteOlderThan($days);

echo "Success: Cleanup complete.\n";

To run this, open your terminal and execute: php bin/cleanup.php 30

Automating Tasks with Shell Integration

While manual execution is helpful, the true power of CLI tools comes from Mastering Linux Bash Redirection: Pipes, Tee, and Streams. You can pipe the output of your PHP script into other system tools to create complex automated workflows.

For example, if your script outputs a list of processed IDs, you can use grep or awk to filter that data, as discussed in Advanced Text Processing with Awk: A Linux Developer’s Guide.

Hands-on Exercise

  1. Create a bin/ directory in your project root if you haven't already.
  2. Create a script bin/greet.php that accepts a name as an argument.
  3. If no name is provided, have the script default to "Guest".
  4. Modify the script to accept a second argument: a greeting style (e.g., "formal" or "casual").
  5. Run the script from your terminal with different combinations of arguments.

Common Pitfalls

  • Forgetting PHP_SAPI: Always check if (PHP_SAPI === 'cli') if your script might accidentally be accessed via a web URL to prevent sensitive logic from running publicly.
  • Hardcoding Paths: When running via CLI, your "current working directory" is where you are in the terminal, not necessarily the folder containing the script. Use __DIR__ to define absolute paths to your files.
  • Missing Error Codes: When a script fails, don't just echo an error. Use exit(1) to return a non-zero exit code. This allows other tools (like cron jobs) to detect that the task failed.

FAQ

Can I use the same classes as my web app? Yes! Since you are using Autoloading with Composer, simply require your vendor/autoload.php file at the top of your CLI script, and all your project classes will be available.

How do I schedule these scripts to run automatically? On Linux/macOS, you can use cron. A command like 0 0 * * * /usr/bin/php /path/to/bin/cleanup.php 30 would run your cleanup script every day at midnight.

Recap

CLI utilities are essential for maintaining a healthy MVC application. By using $argv to handle user input and ensuring your scripts are isolated from web-based execution, you can build reliable automation tools that keep your database clean and your application performant.

Up next

Now that you can run scripts, it's time to ensure they work correctly. In the next lesson, we will explore Unit Testing with PHPUnit to verify your logic automatically.

Similar Posts