3

I wrote a PHP script and I'm trying to read user input from the command line. I started of with

$myVar = exec('read myVar; echo $myVar;');

which worked fine, but when typing the input the arrow keys didn't work the way it should. I learned that this could be solved with the -e switch, so it became:

$myVar = exec('read -e myVar; echo $myVar;'); 

Now this worked like a charm in my development envionment but unfortunately it seems like in our production environment PHP doesn't use a bash shell and doesn't support the -e switch, and it's probably not easy to change this.

According to the third answer to this question one can force PHP to use bash, so it became:

$myVar = exec('/bin/bash -c "read -e myVar; echo $myVar"');

Now, unfortunately this doesn't work as the variable myVar is not set.

When I run the commands directly from the command line $myVar (the shell variable) is set with whatever my input is, and consequently echo'ed

However when using the -c option, either in a PHP-exec() or directly on the command line like this:

/bin/bash -c "read -e myVar; echo $myVar";

$myVar isn't set at all, and an empty string (or whatever was the previous value of $myVar) is echo'ed

What do I do wrong here?

3
  • 1
    Have you considered using readline()? Commented Oct 1, 2015 at 13:27
  • Yes, I did. And quit trying after I found out that it wasn't supported on my development environment, however indeed it works fine on production, so I think I'll just have to make that work on development, or could even go with a 'function_exists()' switch for the time being. So thanks, kind of forgot about that. Still makes me wonder though how the above doesn't work. Commented Oct 1, 2015 at 13:41
  • Are you developing against a different version of PHP than what you have on production? Commented Oct 1, 2015 at 14:26

2 Answers 2

0

The issue is that $myVar is being interpreted before being passed to bash. The following will work by escaping the $ before it's passed to the shell:

/bin/bash -c "read -e myVar; echo \$myVar"

Also you can shorten it a little by making use of $REPLY

/bin/bash -c "read -e; echo \$REPLY"

Sign up to request clarification or add additional context in comments.

2 Comments

That's just it! Thanks :-)
No problem @btum81 :-)
0

The command you are using is correct. The solution is to use the correct escape sequence:

$myVar = exec ('/bin/bash -c \'read -e myVar; echo $myVar \'');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.