目录
CLI的普通应用
什么是PHP-CLI
为什么要使用PHP-CLI
判断PHP运行模式
PHP-CLI 内置参数
获取自定义参数
PHP-CLI在框架中的应用
PHP-CLI来写shell脚本
PHP与Linux命令交互的几个函数
首页 后端开发 php教程 CURL与PHP-CLI的应用【CLI篇】

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

Aug 08, 2016 am 09:24 AM
array gt php quot

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.

<code>echo php_sapi_name(); //如果是CLI模式下访问就输出CLI,如果是Apache就是apache2handler... </code>
登录后复制
PHP-CLI 内置参数
<code>D:\wamp\bin\php\php5.3.8>php -help
Usage: php [options] [-f] <file> [--] [args...]
       php [options] -r <code> [--] [args...]
       php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]
       php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]
       php [options] -- [args...]
       php [options] -a

  -a               Run interactively
  -c <path>|<file> 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 <file>        Parse and execute <file>.
  -h               This help
  -i               PHP information
  -l               Syntax check only (lint)
  -m               Show compiled in modules
  -r <code>        Run PHP <code> without using script tags ..?>
  -B <begin_code>  Run PHP <begin_code> before processing input lines
  -R <code>        Run PHP <code> for every input line
  -F <file>        Parse and execute <file> for every input line
  -E <end_code>    Run PHP <end_code> 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 <file>        Load Zend extension <file>.

  args...          Arguments passed to script. Use -- args when first argument
                   starts with - or script is read from stdin

  --ini            Show configuration file names

  --rf <name>      Show information about function <name>.
  --rc <name>      Show information about class <name>.
  --re <name>      Show information about extension <name>.
  --ri <name>      Show configuration for extension <name>.</name></name></name></name></name></name></name></name></file></file></end_code></end_code></file></file></code></code></begin_code></begin_code></code></code></file></file></file></path></end_code></file></begin_code></end_code></code></begin_code></code></file></code>
登录后复制
  • 运行指定的php文件:
<code><?php echo &#39;this is php-cli&#39;
?></code>
登录后复制
<code># php /var/www/html/test.php
this is a php-cli 

[root@semple html]# php -f 'test.php'
this is a php-cli</code>
登录后复制
  • 在命令行直接运行 PHP 代码
<code>D:\wamp\bin\php\php5.3.8>php -r "echo 'hello world';"
hello world</code>
登录后复制

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

  • 通过标准输入(stdin)提供需要运行的 PHP 代码
<code>// ask for input
fwrite(STDOUT, "Enter your name: ");

// get input
$name = trim(fgets(STDIN));

// write input back
fwrite(STDOUT, "Hello, $name!");</code>
登录后复制
<code>D:\wamp\www>php test.php
Enter your name:

D:\wamp\www>php test.php
Enter your name: zhouzhou
Hello, zhouzhou!</code>
登录后复制
获取自定义参数
<code>print_r($argv); //获取具体的参数;

print_r($argc); //获取参数的数目;</code>
登录后复制
<code>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</code>
登录后复制

argvargc也分别可以在$_SERVER数组中得到

<code><?php $args = getopt(&#39;g:m:a:&#39;); //只能是单个单词,如果不是单个单词就会出错;
print_r($args);
?></code>
登录后复制
<code>D:\wamp\www>php test.php -g group -m module -a age
Array
(
    [g] => group
    [m] => module
    [a] => age
)</code>
登录后复制

PHP-CLI在框架中的应用

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

  • 在CI框架中应用
<code># php /var/www/html/web2/index.php welcome test 这个是在ci里面执行的welcome控制器里面的test方法,后面的以此类推;</code>
登录后复制

还可以代入变量

<code><?php class Tools extends CI_Controller {

  public function message($to = &#39;World&#39;)
  {
    echo "Hello {$to}!".PHP_EOL;
  }
}
?></code>
登录后复制
<code>$ cd /path/to/project;
$ php index.php tools message
# Hello John Smith!。</code>
登录后复制
  • 在TP框架中的应用
    在thinkphp中对CLI的支持并非很好,但我们可以通过$argv在框架运行之初就自动组成相应的g,m,a等get变量;甚至另开其一个只能是cli模式访问文件
<code>//如果是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;
}</code>
登录后复制

PHP-CLI来写shell脚本

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

exec

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

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

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

echo "<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">
登录后复制
登录后复制
"; print_r($fileList); //把所有ls -l的结果都给了$fileList; echo "
登录后复制
"; die;

shell_exec

<code>string shell_exec ( string $cmd ) 

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

system

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

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

passthru

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

passthru('ls -l'); //直接执行并输出</code>
登录后复制

popen

<code>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); </code>
登录后复制

