search
HomeBackend DevelopmentPHP TutorialApplication of CURL and PHP-CLI [CLI]

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 "<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教程有兴趣的朋友有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.