Php command in terminal

Php command in terminal

    Tell PHP to execute a certain file.

$ php my_script.php $ php -f my_script.php
$ php -r 'print_r(get_defined_constants());'

Note: Read the example carefully: there are no beginning or ending tags! The -r switch simply does not need them, and using them will lead to a parse error.

$ some_application | some_filter | php | sort -u > final_output.txt

As with every shell application, the PHP binary accepts a number of arguments; however, the PHP script can also receive further arguments. The number of arguments that can be passed to your script is not limited by PHP (and although the shell has a limit to the number of characters which can be passed, this is not in general likely to be hit). The arguments passed to the script are available in the global array $argv . The first index (zero) always contains the name of the script as called from the command line. Note that, if the code is executed in-line using the command line switch -r, the value of $argv[0] will be «Standard input code» ; prior to PHP 7.2.0, it was a dash ( «-» ) instead. The same is true if the code is executed via a pipe from STDIN .

A second global variable, $argc , contains the number of elements in the $argv array (not the number of arguments passed to the script).

As long as the arguments to be passed to the script do not start with the — character, there’s nothing special to watch out for. Passing an argument to the script which starts with a — will cause trouble because the PHP interpreter thinks it has to handle it itself, even before executing the script. To prevent this, use the argument list separator — . After this separator has been parsed by PHP, every following argument is passed untouched to the script.

# This will not execute the given code but will show the PHP usage $ php -r 'var_dump($argv);' -h Usage: php [options] [-f] [args. ] [. ] # This will pass the '-h' argument to the script and prevent PHP from showing its usage $ php -r 'var_dump($argv);' -- -h array(2) < [0]=>string(1) "-" [1]=> string(2) "-h" >

However, on Unix systems there’s another way of using PHP for shell scripting: make the first line of the script start with #!/usr/bin/php (or whatever the path to your PHP CLI binary is if different). The rest of the file should contain normal PHP code within the usual PHP starting and end tags. Once the execution attributes of the file are set appropriately (e.g. chmod +x test), the script can be executed like any other shell or perl script:

Example #1 Execute PHP script as shell script

Assuming this file is named test in the current directory, it is now possible to do the following:

$ chmod +x test $ ./test -h -- foo array(4) < [0]=>string(6) "./test" [1]=> string(2) "-h" [2]=> string(2) "--" [3]=> string(3) "foo" >

As can be seen, in this case no special care needs to be taken when passing parameters starting with — .

The PHP executable can be used to run PHP scripts absolutely independent of the web server. On Unix systems, the special #! (or «shebang») first line should be added to PHP scripts so that the system can automatically tell which program should run the script. On Windows platforms, it’s possible to associate php.exe with the double click option of the .php extension, or a batch file can be created to run scripts through PHP. The special shebang first line for Unix does no harm on Windows (as it’s formatted as a PHP comment), so cross platform programs can be written by including it. A simple example of writing a command line PHP program is shown below.

Читайте также:  Calendar minus day java

Example #2 Script intended to be run from command line (script.php)

if ( $argc != 2 || in_array ( $argv [ 1 ], array( ‘—help’ , ‘-help’ , ‘-h’ , ‘-?’ ))) ?>

This is a command line PHP script with one option.

can be some word you would like
to print out. With the —help, -help, -h,
or -? options, you can get this help.

The script above includes the Unix shebang first line to indicate that this file should be run by PHP. We are working with a CLI version here, so no HTTP headers will be output.

The program first checks that there is the required one argument (in addition to the script name, which is also counted). If not, or if the argument was —help, -help, -h or -?, the help message is printed out, using $argv[0] to dynamically print the script name as typed on the command line. Otherwise, the argument is echoed out exactly as received.

To run the above script on Unix, it must be made executable, and called simply as script.php echothis or script.php -h. On Windows, a batch file similar to the following can be created for this task:

Example #3 Batch file to run a command line PHP script (script.bat)

@echo OFF "C:\php\php.exe" script.php %*

Assuming the above program is named script.php , and the CLI php.exe is in C:\php\php.exe , this batch file will run it, passing on all appended options: script.bat echothis or script.bat -h.

See also the Readline extension documentation for more functions which can be used to enhance command line applications in PHP.

On Windows, PHP can be configured to run without the need to supply the C:\php\php.exe or the .php extension, as described in Command Line PHP on Microsoft Windows.

Note:

On Windows it is recommended to run PHP under an actual user account. When running under a network service certain operations will fail, because «No mapping between account names and security IDs was done».

User Contributed Notes 7 notes

