Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP PHP Basics Daily Exercise Program Combining Strings

Brian Patterson
Brian Patterson
19,588 Points

Prompt for user input

Just a general question. How do you prompt the user for input in php? Like asking for their name. Then saying welcome so and so. Any help would be appreciated.

4 Answers

Greg Kaleka
Greg Kaleka
39,019 Points

Hi Brian,

I assume you're talking about console interaction, like the gets method in Ruby.

You want the readline() function in PHP. Works essentially the same way.

Example:

  • On a Mac, run php -a in the terminal to open an interactive shell.
  • Type echo "Hello, " . readline("What's your name? ");
  • You will be asked "What is your name?", and then php will echo "Hello, [your name]"

Hope this answers your question!

Cheers :beers:

-Greg

Henrik Christensen
seal-mask
.a{fill-rule:evenodd;}techdegree
Henrik Christensen
Python Web Development Techdegree Student 38,322 Points

Quoting stackoverflow:

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

https://stackoverflow.com/questions/22277633/how-to-take-user-input-like-prompt-but-in-php

Brian Patterson
Brian Patterson
19,588 Points

So is there no such thing as a gets method in PHP like there is in Ruby.

Greg Kaleka
Greg Kaleka
39,019 Points

There is an almost identical method in PHP! It's readline in PHP. See my answer above. Henrik is right for web page display, but I don't believe Ruby's gets works in the middle of web page display either. I assume you're talking about console interaction.

Henrik Christensen
seal-mask
.a{fill-rule:evenodd;}techdegree
Henrik Christensen
Python Web Development Techdegree Student 38,322 Points

I don't think so - the only way to get a users input (like prompt()) is to make a form and then get the entered value (like the example in the link I posted.

Sharif Ahmed
Sharif Ahmed
11,629 Points

<?php

$firstName = "Rasmus"; $lastName = "Lerdorf"; $fullName = "$firstName $lastName";

echo "$fullName was the original creator of PHP\n";

?>

The error message i get is 'Bummer: I do not see a period.' Any idea what's wrong guys???

Sharif Ahmed
Sharif Ahmed
11,629 Points

I missed a full stop at the end of the statement XD