downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

readline_add_history> <rar_open
[edit] Last updated: Mon, 01 Nov 2010

view this page in

CXXXI. Readline (GNU)

Introduction

Les fonctions readline implémentent une interface avec la bibliothèque GNU Readline. Ces fonctions fournissent une ligne de commande éditable, un peu comme lorsque Bash vous permet d'utiliser les flèches de déplacement pour insérer un caractère ou passer en revue l'historique. À cause de l'interactivité de ces commande, elles ne seront que rarement utiles pour les applications Web, mais peuvent se révéler utiles lorsqu'un script est exécuté depuis une ligne de commande.

Note : Cette extension n'est pas disponible sur les plates-formes Windows.

Pré-requis

Pour utiliser les fonctions readline, vous devez installer la bibliothèque libreadline. Vous pouvez la trouver sur la page du projet GNU, à http://cnswww.cns.cwru.edu/~chet/readline/rltop.html. Elle est maintenue par Chet Ramey, qui est l'auteur de Bash.

Vous pouvez aussi utiliser ces fonctions avec la bibliothèque libedit, un remplacement de la bibliothèque readline, qui n'est pas GPL. La bibliothèque libedit est sous licence BSD, et elle est disponible depuis http://www.thrysoee.dk/editline/.

Installation

Pour utiliser ces fonctions, vous devez compiler PHP, en version CGI ou CLI. Vous devez aussi utiliser l'option de compilation --with-readline[=DIR]. Si vous souhaitez utiliser la bibliothèque libedit readline, en remplacement, compilez PHP avec l'option --with-libedit[=DIR].

Configuration à l'exécution

Cette extension ne définit aucune directive de configuration.

Types de ressources

Cette extension ne définit aucune ressource.

Constantes pré-définies

Cette extension ne définit aucune constante.

Table des matières
readline_add_history -- Ajoute une ligne à l'historique
readline_callback_handler_install -- Initialise l'interface et le terminal de callback de readline, affiche le prompt et retourne immédiatement
readline_callback_handler_remove -- Efface un gestionnaire de callback installé précédemment et restaure les paramètres du terminal
readline_callback_read_char -- Lit un caractère et informe l'interface de callback readline lorsqu'une ligne est reçue
readline_clear_history -- Efface l'historique
readline_completion_function -- Enregistre une fonction de complétion
readline_info -- Lit/modifie diverses variables internes
readline_list_history -- Liste l'historique
readline_on_new_line --  Informe readline que le curseur est passé à une nouvelle ligne
readline_read_history -- Lit l'historique
readline_redisplay --  Demande à readline de refaire l'affichage
readline_write_history -- Ecrit dans l'historique
readline -- Lit une ligne


readline_add_history> <rar_open
[edit] Last updated: Mon, 01 Nov 2010
 
add a note add a note User Contributed Notes Readline (GNU)
david at acz dot org 28-Feb-2007 09:07
Readline only reads the window size on startup or on SIGWINCH.  This means if the window is resized when not in a readline() call, the next call will have odd behavior due to confusion about the window size.

The work-around is to force Readline to re-read the window size by sending it SIGWINCH.  This is accomplished using the async interface, which installs the signal handler but returns control to PHP.

The following function is a drop-in replacement for readline(), but re-reads the window size every time:

<?
   
function xreadline($prompt)
    {
        global
$xreadline, $xreadline_line;
       
$code = '$GLOBALS["xreadline"] = false;' .
               
'$GLOBALS["xreadline_line"] = $line;' .
               
'readline_callback_handler_remove();';
       
$cb = create_function('$line', $code);
       
readline_callback_handler_install($prompt, $cb);
       
$signal = defined("SIGWINCH") ? SIGWINCH : 28;
       
posix_kill(posix_getpid(), $signal);
       
$xreadline = true;
        while (
$xreadline)
           
readline_callback_read_char();
        return
is_null($xreadline_line) ? false : $xreadline_line;
    }
?>
flobee 28-Apr-2006 10:29
re to: ds at NOSPAM dot undesigned dot org dot za