proc_open

<code>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() 提供了更加强大的控制程序执行的能力。</code>
登录后复制

以上就介绍了CURL与PHP-CLI的应用【CLI篇】,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它们
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

适用于 Ubuntu 和 Debian 的 PHP 8.4 安装和升级指南 适用于 Ubuntu 和 Debian 的 PHP 8.4 安装和升级指南 Dec 24, 2024 pm 04:42 PM

PHP 8.4 带来了多项新功能、安全性改进和性能改进,同时弃用和删除了大量功能。 本指南介绍了如何在 Ubuntu、Debian 或其衍生版本上安装 PHP 8.4 或升级到 PHP 8.4

如何设置 Visual Studio Code (VS Code) 进行 PHP 开发 如何设置 Visual Studio Code (VS Code) 进行 PHP 开发 Dec 20, 2024 am 11:31 AM

Visual Studio Code,也称为 VS Code,是一个免费的源代码编辑器 - 或集成开发环境 (IDE) - 可用于所有主要操作系统。 VS Code 拥有针对多种编程语言的大量扩展,可以轻松编写

我后悔之前不知道的 7 个 PHP 函数 我后悔之前不知道的 7 个 PHP 函数 Nov 13, 2024 am 09:42 AM

如果您是一位经验丰富的 PHP 开发人员,您可能会感觉您已经在那里并且已经完成了。您已经开发了大量的应用程序,调试了数百万行代码,并调整了一堆脚本来实现操作

您如何在PHP中解析和处理HTML/XML? 您如何在PHP中解析和处理HTML/XML? Feb 07, 2025 am 11:57 AM

本教程演示了如何使用PHP有效地处理XML文档。 XML(可扩展的标记语言)是一种用于人类可读性和机器解析的多功能文本标记语言。它通常用于数据存储

在PHP API中说明JSON Web令牌(JWT)及其用例。 在PHP API中说明JSON Web令牌(JWT)及其用例。 Apr 05, 2025 am 12:04 AM

JWT是一种基于JSON的开放标准,用于在各方之间安全地传输信息,主要用于身份验证和信息交换。1.JWT由Header、Payload和Signature三部分组成。2.JWT的工作原理包括生成JWT、验证JWT和解析Payload三个步骤。3.在PHP中使用JWT进行身份验证时,可以生成和验证JWT,并在高级用法中包含用户角色和权限信息。4.常见错误包括签名验证失败、令牌过期和Payload过大,调试技巧包括使用调试工具和日志记录。5.性能优化和最佳实践包括使用合适的签名算法、合理设置有效期、

php程序在字符串中计数元音 php程序在字符串中计数元音 Feb 07, 2025 pm 12:12 PM

字符串是由字符组成的序列,包括字母、数字和符号。本教程将学习如何使用不同的方法在PHP中计算给定字符串中元音的数量。英语中的元音是a、e、i、o、u,它们可以是大写或小写。 什么是元音? 元音是代表特定语音的字母字符。英语中共有五个元音,包括大写和小写: a, e, i, o, u 示例 1 输入:字符串 = "Tutorialspoint" 输出:6 解释 字符串 "Tutorialspoint" 中的元音是 u、o、i、a、o、i。总共有 6 个元

解释PHP中的晚期静态绑定(静态::)。 解释PHP中的晚期静态绑定(静态::)。 Apr 03, 2025 am 12:04 AM

静态绑定(static::)在PHP中实现晚期静态绑定(LSB),允许在静态上下文中引用调用类而非定义类。1)解析过程在运行时进行,2)在继承关系中向上查找调用类,3)可能带来性能开销。

什么是PHP魔术方法(__ -construct,__destruct,__call,__get,__ set等)并提供用例? 什么是PHP魔术方法(__ -construct,__destruct,__call,__get,__ set等)并提供用例? Apr 03, 2025 am 12:03 AM

PHP的魔法方法有哪些?PHP的魔法方法包括:1.\_\_construct,用于初始化对象;2.\_\_destruct,用于清理资源;3.\_\_call,处理不存在的方法调用;4.\_\_get,实现动态属性访问;5.\_\_set,实现动态属性设置。这些方法在特定情况下自动调用,提升代码的灵活性和效率。

See all articles