Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take user input like prompt() but in PHP?

Tags:

text

php

input

How can I make a PHP input thing like prompt('example prompt') in javascript?

Not like a form, like a prompt().

like image 235
user3397425 Avatar asked Mar 09 '14 02:03

user3397425


People also ask

How do I prompt a user in PHP?

Prompting users for input To get input from users, you also have to prompt them to enter something. You can use PHP's `readline() function to get this input from the console.

How can I get input field value in PHP without form?

If you don't want to submit a form, the only two other ways of accomplishing this are to click a link with the data as query parameters in the url, or use AJAX to send the data to the server in the background.

How can get input field value in PHP variable?

In order to get an input value, you can use the htmlspecialchars() method and $_REQUEST variable. Note: The htmlspecialchars() method functions by converting special characters to HTML entities. The $_REQUEST variable is a built-in PHP variable that functions by getting data from the input field.

What is readline PHP?

Method 1: Using readline() function is a built-in function in PHP. This function is used to read console input.


2 Answers

Solution #1: Prompt for get input inside of anywhere code:

<?php
echo "What do you want to input? ";
$input = rtrim(fgets(STDIN));
echo "I got it:\n" . $input;

Sample output:

# php test.php
What do you want to input? Hello, I'm here!
I got it:
Hello, I'm here!

Solution #2: If you want get input in firstly inline when run php:

<?php
$input = $argv[1];
echo "I got it:\n" . $input;

Sample output:

# php test.php "Hello, I'm here!"
I got it:
Hello, I'm here!

Extra tips:

If you want to integrate CLI and WEB inputs, you can use this magic code:

<?php
if (PHP_SAPI === 'cli') parse_str(implode('&', array_slice($argv, 1)), $_GET);
var_dump($_GET);

And now write for use under CLI:

# php sample.php user=nabikaz website=nabi.ir

And follow the normal routine for the WEB:

http://localhost/sample.php?user=nabikaz&website=nabi.ir

Without defining the number and name of inputs.
Both have the same result. ;-)

array(2) {
  ["user"]=>
  string(7) "nabikaz"
  ["website"]=>
  string(7) "nabi.ir"
}
like image 71
Nabi K.A.Z. Avatar answered Sep 17 '22 19:09

Nabi K.A.Z.


You can't take input in the middle of php execution since it finishes before the page is actually shown to the user. However, you can get input using HTML and receive that using php. Here's a really basic example:

<?php
    echo $_POST['value'];
?>
<form method="post" action="">
<input type="text" name="value">
<input type="submit">
</form>

It takes the user input and reloads the page. Then, it echoes what the input was.

like image 32
Anonymous Avatar answered Sep 19 '22 19:09

Anonymous