Hello guys, today we will learn how to write PHP programs through command line. Generally, PHP is use for web applications but there are occasions where we can use command line such as automatic mail sending, log tracking, cron jobs etc.
PHP supports CLI SAPI(Command Line Interface Server API) for executing the script from command line. This SAPI will differ from other interfaces based on the IO practices, configuration defaults, buffering and more.
For example,
For example,
- IO practices – it will not support PHP request method (GET, POST). Instead, it uses IO streams.
- Command line execution time – In the command line, the execution time limit is unlimited by default.
- Buffering – implicit_flush is enabled to display output. It also supports output buffering.
Some of the PHP CLI SAPI commands:
| Command | Description |
| -i | To display command line PHP info. |
| -v | To show version details. |
| -r | To execute PHP script without delimiters |
| -f | To execute PHP file. |
| -l | To check the syntax of the given file. |
| -w | To strip comments, white spaces from given file and print. |
| -a | To run in the interactive shell environment. |
Note : Try with -h to know more about them.
PHP command line examples:
Now, let us see some simple examples to interact PHP from the command line.These examples deal with PHP where the file name or code is given.
Now, let us see some simple examples to interact PHP from the command line.These examples deal with PHP where the file name or code is given.
Executing PHP file:
Program to print array of strings:
1 2 3 4 | <?php $fruits = array('apple','mango','grapes'); print_r($fruits); ?> |
save this file as index.php. Now you can execute the program from command line by going to the file path and specifying php index.php.
This command will execute the index.php file and print the output as below
Executing PHP code:
This command will execute the index.php file and print the output as below
Executing PHP code:
You can directly execute PHP code in command line. In this example, PHP exho statement is executed from command line.
Hope you understand the tutorial.If you have any doubts please do comment .Please share this post with your friends .Thank you.Have a good day :)
Hope you understand the tutorial.If you have any doubts please do comment .Please share this post with your friends .Thank you.Have a good day :)
Comments
Post a Comment