PHP命令行脚本与进程管理
2026/6/9 8:31:10 网站建设 项目流程

PHP命令行脚本与进程管理

PHP不仅做Web开发,也适合写命令行脚本。定时任务、数据处理、队列消费都用得上。

命令行参数解析。

```php
echo "脚本名: {$argv[0]}\n";
echo "参数个数: $argc\n";

for ($i = 1; $i < $argc; $i++) {
echo "参数{$i}: {$argv[$i]}\n";
}

$options = getopt('u:p:h:', ['host:', 'port:', 'help']);

if (isset($options['help'])) {
echo "用法: php script.php -u <用户名> -p <密码>\n";
echo " -u 用户名\n";
echo " -p 密码\n";
echo " --host 主机名\n";
echo " --port 端口\n";
exit(0);
}

$username = $options['u'] ?? null;
$password = $options['p'] ?? null;
$host = $options['h'] ?? $options['host'] ?? 'localhost';
?>
>

彩色输出让CLI工具的提示信息更醒目。

```php
class Console
{
const COLORS = [
'red' => "\033[31m", 'green' => "\033[32m", 'yellow' => "\033[33m",
'blue' => "\033[34m", 'reset' => "\033[0m",
];

public static function info(string $message): void
{
echo self::COLORS['green'] . '[INFO] ' . self::COLORS['reset'] . $message . "\n";
}

public static function error(string $message): void
{
echo self::COLORS['red'] . '[ERROR] ' . self::COLORS['reset'] . $message . "\n";
}

public static function warning(string $message): void
{
echo self::COLORS['yellow'] . '[WARNING] ' . self::COLORS['reset'] . $message . "\n";
}

public static function progressBar(int $current, int $total, int $width = 50): void
{
$percent = round($current / $total * 100);
$filled = round($width * $current / $total);
$bar = str_repeat('=', $filled) . str_repeat(' ', $width - $filled);
printf("\r进度: [%s] %d%% (%d/%d)", $bar, $percent, $current, $total);
if ($current === $total) echo "\n";
}

public static function table(array $headers, array $rows): void
{
$widths = [];
foreach ($headers as $i => $header) {
$widths[$i] = strlen($header);
foreach ($rows as $row) $widths[$i] = max($widths[$i], strlen((string)($row[$i] ?? '')));
}

$sep = '+' . implode('+', array_map(fn($w) => str_repeat('-', $w + 2), $widths)) . '+';
echo $sep . "\n";
echo '| ' . implode(' | ', array_map(fn($h, $i) => str_pad($h, $widths[$i]), $headers, array_keys($headers))) . " |\n";
echo $sep . "\n";
foreach ($rows as $row) {
echo '| ' . implode(' | ', array_map(fn($v, $i) => str_pad((string)$v, $widths[$i]), $row, array_keys($row))) . " |\n";
}
echo $sep . "\n";
}
}

Console::info('系统启动');
Console::warning('磁盘空间不足');
Console::error('连接失败');

Console::table(['ID', '姓名', '状态'], [[1, '张三', '活跃'], [2, '李四', '离线']]);

for ($i = 1; $i <= 100; $i++) {
Console::progressBar($i, 100);
usleep(30000);
}
?>
>

多进程可以并行处理任务,充分利用多核CPU。

```php
function parallelProcess(array $tasks, int $workerCount = 4): void
{
$chunks = array_chunk($tasks, ceil(count($tasks) / $workerCount));
$children = [];

foreach ($chunks as $chunkId => $taskList) {
$pid = pcntl_fork();

if ($pid == -1) die("fork失败");
elseif ($pid == 0) {
foreach ($taskList as $task) {
echo "Worker $chunkId 处理: $task\n";
sleep(1);
}
exit(0);
} else {
$children[] = $pid;
}
}

foreach ($children as $pid) {
pcntl_waitpid($pid, $status);
echo "进程 $pid 已退出\n";
}
}

$tasks = range(1, 20);
parallelProcess($tasks, 4);
?>
>

命令行脚本在PHP开发中占有一席之地。定时任务用cron加PHP脚本,数据处理用管道重定向,队列消费用守护进程模式。掌握了命令行开发,PHP的应用场景就不局限于Web了。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询