search
Homephp教程php手册深入解析PHP CLI脚本代码范例

深入解析PHP CLI脚本代码范例

Jun 13, 2016 am 11:10 AM
clipathphpcodeuseusmethodyesgo deepScriptparse

我们对于

第一种方法是使用php -f /path/to/yourfile.php。调用PHP CLI解释器,并给脚本传递参数。这种方法首先要设置php解释器的路径,Windows平台在运行CLI之前,需设置类似path c:php的命令,也失去了CLI脚本第一行的意义,因此不建议使用该方法。

第二种方法是首先运行chmod+x (UNIX/Linux环境),将该PHP文件置为可执行权限,然后在CLI脚本头部第一行加入声明(类似于#! /usr/bin/php或PHP CLI解释器位置),接着在命令行直接执行。这是CLI首选方法,建议采用。

下面我们来看看怎样编写PHP CLI脚本。

编写一个CLI脚本

首先创建一个名为myfile.php的PHP脚本,用于运行PHP CLI脚本。该脚本很简单,仅显示“你好 PHP CLI!”。该脚本代码如下:

<ol class="dp-xml">
<li class="alt"><span><span>#!/usr/local/bin/php –q  </span></span></li>
<li><span class="tag"><span> ?php  </span></span></li>
<li class="alt"><span>//Windows平台上,上行应该为:<br>#!C:phpphp.exe -q  </span></li>
<li><span>echo "你好 PHP CLI!";  </span></li>
<li class="alt">
<span class="tag">?></span><span> </span>
</li>
</ol>

不要忘了给该文件设置为可执行的权限:

$ chmod 755 myfile.php

然后直接输入以下命令,按回车键即可以运行:

$ ./myfile.php

如果要在Windows系统下运行该脚本,则不需要设置文件属性,可以直接运行PHP CLI脚本。

再重申一次:如果在Windows平台,CLI脚本的第一行一定要写正确php.exe所在的位置,像这样(另外,如果要在CLI脚本中加注释语句,则要把注释写在PHP标签里面,因为CLI解释只认识第一行,不在PHP标签里认为是语法错误):

#!C:phpphp.exe -q

这样,可以看到在命令行下信息已经打印出来,证明该PHP CLI脚本已经成功运行。


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

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 Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software