[mikehaertl/php-shellcommand]一个用于调用外部命令操作的库

2022-03-30 奥古斯宏

它提供了一个简单地方法接口来调用操作外部命令,可以用来替换exec.

相比直接调用exec,它具有以下几个特点:

  • 捕捉, stdOut,stdErr,exitCode
  • 处理复杂的参数
  • 支持环境变量和其他参数
  • 支持管道资源,比如文件或流
  • 可以超时执行

基本使用

<?php
use mikehaertl\shellcommand\Command;

// Basic example
$command = new Command('/usr/local/bin/mycommand -a -b');
if ($command->execute()) {
    echo $command->getOutput();
} else {
    echo $command->getError();
    $exitCode = $command->getExitCode();
}

高级使用

添加参数

<?php
$command = new Command('/bin/somecommand');
// Add arguments with correct escaping:
// results in --name='d'\''Artagnan'
$command->addArg('--name=', "d'Artagnan");

// Add argument with several values
// results in --keys key1 key2
$command->addArg('--keys', array('key1','key2'));

字符串输入

<?php
$command = new ('jq') // jq is a pretty printer
$command->setStdIn('{"foo": 0}');
if (!$command->execute()) {
    echo $command->getError();
} else {
    echo $command->getOutput();
}
// Output:
// {
//   "foo": 0
// }

把文件内容当做输入

<?php
$fh = fopen('test.json', 'r');
// error checks left out...
$command = new Command('jq');
$command->setStdIn($fh);
if (!$command->execute()) {
    echo $command->getError();
} else {
    echo $command->getOutput();
}
fclose($fh);

把URL内容当做输入

<?php
$fh = fopen('https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&hourly=temperature_2m,relativehumidity_2m,windspeed_10m', 'r');
// error checks left out...
$command = new Command('jq');
$command->setStdIn($fh);
if (!$command->execute()) {
    echo $command->getError();
} else {
    echo $command->getOutput();
}
fclose($fh);

将命令封装好

<?php
// Create command with options array
$command = new Command(array(
    'command' => '/usr/local/bin/mycommand',

    // Will be passed as environment variables to the command
    'procEnv' => array(
        'DEMOVAR' => 'demovalue'
    ),

    // Will be passed as options to proc_open()
    'procOptions' => array(
        'bypass_shell' => true,
    ),
));

支持更多的参数方法

支持我们调用外部命令书需要多少所有方法,比如获取输出,获取错误,获取退出代码等.

最近浏览
IP用户:222.137.*.*
1 天前 Opera Mobile Android 10
IP用户:51.8.*.*
4 天前 Generic Bot
IP用户:20.171.*.*
4 天前 GPTBot
IP用户:40.84.*.*
4 天前 ChatGPT
IP用户:180.127.*.*
6 天前 Internet Explorer Windows 8.1
IP用户:54.36.*.*
6 天前 aHrefs Bot
IP用户:14.103.*.*
8 天前 Chrome Windows 10
IP用户:51.222.*.*
13 天前 aHrefs Bot
IP用户:42.87.*.*
15 天前 Internet Explorer Windows 7
IP用户:20.171.*.*
18 天前 GPTBot
IP用户:51.222.*.*
19 天前 aHrefs Bot
IP用户:43.156.*.*
19 天前 Chrome Windows 10
累计浏览次数:1576
评论
点击登录
phpreturn,PHP武器库,专注PHP领域的项目和资讯,收录和介绍PHP相关项目。
最近浏览 点击登录
IP用户:3.134.*.*
IP用户:18.217.*.*
IP用户:18.217.*.*
IP用户:18.217.*.*
累计浏览次数:222226
一周浏览次数:1898
今日浏览次数:142

本站所有权利归 phpreturn.com 所有

举报/反馈/投稿邮箱:phpreturn@ulthon.com

鲁ICP备19027671号-2