1
0

cli-user-input.php 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. <?php
  2. /**
  3. * dolphin. Collection of useful PHP skeletons.
  4. * Copyright (C) 2013 Johannes 'Banana' Keßler
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the COMMON DEVELOPMENT AND DISTRIBUTION LICENSE
  8. *
  9. * You should have received a copy of the
  10. * COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
  11. * along with this program. If not, see http://www.sun.com/cddl/cddl.html
  12. */
  13. /**
  14. *
  15. * How to read user input from the command line
  16. * useful for a cli script whoch needs user input
  17. * You need some input validation to make it "save"
  18. *
  19. * This Example reads user input until the user inputs a . at a single new line.
  20. * This .\n terminates the read process. The termination is not stored in the $input variable
  21. */
  22. $fp = fopen('php://stdin', 'r');
  23. $last_line = false;
  24. $input = '';
  25. while (!$last_line) {
  26. $next_line = fgets($fp, 1024); // read the special file to get the user input from keyboard
  27. if (".\n" == $next_line) {
  28. $last_line = true;
  29. } else {
  30. $input .= $next_line;
  31. }
  32. }
  33. ?>