search
HomeBackend DevelopmentPHP TutorialIntroduction to the method of passing custom parameters to cli command in php

Both the version compiled from source and the pre-created PHP version come with a PHP executable file by default. This executable can be used to run command line PHP programs.

To find this executable file on your system, follow the steps below: Windows: Place it in the main PHP installation directory. The file name is php.exe or (in older versions of PHP) php-cli.exe. Linux: Saved in the bin/ subdirectory of the PHP installation directory.

Note: The PHP.INI used when running in CLI mode and CGI mode are not the same set of configurations and need to be configured separately. No matter which system it is on, you need to test it to ensure that it works properly by calling it with the -v parameter:

shell> /path/php.exe -v
PHP 5.0.0 (cli) (built: Jun 1 2005 18:32:10)
Copyright (c) 1997-2004 The PHP Group
Zend Engine v2.0.0, Copyright (c) 1998-2004 Zend Technologies
It should return the PHP version number.

Use CLI commands A simple PHP CLI program named hello.php

<?php
echo "Hello from the CLI";
?>
Now, try running this program from the command line prompt by calling the CLI executable and providing the file name of the script:
shell> /path/php.exe /example/hello.php
Hello from the CLI

Use standard input and output The PHP CLI defines three constants to make it easier to interact with the interpreter at the command line prompt. These constants are shown in the table below
Constant Instructions
STDIN Standard input devices
STDOUT Standard output devices
STDERR Standard error facility

You can use these three constants in your own PHP scripts to accept user input or display the results of processing and calculations.

Usage example:

<?php
// ask for input
fwrite(STDOUT, "Enter your name: ");

// get input
$name = trim(fgets(STDIN));

// write input back
fwrite(STDOUT, "Hello, $name!");
?>

output:

D:\>\wamp\bin\php\php5.3.0\php.exe  \tools\index.php
Enter your name: kkk
Hello, kkk!

In this script, the fwrite() function first writes a message to the standard output device asking for the user's name. It then reads the user input information obtained from the standard input device into a PHP variable and combines it into a string. Then use fwrite() to print the string to the standard output device. Command line custom variables1【$argv|$argc】 It is common to enter arguments to a program at the command line to change the way it runs. You can do this with CLI programs as well. The PHP CLI comes with two special variables specifically designed for this purpose: One is the $argv variable, which saves the parameters passed to the PHP script through the command line as separate array elements; The other is the $argc variable, which is used to save the number of elements in the $argv array. Usage example:
<?php
print_r($argv);
?>

output:

D:\>\wamp\bin\php\php5.3.0\php.exe  \tools\index.php bac ddd
Array
(
    [0] => \tools\index.php
    [1] => bac
    [2] => ddd
)

As you can see from the output, the value passed to index.php automatically appears as an array element in $argv. Note that the first argument to $argv is always the name of the script itself.

Note: We can also use the Console_Getopt PEAR class to add more complex command line parameters to PHP.

Command line custom variables2 [Use Console_Getopt to receive parameters]

Note: This variable is only available when register_argc_argv is turned on

getopt($option, $longopts) // The first $option receives -h vb the second parameter receives --require sss

Usage examples

<?php
        $shortopts = "";
        $shortopts .= "f:";  // Required value
        $shortopts .= "v::"; // Optional value
        $shortopts .= "abc"; // These options do not accept values
        $longopts = array(
            "required:", // Required value
            "optional::", // Optional value
            "option", // No value
            "opt", // No value
        );
        $options = getopt($shortopts, $longopts);
        var_dump($options);
?> 

ouput:

D:\>\wamp\bin\php\php5.3.0\php.exe  \tools\index.php -f "value for f" -v -a --re
quired value --optional="optional value" --option will
array(6) {
  ["f"]=>
  string(11) "value for f"
  ["v"]=>
  bool(false)
  ["a"]=>
  bool(false)
  ["required"]=>
  string(5) "value"
  ["optional"]=>
  string(14) "optional value"
  ["option"]=>
  bool(false)
}
Command line variables3 [Use CLI parameters]

In addition to passing PHP script parameters with the command line, you can also pass PHP CLI parameters to change the way it works.

Parameters Instructions
-a Run interactively
-c path reads php’s .ini file from path
-n Run it directly without reading php’s .ini file
-m List compiled modules
-i Display information about PHP build
-l Check syntax of PHP script
-s Display source code in color
-w Show the source code without comments
-h Show help

交互模式 你还可以以交互方式使用PHP CLI,也就是输入命令,马上获得结果。 要得到这种效果,只需要使用一个参数调用CLI可执行文件就行了,就像下面这样:

shell> /path/to/php -a
Interactive mode enabled
<?php
echo mktime();
1121187283
echo 2+2;
4
exit();
shell>
或者,你可以不使用-a参数就调用CLI可执行文件,直接输入完整的脚本或者代码段。

-D来结束代码段,并让CLI来执行它。见下面的例子:

shell> /path/to/php
<?php
echo date("d-M-Y h:i:s", time());
?>
<Ctrl-D>
12-Jul-2005 06:54:04


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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools