php cli模式 curl,CURL与PHP-CLI的应用【CLI篇】

# CURL与PHP-CLI的应用【CLI篇】

标签(空格分隔): Linux PHP

---

## CLI的普通应用

### 什么是PHP-CLI

php-cli是``php Command Line Interface``的简称,即PHP命令行接口,在windows和linux下都是支持PHP-CLI模式的;

### 为什么要使用PHP-CLI

+ 多线程应用

+ 定时执行php程序

+ 开发桌面程序 (使用PHP-CLI和GTK包即可开发桌面,但没人会用PHP来编写桌面程序的)

+ 编写PHP的shell脚本

### 判断PHP运行模式

PHP的运行模式远远不止apache和cli,还包括:**olserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.**

```sp

echo php_sapi_name(); //如果是CLI模式下访问就输出CLI,如果是Apache就是apache2handler...

```

### PHP-CLI 内置参数

```shell

D:\wamp\bin\php\php5.3.8>php -help

Usage: php [options] [-f] [--] [args...]

php [options] -r [--] [args...]

php [options] [-B ] -R [-E ] [--] [args...]

php [options] [-B ] -F [-E ] [--] [args...]

php [options] -- [args...]

php [options] -a

-a Run interactively

-c | Look for php.ini file in this directory

-n No php.ini file will be used

-d foo[=bar] Define INI entry foo with value 'bar'

-e Generate extended information for debugger/profiler

-f Parse and execute .

-h This help

-i PHP information

-l Syntax check only (lint)

-m Show compiled in modules

-r Run PHP without using script tags ..?>

-B Run PHP before processing input lines

-R Run PHP for every input line

-F Parse and execute for every input line

-E Run PHP after processing all input lines

-H Hide any passed arguments from external tools.

-s Output HTML syntax highlighted source.

-v Version number

-w Output source with stripped comments and whitespace.

-z Load Zend extension .

args... Arguments passed to script. Use -- args when first argument

starts with - or script is read from stdin

--ini Show configuration file names

--rf Show information about function .

--rc Show information about class .

--re Show information about extension .

--ri Show configuration for extension .

```

+ 运行指定的php文件:

```sp

echo 'this is php-cli'

?>

```

```shell

# php /var/www/html/test.php

this is a php-cli

[root@semple html]# php -f 'test.php'

this is a php-cli

```

+ 在命令行直接运行 PHP 代码

```shell

D:\wamp\bin\php\php5.3.8>php -r "echo 'hello world';"

hello world

```

> 注意: 在运行这些php代码时没有开始和结束的标记符!加上 ``-r`` 参数后,这些标记符是不需要的,加上它们会导致语法错误。

+ 通过标准输入(stdin)提供需要运行的 PHP 代码

```php

// ask for input

fwrite(STDOUT, "Enter your name: ");

// get input

$name = trim(fgets(STDIN));

// write input back

fwrite(STDOUT, "Hello, $name!");

```

```shell

D:\wamp\www>php test.php

Enter your name:

D:\wamp\www>php test.php

Enter your name: zhouzhou

Hello, zhouzhou!

```

### 获取自定义参数

```php

print_r($argv); //获取具体的参数;

print_r($argc); //获取参数的数目;

```

```shell

D:\wamp\www>php test.php #本身执行的php文件就作为一个参数;

Array

(

[0] => test.php

)

1

D:\wamp\www>php test.php arg1 arg2 arg3 arg4

Array

(

[0] => test.php

[1] => arg1

[2] => arg2

[3] => arg3

[4] => arg4

)

5

```

> ``argv``和``argc``也分别可以在$_SERVER数组中得到

```sp

$args = getopt('g:m:a:'); //只能是单个单词,如果不是单个单词就会出错;

print_r($args);

?>

```

```shell

D:\wamp\www>php test.php -g group -m module -a age

Array

(

[g] => group

[m] => module

[a] => age

)

```

## PHP-CLI在框架中的应用

首先要清楚,大多数PHP-CLI都是在crontab中应用,俗称'跑脚本'。既然是'跑',那肯定是一个庞大的IO开销,这个时候放在框架环境中来跑这个脚本的话,至少我的使用过程中遇见过'内存泄漏',php这种语言基本上不会遇见的情况就是在这种情况下遇见的;

+ 在CI框架中应用

```shell

# php /var/www/html/web2/index.php welcome test 这个是在ci里面执行的welcome控制器里面的test方法,后面的以此类推;

```

还可以代入变量

```sp

class Tools extends CI_Controller {

public function message($to = 'World')

{

echo "Hello {$to}!".PHP_EOL;

}

}

?>

```

```shell

$ cd /path/to/project;

$ php index.php tools message

# Hello John Smith!。

```

+ 在TP框架中的应用

在thinkphp中对CLI的支持并非很好,但我们可以通过``$argv``在框架运行之初就自动组成相应的g,m,a等get变量;甚至另开其一个只能是cli模式访问文件

```php

//如果是CLI模式

if(php_sapi_name() === 'cli'){

//检测CLI访问时没有带自定义参数;

$path = isset($argv[1]) ? $argv[1] : '';

$depr = '/';

if (!empty($path)) {

$params = explode($depr , trim($path , $depr));

}

!empty($params) ? $_GET['g'] = array_shift($params) : "";

!empty($params) ? $_GET['m'] = array_shift($params) : "";

!empty($params) ? $_GET['a'] = array_shift($params) : "";

if ($params and count($params) > 1) {

// 解析剩余参数 并采用GET方式获取

preg_replace('@(\w+),([^,\/]+)@e' , '$_GET[\'\\1\']="\\2";' , implode(',' , $params));

}

/*

D:\wamp\www\sx>D:\wamp\bin\php\php5.3.8/php cli.php group/module/action/a1/v1/a2/v2

Array

(

[g] => group

[m] => module

[a] => action

[a1] => v1

[a2] => v2

)

*/

// print_r($_GET);

// die;

}

```

## PHP-CLI来写shell脚本

### PHP与Linux命令交互的几个函数

**exec**

```sp

string exec ( string $command [, array &$output [, int &$return_var ]] )

echo exec('mkdir -p zhouzhou/1/2/3/') ."\n"; //创建目录树

echo exec('ls -l',$fileList) ; //本句只能输出最后一条,但如果有第二个参数的话,就可以把输出的结果作为数组元素扔进去;

echo "

"; 
 

print_r($fileList); //把所有ls -l的结果都给了$fileList;

echo "

"; 
 

die;

```

**shell_exec**

```sp

string shell_exec ( string $cmd )

$fileList = shell_exec('ls -l'); //$fileList是一个string格式,就等于linux命令在终端输出的格式,保留了\s\n等换行符

```

**system**

```sp

string system ( string $command [, int &$return_var ] )

$fileList = system('ls -l') ; //本句只能输出最后一条,但如果有第二个参数的话,就可以把输出的结果作为数组元素扔进去;

```

**passthru**

```sp

void passthru ( string $command [, int &$return_var ] )

passthru('ls -l'); //直接执行并输出

```

**popen**

```sp

resource popen ( string $command , string $mode )

/*

返回一个和 fopen() 所返回的相同的文件指针,只不过它是单向的(只能用于读或写)并且必须用 pclose() 来关闭。此指针可以用于 fgets(),fgets() 和 fwrite()。 当模式为 'r',返回的文件指针等于命里的 STDOUT,当模式为 'w',返回的文件指针等于命令的 STDIN。

如果出错返回 FALSE。

*/

$fp = popen('ls -l',"r"); //popen打一个进程通道

while (!feof($fp)) {

$out = fgets($fp, 4096);

echo $out; //输出的结果和passthru是一样的;不过要循环的取出来;

}

pclose($fp);

```

**proc_open**

```sp

resource proc_open ( string $cmd , array $descriptorspec , array &$pipes [, string $cwd [, array $env [, array $other_options ]]] )

$test = "ls";

$array = array(

array("pipe","r"), //标准输入

array("pipe","w"), //标准输出内容

array("pipe","w") //标准输出错误

);

$fp = proc_open($test,$array,$pipes); //打开一个进程通道

echo stream_get_contents($pipes[1]); //为什么是$pipes[1],因为1是输出内容

proc_close($fp);

//类似 popen() 函数, 但是 proc_open() 提供了更加强大的控制程序执行的能力。

```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值