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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
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)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles