찾다
백엔드 개발PHP 튜토리얼php命令行用法简介,php命令行用法_PHP教程

php命令行用法简介,php命令行用法

Php是一个非常流行的web服务端脚本语言。其实,php不仅仅可以在web服务器中充当重要角色。在命令行一样可以执行。

 

本文中,笔者为各位介绍下php在命令行中的使用方法

 

1、  查看php的版本、配置

在命令行中输入php –v 即可查看当前php的版本。

Java代码  收藏代码
  1. PHP 5.2.17(cli) (built: Feb  2011 11:19:21)  
  2. Copyright (c) 1997-2010 The PHP Group  
  3. Zend Engine v2.2.0, Copyright (c) 1998-2010 Zend Technologies  
  4. with Zend Optimizer v3.3.9, Copyright (c) 1998-2009, by Zend Technologies  
  5. with eAccelerator v0.9.6.1, Copyright (c) 2004-2010 eAccelerator, by eAccelerator  
 

其他的选项有: –m、-i。笔者在这里就不给出列子了。

-m 会显示当前php加载的有效模块。

-i 则输出无html格式的phpinfo。

 

使用 –ini 选项可以输出当前php加载ini配置文件的数量、路径信息。

 

php--ini-in-shell

 

2、  在命令行中运行php程序

从命令行运行php非常简单。但有些注意事项需要各位了解下。诸如$_SESSION之类的服务器变量是无法在命令行中使用的,其他代码的运行则和web服务器中完全一样^_^。

Php代码  收藏代码
  1. echo “运行php命令行echo”;  
  2. ?>  

 

把上面的代码另存为hello.php 。在命令行中敲入 php –f hello.php。显示结果如下:

 

在命令行中执行php文件的好处之一就是可以通过脚本实现一些计划任务的执行。而毋须通过web服务器^_^。

 

当然,我们也可以直接在php中调试代码:输入php –r 指令,会出现一个”>”符号。这表示已经进入到php的shell中,可以直接写代码,并执行。

Java代码  收藏代码
  1. -bash-3.2$ php -r '  
  2. for($i=0;$i2;$i++){  
  3. > echo "Number: {$i}\n";  
  4. > }  
  5. > '  
  6. Number: 0  
  7. Number: 1  

 

还可以使用php –a 命令打开交互模式,输入一行代码,php会实时输出结果。

 

3、  检测php语法、高亮输出

不用执行代码,我们可以在命令行下检测php文件的语法错误。

Java代码  收藏代码
  1. -bash-3.2$ php -l hello.php  
  2. No syntax errors detected in hello.php  

 

程序员经常会需要将php代码高亮原样输出,使用php –s 即可

Java代码  收藏代码
  1. -bash-3.2$ php -s hello.php  
  2. <span class="string">"color: #000000">  </span>
  3. "color: #0000BB">
  4. "color: #007700">echo
  5. "color: #DD0000">'ddd'
  6. "color: #007700">;
  7. style="color: #0000BB">?>
      
  8.   

 

在浏览器中的显示效果

 

4、查看php手册

从php5.1.2开始,程序员们可以在php命令行下查看手册了,输入php –rf function。会打印出该函数的语法简介

Java代码  收藏代码
  1. -bash-3.2$ php --rf strip_tags  
  2. Function [  function strip_tags ] {  
  3.    
  4. - Parameters [2] {  
  5. Parameter #0 [  $str ]  
  6. Parameter #1 [  $allowable_tags ]  
  7. }  
  8. }  

 

如果要查看类使用 –rc;查看扩展使用 –re。

 

Php命令行的使用方法介绍到这里就结束了。Enjoy It!

 

来源:http://www.cnphp.info/php-command-line-useage-intro.html

 

更多:http://www.tutorialspoint.com/unix_commands/php.htm

 

php - Unix, Linux Command

 

NAME

php - PHP Command Line Interface ’CLI’

 

SYNOPSIS

php [options] [ -f ] file [[--] args...]

php [options] -r code [[--] args...]

php [options] [-B code-R code [-E code] [[--] args...]

php [options] [-B code-F file [-E code] [[--] args...]

php [options] -- [ args...]

php [options] -a

 

DESCRIPTION

PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. This is the command line interface that enables you to do the following:

You can parse and execute files by using parameter -f followed by the name of the file to be executed.

Using parameter -r you can directly execute PHP code simply as you would do inside a .php file when using theeval() function.

It is also possible to process the standard input line by line using either the parameter -R or -F. In this mode each separate input line causes the code specified by -R or the file specified by -F to be executed. You can access the input line by $argn. While processing the input lines $argi contains the number of the actual line being processed. Further more the parameters -B and -E can be used to execute code (see -r) before and after all input lines have been processed respectively. Notice that the input is read from STDIN and therefore reading from STDIN explicitly changes the next input line or skips input lines.

If none of -r -f -B -R -F or -E is present but a single parameter is given then this parameter is taken as the filename to parse and execute (same as with -f). If no parameter is present then the standard input is read and executed.

 

OPTIONS

Tag Description

--interactive 
-a
Run PHP interactively. This lets you enter snippets of PHP code that directly get executed. When readline support is enabled you can edit the lines and also have history support.
--bindpathaddress:port|port
-baddress:port|port
  Bind Path for external FASTCGI Server mode (CGI only).
--no-chdir 
-C
Do not chdir to the script’s directory (CGI only).
--no-header 
-q
Quiet-mode. Suppress HTTP header output (CGI only).
--timing count 
-T count
Measure execution time of script repeated count times (CGI only).
--php-inipath|file 
-c path|file
Look for php.ini file in the directory path or use the specified file
--no-php-ini 
-n
No php.ini file will be used
--definefoo[=bar
-d foo[=bar]
  Define INI entry foo with value bar
-e Generate extended information for debugger/profiler
--file file 
-f file
Parse and execute file
--global name 
-g name
Make variable name global in script.
--help 
-h
This help
--hide-args 
-H
Hide script name (file) and parameters (args...) from external tools. For example you may want to use this when a php script is started as a daemon and the command line contains sensitive data such as passwords.
--info 
-i
PHP information and configuration
--syntax-check 
-l
Syntax check only (lint)
--modules 
-m
Show compiled in modules
--run code 
-r code
Run PHP code without using script tags ’..?>’
--process-begin code 
-B code
  Run PHP code before processing input lines
--process-codecode 
-R code
  Run PHP code for every input line
--process-filefile 
-F file
  Parse and execute file for every input line
--process-endcode 
-E code
Run PHP code after processing all input lines
--syntax-highlight 
-s
Output HTML syntax highlighted source
--version 
-v
Version number
--stripped 
-w
Output source with stripped comments and whitespace
--zend-extension file 
-z file
  Load Zend extension file
args... Arguments passed to script. Use ’--’ args when first argument starts with ’-’ or script is read from stdin
--rfunction name
--rf name Shows information about function name
--rclass name
--rc name Shows information about class name
--rextension name
--re name Shows information about extension name
--rextinfo name
--ri name Shows configuration for extension name
--ini Show configuration file names

 

FILES

 

Tag Description

php-cli.ini The configuration file for the CLI version of PHP.
php.ini The standard configuration file will only be used when php-cli.ini cannot be found.

 

EXAMPLES

 

Tag Description

php -r ’echo "Hello World\n";’
  This command simply writes the text "Hello World" to standard out.
php -r ’print_r(gd_info());’
  This shows the configuration of your gd extension. You can use this to easily check which image formats you can use. If you have any dynamic modules you may want to use the same ini file that php uses when executed from your webserver. There are more extensions which have such a function. For dba use:php -r ’print_r(dba_handlers(1));’
php -R ’echo strip_tags($argn)."\n";’
  This PHP command strips off the HTML tags line by line and outputs the result. To see how it works you can first look at the following PHP command 'php -d html_errors=1 -i' which uses PHP to output HTML formatted configuration information. If you then combine those two 'php ...|php ...' you’ll see what happens.
php -E ’echo "Lines: $argi\n";’
  Using this PHP command you can count the lines being input.
php -R ’@$l+=count(file($argn));’ -E ’echo "Lines:$l\n";’
  In this example PHP expects each input line being a file. It counts all lines of the files specified by each input line and shows the summarized result. You may combine this with tools like find and change the php scriptlet.
php -R ’echo "$argn\n"; fgets(STDIN);’
  Since you have access to STDIN from within -B -R -F and -E you can skip certain input lines with your code. But note that in such cases $argi only counts the lines being processed by php itself. Having read this you will guess what the above program does: skipping every second input line.

 

TIPS

You can use a shebang line to automatically invoke php from scripts. Only the CLI version of PHP will ignore such a first line as shown below:

#!/bin/php

// your script

?>

 

SEE ALSO

 

http://www.php.net/manual/

 

BUGS

You can view the list of known bugs or report any new bug you found at:

http://bugs.php.net

AUTHORS

The PHP Group: Thies C. Arntzen, Stig Bakken, Andi Gutmans, Rasmus Lerdorf, Sam Ruby, Sascha Schumann, Zeev Suraski, Jim Winstead, Andrei Zmievski.

Additional work for the CLI sapi was done by Edin Kadribasic, Marcus Boerger and Johannes Schlueter.

A List of active developers can be found here:

http://www.php.net/credits.php

And last but not least PHP was developed with the help of a huge amount of contributors all around the world.

VERSION INFORMATION

This manpage describes php, version 5.2.17.

COPYRIGHT

Copyright © 1997-2010 The PHP Group

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/952017.htmlTechArticlephp命令行用法简介,php命令行用法 Php是一个非常流行的web服务端脚本语言。其实,php不仅仅可以在web服务器中充当重要角色。在命令行一样...
성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
PHP 실행 : 실제 예제 및 응용 프로그램PHP 실행 : 실제 예제 및 응용 프로그램Apr 14, 2025 am 12:19 AM

PHP는 전자 상거래, 컨텐츠 관리 시스템 및 API 개발에 널리 사용됩니다. 1) 전자 상거래 : 쇼핑 카트 기능 및 지불 처리에 사용됩니다. 2) 컨텐츠 관리 시스템 : 동적 컨텐츠 생성 및 사용자 관리에 사용됩니다. 3) API 개발 : 편안한 API 개발 및 API 보안에 사용됩니다. 성능 최적화 및 모범 사례를 통해 PHP 애플리케이션의 효율성과 유지 보수 성이 향상됩니다.

PHP : 대화식 웹 컨텐츠를 쉽게 만들 수 있습니다PHP : 대화식 웹 컨텐츠를 쉽게 만들 수 있습니다Apr 14, 2025 am 12:15 AM

PHP를 사용하면 대화식 웹 컨텐츠를 쉽게 만들 수 있습니다. 1) HTML을 포함하여 컨텐츠를 동적으로 생성하고 사용자 입력 또는 데이터베이스 데이터를 기반으로 실시간으로 표시합니다. 2) 프로세스 양식 제출 및 동적 출력을 생성하여 htmlspecialchars를 사용하여 XSS를 방지합니다. 3) MySQL을 사용하여 사용자 등록 시스템을 작성하고 Password_Hash 및 전처리 명세서를 사용하여 보안을 향상시킵니다. 이러한 기술을 마스터하면 웹 개발의 효율성이 향상됩니다.

PHP 및 Python : 두 가지 인기있는 프로그래밍 언어를 비교합니다PHP 및 Python : 두 가지 인기있는 프로그래밍 언어를 비교합니다Apr 14, 2025 am 12:13 AM

PHP와 Python은 각각 고유 한 장점이 있으며 프로젝트 요구 사항에 따라 선택합니다. 1.PHP는 웹 개발, 특히 웹 사이트의 빠른 개발 및 유지 보수에 적합합니다. 2. Python은 간결한 구문을 가진 데이터 과학, 기계 학습 및 인공 지능에 적합하며 초보자에게 적합합니다.

PHP의 지속적인 관련성 : 여전히 살아 있습니까?PHP의 지속적인 관련성 : 여전히 살아 있습니까?Apr 14, 2025 am 12:12 AM

PHP는 여전히 역동적이며 현대 프로그래밍 분야에서 여전히 중요한 위치를 차지하고 있습니다. 1) PHP의 단순성과 강력한 커뮤니티 지원으로 인해 웹 개발에 널리 사용됩니다. 2) 유연성과 안정성은 웹 양식, 데이터베이스 작업 및 파일 처리를 처리하는 데 탁월합니다. 3) PHP는 지속적으로 발전하고 최적화하며 초보자 및 숙련 된 개발자에게 적합합니다.

PHP의 현재 상태 : 웹 개발 동향을 살펴보십시오PHP의 현재 상태 : 웹 개발 동향을 살펴보십시오Apr 13, 2025 am 12:20 AM

PHP는 현대 웹 개발, 특히 컨텐츠 관리 및 전자 상거래 플랫폼에서 중요합니다. 1) PHP는 Laravel 및 Symfony와 같은 풍부한 생태계와 강력한 프레임 워크 지원을 가지고 있습니다. 2) Opcache 및 Nginx를 통해 성능 최적화를 달성 할 수 있습니다. 3) PHP8.0은 성능을 향상시키기 위해 JIT 컴파일러를 소개합니다. 4) 클라우드 네이티브 애플리케이션은 Docker 및 Kubernetes를 통해 배포되어 유연성과 확장 성을 향상시킵니다.

PHP 대 기타 언어 : 비교PHP 대 기타 언어 : 비교Apr 13, 2025 am 12:19 AM

PHP는 특히 빠른 개발 및 동적 컨텐츠를 처리하는 데 웹 개발에 적합하지만 데이터 과학 및 엔터프라이즈 수준의 애플리케이션에는 적합하지 않습니다. Python과 비교할 때 PHP는 웹 개발에 더 많은 장점이 있지만 데이터 과학 분야에서는 Python만큼 좋지 않습니다. Java와 비교할 때 PHP는 엔터프라이즈 레벨 애플리케이션에서 더 나빠지지만 웹 개발에서는 더 유연합니다. JavaScript와 비교할 때 PHP는 백엔드 개발에서 더 간결하지만 프론트 엔드 개발에서는 JavaScript만큼 좋지 않습니다.

PHP vs. Python : 핵심 기능 및 기능PHP vs. Python : 핵심 기능 및 기능Apr 13, 2025 am 12:16 AM

PHP와 Python은 각각 고유 한 장점이 있으며 다양한 시나리오에 적합합니다. 1.PHP는 웹 개발에 적합하며 내장 웹 서버 및 풍부한 기능 라이브러리를 제공합니다. 2. Python은 간결한 구문과 강력한 표준 라이브러리가있는 데이터 과학 및 기계 학습에 적합합니다. 선택할 때 프로젝트 요구 사항에 따라 결정해야합니다.

PHP : 웹 개발의 핵심 언어PHP : 웹 개발의 핵심 언어Apr 13, 2025 am 12:08 AM

PHP는 서버 측에서 널리 사용되는 스크립팅 언어이며 특히 웹 개발에 적합합니다. 1.PHP는 HTML을 포함하고 HTTP 요청 및 응답을 처리 할 수 ​​있으며 다양한 데이터베이스를 지원할 수 있습니다. 2.PHP는 강력한 커뮤니티 지원 및 오픈 소스 리소스를 통해 동적 웹 컨텐츠, 프로세스 양식 데이터, 액세스 데이터베이스 등을 생성하는 데 사용됩니다. 3. PHP는 해석 된 언어이며, 실행 프로세스에는 어휘 분석, 문법 분석, 편집 및 실행이 포함됩니다. 4. PHP는 사용자 등록 시스템과 같은 고급 응용 프로그램을 위해 MySQL과 결합 할 수 있습니다. 5. PHP를 디버깅 할 때 error_reporting () 및 var_dump ()와 같은 함수를 사용할 수 있습니다. 6. 캐싱 메커니즘을 사용하여 PHP 코드를 최적화하고 데이터베이스 쿼리를 최적화하며 내장 기능을 사용하십시오. 7

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음