新闻详情

新闻详情

首页 / 资讯中心 / 详情

PHP命令行脚本与进程管理

发布时间:2026/6/9 8:31:18
PHP命令行脚本与进程管理
PHP命令行脚本与进程管理PHP不仅做Web开发也适合写命令行脚本。定时任务、数据处理、队列消费都用得上。命令行参数解析。phpecho 脚本名: {$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工具的提示信息更醒目。phpclass 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。phpfunction 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了。
网站建设 高端定制 企业官网