On Linux, the shebang (#!) line is parsed by the kernel into at most two parts.
For example:

1: #!/usr/bin/php
2: #!/usr/bin/env php
3: #!/usr/bin/php -n
4: #!/usr/bin/php -ddisplay_errors=E_ALL
5: #!/usr/bin/php -n -ddisplay_errors=E_ALL

1. is the standard way to start a script. (compare «#!/bin/bash».)

2. uses «env» to find where PHP is installed: it might be elsewhere in the $PATH, such as /usr/local/bin.

3. if you don’t need to use env, you can pass ONE parameter here. For example, to ignore the system’s PHP.ini, and go with the defaults, use «-n». (See «man php».)

4. or, you can set exactly one configuration variable. I recommend this one, because display_errors actually takes effect if it is set here. Otherwise, the only place you can enable it is system-wide in php.ini. If you try to use ini_set() in your script itself, it’s too late: if your script has a parse error, it will silently die.

Читайте также:  Некэшируемые типы данных python

5. This will not (as of 2013) work on Linux. It acts as if the whole string, «-n -ddisplay_errors=E_ALL» were a single argument. But in BSD, the shebang line can take more than 2 arguments, and so it may work as intended.

Summary: use (2) for maximum portability, and (4) for maximum debugging.

Источник

How to use PHP through command-line

PHP is mainly used to develop web applications, but it can also be used for other purposes. One of the useful features of PHP is the support of SAPI (Server Application Programming Interface) type named CLI (Command Line Interface). The CLI SAPI is released in PHP 4.2.0 version for the first time. The –enable-cli option is used to enable this feature, and this option is enabled in the new version of PHP by default. Furthermore, the –disable-cli option is used to disable this feature.

Different CLI options are used in PHP, and the way of executing PHP script from the command line is described in this tutorial.

CLI options:

Some mostly used CLI options. They are explained below:

Option Description
-r It is used to execute PHP script without using PHP delimiter ().
-f It is used to execute the PHP file.
-i It is used to display the output of phpinfo().
-l It is used to check the syntax of the given PHP file.
-w It is used strip comments and whitespaces from the given file.
-a It is used to run in an interactive shell environment.
-h It is used to display all available options with an explanation of CLI.
-v It is used to display the PHP CLI version information.

Uses of CLI options:

You have to install PHP on your operating system to check the CLI options of PHP. No web server is required to run the PHP script from the terminal. So, you can run the PHP command from any location, and the PHP file can be stored in any location.

The uses of different CLI options are shown in this part of this tutorial.

Example-1: Check the version of CLI using –v

Run PHP command with -v option from the terminal.

The following output shows CLI version 7.4.3 installed on the system.

Example-2: Display the output of phpinfo() using -i

Run PHP command with -i option from the terminal.

The following output shows the detailed information returned by the phpinfo() function.

Example-3: Execute a simple PHP script without PHP delimiter using -r

Run PHP command with -r option and a script from the terminal.

The following output will appear after running the script. The string value is printed with a newline here.

Example-4: Execute PHP script from a file using -f

Create a PHP file named cli1.php with the following script. Here, STDIN is defined at the beginning of the script to take the input from the user. Next, two string values will be taken from the user where the input value can be a maximum of 5 characters. Then, the values will be converted into integer values, and their sum will be stored in a variable that will be printed later.

#!/usr/bin/php -q

// Define STDIN to read data from PHP
if ( ! defined ( «STDIN» ) ) {
define ( «STDIN» , fopen ( ‘php://stdin’ , ‘r’ ) ) ;
}

Читайте также:  Рамка вокруг таблицы

//Take two numeric values as input
echo «Enter the value of a: » ;
$number1 = fread ( STDIN , 5 ) ;
echo «Enter the value of b: » ;
$number2 = fread ( STDIN , 5 ) ;

//Convert the string data to number and calculate sum
$sum = ( int ) $number1 + ( int ) $number2 ;

//Print the result of the summation
printf ( «The sum of %d and %d is %d \n » , $number1 , $number2 , $sum ) ;
?>

Run the PHP file from the terminal using the PHP command with -f option. You have to mention the path of the PHP file properly in the command.

In the following output, 30 and 70 are taken as input, and 100 is printed as output.

Example-5: Check the syntax of PHP file using -l

Create a PHP file named cli2.php with the following script. Here, STDIN is defined at the beginning of the script to take the input from the user. Next, a string value will be taken from the user and that is printed after formating.

#!/usr/bin/php -q

// Define STDIN to read data from PHP
if ( ! defined ( «STDIN» ) ) {
define ( «STDIN» , fopen ( ‘php://stdin’ , ‘r’ ) ) ;
}

echo «What is your favorite color? \n » ;
//Take input from the user
$color = fread ( STDIN , 10 ) ;
//Print the input value
printf ( «Your selected color is: %s \n » , $color ) ;
?>

Run the above script with the -l option to check the syntax error. If the script contains any syntax error, then the output will display the error with a line number. Otherwise, it will print the value ‘No syntax error detected’. It is better to check the script, whether contains any syntax error or not, before executing the script.

The following output shows that the script has no syntax error. For example, if any semicolon(;) is omitted after any line, then it will display the error with line number.

Example-6: Display PHP script from a file by omitting comments and whitespaces using -w

You can check the use of the -w option by creating any PHP script file with comments and whitespaces. Create a PHP file named cli3.php with the following code that contains two comments and many whitespaces. The output will show the full script by removing comments and whitespaces.

//Assign a numeric value
$num = 78 ;

//Check the number is less than 100 or not
if ( $num < 100 )
{
echo «The value $num is less than 100 \n » ;
}
else
{
echo «The value $num is more than or equal to 100 \n » ;
}

Run the above script with -w option using PHP command.

The following output will appear after running the script.

Conclusion

You can test the PHP script without using any web server by using the CLI feature. Many other options exist for PHP CLI for different purposes. You can get the list of all CLI options by running the PHP command with the -h option if you want to know more about the PHP CLI. The most commonly used CLI options are explained in this tutorial, with examples, to let the readers know more about this PHP feature.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Оцените статью