Reading Data from Keyboard in PHP
How To Read Data from Keyboard (Standard Input) in PHP?
If you want to read data from the standard input, usually the keyboard, you can use the fopen("php://stdin") function. It creates a special file handle linking to the standard input, and returns the file handle. Once the standard input is opened to a file handle, you can use fgets() to read one line at a time from the standard input like a regular file. Remember fgets() also includes "\n" at the end of the returning string. Here is a PHP script example on how to read from standard input:
<?php $stdin = fopen("php://stdin", "r"); print("What's your name?\n"); $name = fgets($stdin); print("Hello $name!\n"); fclose($stdin); ?>
This script will print:
What's your name? Leo Hello Leo !
"!" is showing on the next line, because $name includes "\n" returned by fgets(). You can use rtrim() to remove "\n".
If you are using your script in a Web page, there is no standard input.
If you don't want to open the standard input as a file handle yourself, you can use the constant STDIN predefined by PHP as the file handle for standard input.
2016-11-24, 330👍, 0💬
How To Insert Rows Based on SELECT Statements in PHP? If want to insert rows into a table based on d...
How To Connect to MySQL from a PHP Script in PHP? If you want access the MySQL server, you must crea...
Why Do You Need to Filter Out Empty Files in PHP? When you are processing uploaded files, you need t...
How To Support Multiple-Page Forms in PHP? If you have a long form with a lots of fields, you may wa...
How To Generate and Process a Form with the Same Script in PHP? In previous exercises, a Web form is...