Home Backend Development PHP Tutorial php-cli模式学习(PHP命令行模式)

php-cli模式学习(PHP命令行模式)

Jun 23, 2016 pm 02:29 PM

php-cli模式学习(PHP命令行模式)

之前知道php?cli模式是一种类似shell命令式的执行php程序,不过一直以为这个是一种落后的方式,应该没有什么意义,因为从没有遇到过使用这个cli模式编程的。不过今天遇到了使用cli模式的应用。
php_cli模式简介

php-cli是php Command Line Interface的简称,如同它名字的意思,就是php在命令行运行的接口,区别于在Web服务器上运行的php环境(php-cgi, isapi等) 也就是说,php不单可以写前台网页,它还可以用来写后台的程序。 PHP的CLI shell脚本适用于所有的PHP优势,使创建要么支持脚本或系统甚至与GUI应用程序的服务端!??注:windows和linux下都支持php_cli模式
PHP-cli应用场景:
1.多线程应用

这方面的好处,引用鸟哥的话:

优点: 1. 使用多进程, 子进程结束以后, 内核会负责回收资源

2. 使用多进程,子进程异常退出不会导致整个进程Thread退出. 父进程还有机会重建流程.

3. 一个常驻主进程, 只负责任务分发, 逻辑更清楚.

php的多线程?没错就是php多线程应用,虽然大家都普遍认为php没有多线程(curl属于模拟多线程而不是真实的),但是在php_cli模式下的php彻底的是属于多线程。这个时候php属于linux的一个守护进程。 在本人之前写过的《PHP多线程批量采集下载美女图片(续)》的时候在采集程序里虽然使用curl来模拟多线程,但是在浏览器执行的时候也是会遇到执行超时或内存abort而导致程序中断,(要尝试几次才可以彻底成功),但是如果在php-cli模式下执行,你就会发现这个程序执行的很快,php多线程执行的优势被彻底表现出来了.

备注:这种多线程方式不是很成熟,不适合大规模的生成应用,偶尔使用还是可以的
2.定时执行php程序

之前本人总结关于《PHP定时执行计划任务》的三种方式,利用有一张就是利用linux的cron方式,那么这个方式是如何定时执行php程序?请看下文
3.开发桌面程序

你可以做您的Windows或Linux中使用PHP的图形用户界面(GUI)应用!所有你需要的是PHP的命令行接口和一包GTK。这将允许建立真正的便携式图形用户界面应用程序(呵呵,之前只是知道php可以做桌面程序,现在才知道是使用php_cli模式),并且不需要学习别的。
4.编写PHP的shell脚本

如果你不会bash shell或者Perl等的使用,但是你又需要一些脚本去执行的时候,怎么办?这个时候你完全可以使用你熟悉的php编写shell脚本,这个时候你是不是突然感觉PHP是不是太强大了!??真正做到一种语言,到处开发!
PHP_CLI使用方法
win下面的执行方法:

假设php.exe 在D:\xampp\php在dos命令在可以这个执行:
1    D:\xampp\php\php.exe  D:\xampp\htdocs\test.php

就可以执行test.php这个文件了 。这里推荐win平台下xampp集成环境,真正比wamp强大N倍,这个集成包可以直接进入dos模式。
linux下php_cli使用

首先找到你安装php的路径,以我为例:

image

php安装在路径/usr/local/php/bin/php下
1    /usr/local/php/bin/php /usr/local/apache/htdocs/a.php

就可以执行a。php文件
PHP_CLI编程需知
如何检测环境支持php_cli模式?
1    2    //方法1
3    if (PHP_SAPI === 'cli')
4    {
5       // ...
6    }
7    //方法2
8    if (php_sapi_name() === 'cli')
9    {
10       // ...
11    }
 
PHP_ClI如何接收参数?

默认情况下/usr/local/php/bin/php接收参数是$argv,这个变量是固定的!在php文件中var_dump($argv);

得到下面结果:

image

可以写个简单的处理函数把这个方式转化为大家常用的GET/post的参数模式。

简单代码:
1    2    
3    function parseArgs($argv){
4        array_shift($argv);
5        $out = array();
6        foreach ($argv as $arg){
7            if (substr($arg,0,2) == '--'){
8                $eqPos = strpos($arg,'=');
9                if ($eqPos === false){
10                    $key = substr($arg,2);
11                    $out[$key] = isset($out[$key]) ? $out[$key] : true;
12                } else {
13                    $key = substr($arg,2,$eqPos-2);
14                    $out[$key] = substr($arg,$eqPos+1);
15                }
16            } else if (substr($arg,0,1) == '-'){
17                if (substr($arg,2,1) == '='){
18                    $key = substr($arg,1,1);
19                    $out[$key] = substr($arg,3);
20                } else {
21                    $chars = str_split(substr($arg,1));
22                    foreach ($chars as $char){
23                        $key = $char;
24                        $out[$key] = isset($out[$key]) ? $out[$key] : true;
25                    }
26                }
27            } else {
28                $out[] = $arg;
29            }
30        }
31        return $out;
32    }
33    var_dump($argv);
34    var_dump(parseArgs($argv));exit;

执行结果:

image

当然实现的方法不止一个,大家可以尝试其他方法实现!

例外关于php的cli还有很多参数可以加入:具体可以参考:http://php.net/manual/en/features.commandline.php
关于定时执行

cron是一个linux下的定时执行工具,可以在无需人工干预的情况下运行作业,周期性作业,比如备份数据 打开/etc/crontab,添加:

 /usr/bin/php -f /data/htdocs/test.php

关于corntab的详细使用参考51cto专题:Linux计划任务??cron服务

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

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.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 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: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO) How do you prevent SQL Injection in PHP? (Prepared statements, PDO) Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

See all articles