1

In the code below I would like to be able to input a single character from the keyboard without having to type afterwards. Currently I have to add at the read_stdin() statement. This greatly slows the process when I have a lot of photos. Doubling the keystrokes required to sort each photo.

<?php

// View the jpg images one at a time
$files = glob("images/*.jpg");
foreach($files as $jpg){
//    echo "<img src='$jpg'></br>";
  echo "view image somehow" . PHP_EOL;

echo "The jpg variable equals '$jpg'" . PHP_EOL;

// show them a message to enter letter for category
echo "Enter the category, a(family), r(friends), c(coworkers), d(delete), ctrl-letter(two folders)" . PHP_EOL;

// the script will wait here until the user has entered something and hit ENTER
$category = read_stdin();

// This will display the category message including the category they entered.
echo "You chose $category . Next photo" . PHP_EOL;

switch ($category) {
    case "a":
        echo "$category equals family" . PHP_EOL;
        rename("$jpg", "images/sorted/family/$jpg");
        break;
    case "r":
        echo "$category equals friends" . PHP_EOL;
        rename("$jpg", "images/sorted/friends/$jpg");
        break;
    case "c":
        echo "$category equals coworkers" . PHP_EOL;
        rename("$jpg", "images/sorted/coworkers/$jpg");
        break;
    default:
       echo "$category is not equal to a,r, or c" . PHP_EOL;
 }

}

// our function to read from the command line
function read_stdin()
{
        $fr=fopen("php://stdin","r");   // open our file pointer to read from stdin
        $input = fgets($fr,128);        // read a maximum of 128 characters
        $input = rtrim($input);         // trim any trailing spaces.
        fclose ($fr);                   // close the file handle
        return $input;                  // return the text entered
}

?>
John
  • 41
  • 5
  • This may be answered here: http://stackoverflow.com/questions/3684367/php-cli-how-to-read-a-single-character-of-input-from-the-tty-without-waiting-f – Lack Jan 16 '15 at 04:55

1 Answers1

2

Yes, you can place the following code at the beginning of your script:

system("stty -icanon");

This will set the terminal line settings to accept one character at a time.

You may wish the place the following code at the end of your script:

system("stty sane");

Which will restore the terminal to its "sane" state.

Leo Galleguillos
  • 2,429
  • 3
  • 25
  • 43
  • I have implemented the system("stty -icanon"); line at the beginning of my script but it is still requiring me to press after typing the single letter. – John Jan 16 '15 at 19:11
  • Change `fgets` to `fread`. The [answer this one duplicates](http://stackoverflow.com/questions/3684367/php-cli-how-to-read-a-single-character-of-input-from-the-tty-without-waiting-f) actually has an example of working code. – Lack Jan 17 '15 at 01:11