PHP and $argv
Posted by Code, Command-Line, Functions, Guides, Linux, OS X, PHP, Server, Ubuntu | Posted on 31-01-2011
| Posted inI’ve been adding $argv functionality to all of my PHP maintenance scripts. I am doing this, so I don’t have to edit a variable each time I want to execute it.
A PHP $argv example.
#!/usr/bin/php < ? PHP # test.php # demonstration of $argv # Dan McCoy # January 31 2011 $command = $argv[1]; $GLOBALS['script'] = basename($argv[0]); $GLOBALS['ver'] = "1.0"; $GLOBALS['file'] = $argv[2]; function help() { echo "Help for ". $GLOBALS['script'] ."\n"; echo "-h \t Help prompt \n"; echo "-v \t Version ". $GLOBALS['ver'] ."\n"; echo "-g \t Grab file from X \n"; echo "-f \t Reformat data from X \n"; echo "-l \t Load data from X \n"; }// end help function grab(){ @exec('/opt/local/bin/wget http://webserver.com/page.php -O '. $GLOBALS['file'],$retval); return "Grab completed ". $retval[0] ." \n"; }// end grab function reformat() { $fp = $GLOBALS['file']; $file = fopen($fp,'r'); $data = fread($file,filesize($fp)); fclose($file); $data = str_replace("<br /><br />","\n\n",$data); $data = str_replace("<br />","\n",$data); $data = strip_tags($data); $data = str_replace("\t","",$data); $fp = $GLOBALS['file']; $file = fopen($fp,'w'); fwrite($file,$data); fclose($file); return "Reformating completed \n"; }// end reformat function load() { $fp = $GLOBALS['file']; $file = fopen($fp,'r'); $data = fread($file,filesize($fp)); fclose($file); return $data; } function delete() { $ret = @unlink($GLOBALS['file']); if ($ret==TRUE){ return "File has been deleted \n"; }else{ return "There was an ERROR deleting ". $GLOBALS['file']."\n"; } }// end delete function switch_default() { echo "Command not found \n"; help(); } switch($command) { case "-h": echo help(); break; case "-g": echo grab(); break; case "-f": echo reformat(); break; case "-l": echo load(); break; case "-d": echo delete(); break; default: switch_default(); break; }// end switch ? >