-
What is CLI [Command line interface]?
- CLI is a command-line program that accepts text input to execute operating system functions.
-
Why to use PHP CLI?
- because there are several advantages in being able to run PHP code from the command line such as:
- PHP into a general-purpose language to execute on any environment, not only on web servers.
- no need to learn another language such as Perl, Bash, Awk or python
- running scheduled (CRON) tasks.
- making GUI applications with GTK.
- reuse of your existing components.
- write very robust scripts for your system using multi-threading capabilities.
- access system STDIN [input], STDOUT [output], STERR [error].
- because there are several advantages in being able to run PHP code from the command line such as:
in this Guide, we will use vim editor and you are free to use vscode or anything you like
- for
php://stdin, php://stdout and php://stderr
check Accessing various I/O streams
-
We need to create our executable file and protect it from running on the web servers.
vim [example] -> (filename) then press Enter
[notes that we didn't add the extension for the file for protecting it].- make our file executable via our OS using the command
chmod -x example
.
-
Writing our program.
-
start your file with the following sentence.
- if you are following this guide using vim
press i
so you can start typing. #!/usr/bin/env php
to make our code executable via PHP installed on our machine.- after making sure that our program can execute our PHP code then open your PHP tag and start to write your code.
- if you are following this guide using vim
-
Inputs
- to read input while starting the CLI app use super global indexed array
$_SERVER["argv"]
- to access first input
$_SERVER["argv"][0]
the second - to access first input$_SERVER["argv"][1]
, etc - to get count of the parameter passed via starting the CLI app access it using
$_SERVER["argc"]
- to access first input
- after running the CLI app can make it reactive with the user which you are building the app for him use
$input = fread(fopen('php://stdin','r'), $length);
$length -> length of bytes you want to read
- to read input while starting the CLI app use super global indexed array
-
Outputs
echo $output|| print($output)
fwrite(fopen('php://stdout','w'), $output)
-
- with inputs
php [example] -> (filename) input1 input2, etc
- without inputs
php [example] -> (filename)