PHP-CLI Semi-FAQ

June 14, 2005

PHP-CLI Semi-FAQ

I've been playing around with the PHP-CLI a bit recently and thought I'd post a couple solutions to issues that I have come across:

  1. How can I prevent user input from being echoed back as it is being typed (e.g. for a password)?

    Use the UNIX command stty to set terminal line settings. To this end I have created a simple function called ttyecho:

    //*nix only... there is no way to do this in Windows unless you
    //want to muck around w/ Windows Scripting
    function ttyecho($on){
    global $ttyecho;
    if($on){
    if(isset($ttyecho))
    exec("stty $ttyecho");
    }
    else{
    $ttyecho = exec("stty -g");
    exec("stty -echo");
    }
    }

    //Usage:
    ttyecho(false); //turn off echoing
    $password = trim(fgets(STDIN)); //read in a password
    ttyecho(true); //turn echoing back on
  2. Suppose both STDOUT and STDERR are being redirected to a file like so: #myscript > foo.txt 2>&1. How can I guarantee that a certain string is echoed to the TTY and not redirected?

    Open up a stream to /dev/tty using fopen and then write to it just like you would to a file or to STDOUT. This is useful in cases where you are prompting the user for input and need to ensure he/she gets the message. (Won't work in Windows for obvious reasons)

  3. I want to run a PHP script from the DOS prompt, but I am too lazy to type "php myscript.php". Couldn't I just type "myscript" and have it run like I do in Linux?

    Sure thing... First off, the .php extension is not required, but you can take it one step further using a batch file. If your PHP file is named "myscript", create a batch file named "myscript.bat" in the same directory with the following two lines:

    @echo off
    php "%~dp0myscript" %*

    Assuming that the location of PHP executable and your scripts can be found via the PATH variable, you can call "myscript" from anywhere. "%~dp0" prepends the directory where the script is located and "%*" passes any command line parameters from the batch file to your script.

Questions? Comments? Errors? Let me have it.

Posted by jon at June 14, 2005 12:40 AM

Comments

Cheers for posting that. I've just used your ttyecho() function.

Posted by: Dave at October 28, 2006 11:33 AM
Post a comment









Remember personal info?