Zend - The PHP Company




Text

Add Code


Implementing PHP into console with readline  

Type: code fragment
Added by: phpie
Entered: 17/02/2002
Last modified: 03/12/2001
Rating: - (fewer than 3 votes)
Views: 4857
Some simple functions to handle data for those wanting to write php console scripts with readline, with an example for adding colour to your scripts too.


<?php

/*

here's a list of the colours, exactly the same as normal shell colours - they're used for cl()

reset         = 0          
flashing      = 5
black         = 0;30       
red           = 0;31
green         = 0;32
yellow        = 0;33
blue          = 0;34
magenta       = 0;35
cyan          = 0;36
white         = 0;37
highblack     = 1;30
highred       = 1;31
highgreen     = 1;32
highyellow    = 1;33
highblue      = 1;34
highmagenta   = 1;35
highcyan      = 1;36
highwhite     = 1;37
bg-white      = 47
bg-magenta    = 45
bg-blue       = 44
bg-red        = 41
bg-black      = 40
bg-green      = 42
bg-yellow     = 43
bg-cyan       = 46

*/

/* return shell colours - return 0 to reset (you can remove the colouring if you don't want to use it, it's just an example to show how colour can be added).  chr(27) returns the ^[ character */
function cl($str 0) {
  return (
chr(27) . "[" $str "m");
}

/* i think this is a nifty function, checks user input for readline() (uses $default if given), asks for it again if user input is null when no default is set, and prints out the colours for bash (which you can remove by deleting all cl()'s in it) */

function readline_add($str,$default null) {
  for (
$i 0$i 1$i++) {  
    if (
$default !== null) {
      
$line readline(cl("1;31") . $str cl("1;37") . " [$default]: ");
      if (isset(
$line) && $line !== "") {
        
readline_add_history($line); /* add history */
      
} else {
        
readline_add_history($default); /* add default to history */
      
}
    } else {
      
$line readline(cl("1;31") . $str cl("1;37") . ": ");
      if (isset(
$line) && $line !== "") {
        
readline_add_history($line); /* add history */
      
} else {
        
$i -= 1/* we -1 to repeat the query if input is null */
      
}
    }  
  }
}

?>


Usage Example


<?php

readline_add
("Username"); /* $history[0] - if no input is given, it asks for it again */
readline_add("Shell","/bin/bash"); /* $history[1] - if no input is given it defaults to /bin/bash */
/* readline_list_history returns arrays, so handle the array how you wish... */
$history readline_list_history();

print 
"Username: " $history[0] . "n";
print 
"Shell Type: " $history[1] . "n";

print 
cl(); /* we just do this to reset the colours so colours aren't broken when the script exits */

?>


Rate This Script





Search



This Category All Categories