cool program! note when trying to exec() something:
in the while loop you need to reset exec() returns or you will get all results of all executions (on my my windows and or cygwin :-(
like:
<?php
// your class prompt()

echo "Enter something or 'exit' to quit\n";
do {
   
$cmdline = new prompt();
   
$buffer = $cmdline->get('shell command: ');
// init/ reset first!
   
$data = null;
   
$return = null;
// now start:
   
echo "You said: $buffer\n";
    if (!empty(
$buffer)) {
       
$x = exec($buffer, $data, $return);
       
print_r($data);
    }
} while (
$buffer !== "exit");
echo
"Goodbye\n";
jeffrey at thompsonic dot com 22-Feb-2005 06:18
Here's an easy way without readline() if you don't have it compiled in already:

   $fp = fopen("php://stdin","r");
   $line = rtrim(fgets($fp, 1024);
jcl atNOSPAM jcl dot name 23-Nov-2004 09:40
Even better than 'plz at dont dot spam' in only one line :) :

@c:\\php\\cli\\php.exe script.php %*

Cheers,
Jean-Charles
plz at dont dot spam 08-Aug-2004 01:50
To get all arguments passed to a batch file in one variable
rather than using %1 %2 %3 etc;

:LOOP
if "%1" == "" goto DONE
set args=%args% %1
shift
goto LOOP
:DONE
@c:\\php\\cli\\php.exe script.php %args%
set args=
ds at NOSPAM dot undesigned dot org dot za 04-Dec-2003 08:04
You can open /dev/tty on unix systems or \con in windows, with ob_implicit_flush(true) to write output unbuffered.  Works like a charm :-)

-------------------------------

#!/usr/local/bin/php -q
<?php

set_time_limit
(0);
@
ob_end_flush();
ob_implicit_flush(true);

class
prompt {
  var
$tty;

  function
prompt() {
    if (
substr(PHP_OS, 0, 3) == "WIN") {
     
$this->tty = fOpen("\con", "rb");
    } else {
      if (!(
$this->tty = fOpen("/dev/tty", "r"))) {
       
$this->tty = fOpen("php://stdin", "r");
      }
    }
  }

  function
get($string, $length = 1024) {
    echo
$string;
   
$result = trim(fGets($this->tty, $length));
    echo
"\n";
    return
$result;
  }
}

echo
"Enter something or 'exit' to quit\n";
do {
 
$cmdline = new prompt();
 
$buffer = $cmdline->get("Something: ");
  echo
"You said: $buffer\n";
} while (
$buffer !== "exit");
echo
"Goodbye\n";

?>
jewfish at jewfish dot net 10-Jun-2002 04:05
There is a simpler way to do a multiline read than above:

function multiline() {
    while(($in = readline("")) != ".")
        $story .= ($PHP_OS == "WINNT") ? "\r\n".$in :
                                         "\n".$in;

    return $story;
}
joshua at neocodesoftware.com 21-Apr-2002 03:17
Here's an example simple readline-like way to input from command line on windows - the single line is from http://www.phpbuilder.com/columns/darrell20000319.php3, the multiline is something I added...

<?
function read () {
   
# 4092 max on win32 fopen

   
$fp=fopen("php://stdin", "r");
   
$in=fgets($fp,4094);
   
fclose($fp);

   
# strip newline
   
(PHP_OS == "WINNT") ? ($read = str_replace("\r\n", "", $in)) : ($read = str_replace("\n", "", $in));

    return
$read;
}

function
multilineread () {
    do {
       
$in = read();

       
# test exit
       
if ($in == ".") return $read;

       
# concat input
       
(PHP_OS == "WINNT") ? ($read = $read . ($read ? "\r\n" : "") . $in) : ($read = $read . "\n" . $in);

    } while (
$inp != ".");

    return
$read;
}

print(
"End input with . on line by itself.\n");

print(
"What is your first name?\n");
$first_name = multilineread();

print(
"What is your last name?\n");
$last_name = read();

print(
"\nHello, $first_name $last_name! Nice to meet you! \n");
?>
14-Apr-2002 07:17
[Ed. note: you can use fopen("php://stdin", "w") to achieve the same thing, works on both Windows and Unix)]

I wanted to get console input in a PHP script running on windows, so I made a little hack, which is so simple, it is clearly public domain.  What I did was write a C++ program to get a line, then output it.  Then all that is needed is to exec() that program and capture the output - readline() for windows.  The C++ source is as follows:

#include <iostream.h>
#include <string>
void main()
{
    string input;
    cin >> input;
    cout << input;
}

It works wonderfully for my purposes, since I love the PHP language and want to have console input.

Justin Henck

 
show source | credits | sitemap | contact | advertising | mirror sites