PHP CLI 

{name : "Nishant",
 email : "nishant@weboniselab.com",
 connection : {twitter : "n1shant" }}



What!


: What can we achieve

Using PHP, as a Shell script, while making it useful and appealing.



Why command line!


Why Not!!!
- Data processing
- Long running processes
- Tools and utilities
- Component testint 


Why php?


Why Not!!!

- Familiarity
- Flexibility
- Ease of use
- Code reuse


Examples



- Composer
- PHPUnit
- phpDocumentor
- Phing


How!



Hello World!!!

" #! "


Known as 
: Shebang
: Hash-bang
: Pound-bang

  • Intepreter Directive
    • #!/usr/bin/php
    • #!/usr/bin/env php
  • File should be Executable
System Calls


- `call` : Backtick operator

- shell_exec(string $cmd)

- exec(string $cmd , [,array &$output[, int &$input]])

- passthru(string)



process control





Terminal information

  1. Size in columns : "tput cols"
  2. Size in rows : "tput lines"
  3. Supported Number of colors : "tput colors"


Let's check it out... 




STREAMS



Standard streams


  1. Standard Output
  2. Standard Error
  3. Standard Input



Standard output


                            echo "HELLO WORLD";
php://output in not standard out
*** fwrite(STDOUT , 'Hello World!'); ***


STandard input

 #!/usr/bin/php<?phpfwrite(STDERR , "Are you sure (y/n) : ");if(fread(STDIN , 1) == 'y') {     fwrite (STDOUT , 'Super awesome..!');} else {     fwrite (STDOUT , 'This is Lame!');}fwrite (STDOUT , PHP_EOL);




Command line arguments


Basic arguments

  • Global $argv
  • First argument is always the executed script
  • Good for small scripts, if you want to pass on some 

#!/usr/bin/php <?php $arguments = $argv; print_r($arguments); fwrite (STDOUT , PHP_EOL);



Things to look at


  • PHAR for redistribution
  • PHP-CLI.com

PHP - CLI

By Nishant Shrivastava