Location: PHPKode > scripts > OO shell scripts using PHP > oo-shell-scripts-using-php/OO_PHP_Shell.php
(c) 2007-2008 Anil Jagtap, All rights reserved.
This material is free for use but you cannot claim its as your invension.
Email: hide@address.com
       hide@address.com
	   

PHP CLI
CLI = Command Line Interface

Writing first shell script using PHP

#!/opt/lampp/bin/php
<?php
echo "Hello World of PHP Scripting\n";
?>

Printing on output device using PHP output stream

#!/opt/lampp/bin/php
<?php
$out = fopen("php://stdout","w");
$str = "This is a string in PHP variable.";
fwrite($out,$str);
fclose($out);
echo "\n";
?>

Getting user input using PHP Stream

#!/opt/lampp/bin/php
<?
$keyboard = fopen("php://stdin","r");
print "Enter your name: ";
$input = fgets($keyboard,100);
print "\nYour Name is: $input" . "\n";
fclose($keyboard);
?>

Getting command line arguments using PHP shell script

#!/opt/lampp/bin/php
<?
echo "These are command line arguments passed:\n";
for( $i=0; $i < $argc; $i++ ){
	echo "Argument $i :". $argv[$i] . "\n";
}
$str = implode(",",$argv);
echo "Imploded arguments array:$str\n";
?>

Object Oriented Shell Scripting Using PHP

Its strange to hear about object oriented programming for shell scripting. And with PHP?
Yes, its really fun doing shell scripting using PHP. First I have written a few simple scripts
for shell using PHP like a few above.

There is not much available on Internet related to PHP CLI or Shell Scripts using PHP.

Here is a class I have written for getting OO in shell scripts

<?php
class mySystem{
	var $input;
	var $output;
	var $err;
	function mySystem(){
		$this->input = fopen("php://stdin","r");
		$this->output = fopen("php://stdout","w");
		$this->err = fopen("php://stderr","w");
	}

	function getLine(){
		return fgets($this->input,180);
	}
	
	function writeLine($line){
		fwrite($this->output,$line);
	}
	
	function writeErr($line){
		fwrite($this->err,$line);
	}
	
	function execCmd($cmd){
		return exec($cmd);
	}
	
	function Close(){
		fclose($this->input);
		fclose($this->output);
		fclose($this->err);
	}
}
?>

<?php
$ms = new mySystem();
$ms->writeLine("Enter Something:");
$ln = $ms->getLine();
$ms->writeLine("You typed:" . $ln);
$ms->writeLine( $ms->execCmd("ls -l"));
$ms->Close();
echo "\n";
?>
Return current item: OO shell scripts using PHP