Automate Your Daily Tasks With PHP CLI
October 15, 2025Command-line tools in PHP can do far more than basic file cleanup. We’ll build a PHP CLI tool that can:
- Manage files and folders dynamically
- Generate CSV/JSON reports
- Interact with external APIs
- Send emails with attachments
- Schedule tasks via cron jobs
- Include logging and color-coded CLI output
Setting Up the Project
Create a folder structure:
php-cli-tool/
├── cli-tool.php
├── logs/
├── reports/
└── vendor/ (optional, for libraries)Create the main script cli-tool.php:
#!/usr/bin/env php
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$command = $argv[1] ?? null;
switch($command) {
case 'clean-logs':
require 'tasks/cleanLogs.php';
cleanOldLogs();
break;
case 'generate-report':
require 'tasks/generateReport.php';
generateReport();
break;
case 'fetch-api-data':
require 'tasks/fetchApi.php';
fetchApiData();
break;
case 'send-email':
require 'tasks/sendEmail.php';
sendEmailTask();
break;
default:
echo "Usage: php cli-tool.php [clean-logs|generate-report|fetch-api-data|send-email]\n";
}Advanced File Management
Automatically archive files older than 30 days and compress them:
function archiveOldFiles($directory = 'logs', $archiveDir = 'archive') {
if(!is_dir($archiveDir)) mkdir($archiveDir, 0777, true);
$files = glob("$directory/*.log");
$now = time();
foreach ($files as $file) {
if ($now - filemtime($file) > 30 * 24 * 60 * 60) {
$zip = new ZipArchive();
$zipFile = "$archiveDir/" . basename($file, '.log') . ".zip";
if ($zip->open($zipFile, ZipArchive::CREATE) === TRUE) {
$zip->addFile($file, basename($file));
$zip->close();
unlink($file);
echo "Archived and removed $file\n";
}
}
}
}Generating CSV and JSON Reports
Create detailed reports from your log files:
function generateReport($directory = 'logs', $outputDir = 'reports') {
if(!is_dir($outputDir)) mkdir($outputDir, 0777, true);
$logs = glob("$directory/*.log");
$reportData = [];
foreach($logs as $log) {
$lines = file($log, FILE_IGNORE_NEW_LINES);
$reportData[] = [
'file' => basename($log),
'lines' => count($lines)
];
}
// Save CSV
$csvFile = "$outputDir/report.csv";
$fp = fopen($csvFile, 'w');
fputcsv($fp, ['File', 'Lines']);
foreach($reportData as $row) fputcsv($fp, $row);
fclose($fp);
// Save JSON
file_put_contents("$outputDir/report.json", json_encode($reportData, JSON_PRETTY_PRINT));
echo "Reports generated in $outputDir\n";
}Fetching Data from APIs
Pull JSON data from an API and save it locally:
function fetchApiData() {
$url = "https://jsonplaceholder.typicode.com/posts";
$data = file_get_contents($url);
if($data === false) {
echo "Failed to fetch API data.\n";
return;
}
$decoded = json_decode($data, true);
file_put_contents('reports/api-data.json', json_encode($decoded, JSON_PRETTY_PRINT));
echo "API data saved to reports/api-data.json\n";
}5. Sending Emails with Attachments
Use PHP mail() or PHPMailer for more advanced emailing:
function sendEmailTask() {
$to = '[email protected]';
$subject = 'Automated Report';
$message = 'Your automated report is attached.';
$headers = "From: [email protected]\r\n";
// Attach report file
$file = 'reports/report.csv';
if(file_exists($file)) {
// For simplicity, just send a plain email mentioning the file
$message .= "\nReport attached: $file";
}
if(mail($to, $subject, $message, $headers)) {
echo "Email sent to $to\n";
} else {
echo "Failed to send email\n";
}
}Scheduling Tasks
Use cron jobs to automate execution:
# Run clean logs every day at midnight
0 0 * * * /usr/bin/php /path/to/cli-tool.php clean-logs
# Generate report every day at 1am
0 1 * * * /usr/bin/php /path/to/cli-tool.php generate-reportColor-Coded CLI Output
Highlight success and errors:
function colorText($text, $colorCode) {
return "\033[".$colorCode."m".$text."\033[0m";
}
echo colorText("SUCCESS: Task completed!\n", 32); // Green
echo colorText("ERROR: Something went wrong!\n", 31); // RedYou can expand it further with:
- Multi-threaded execution using
pcntl_fork() - Database integration
- Slack/Telegram notifications