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
- proc_* : php.net/manual/en/function.proc-open.php
- Superb, for long running external commands, where we can (are) parsing the output in real time.
Terminal information
- Size in columns : "tput cols"
- Size in rows : "tput lines"
- Supported Number of colors : "tput colors"
Let's check it out...
STREAMS
Standard streams
- Standard Output
- Standard Error
- Standard Input
Standard output
echo "HELLO WORLD";
php://output in not standard out
*** fwrite(STDOUT , 'Hello World!'); ***
STandard input
#!/usr/bin/php
<?php
fwrite(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
PHP - CLI
- 743