Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute in PHP interactive mode

I am new to PHP, and I just wanted to run PHP in a command prompt (interactive mode).

So I typed this code:

`php -v` `<?php` `echo 7;` `?>` 

But I do not know how to execute it, because when I press Enter cmd expects me to continue writing the code. I searched on php.net and some other forums, but I didn't find anything. So is there a function key or something to display the result?

like image 904
Abhishek Mhatre Avatar asked Jun 30 '13 15:06

Abhishek Mhatre


People also ask

How do I run PHP interactive shell?

The CLI SAPI provides an interactive shell using the -a option if PHP is compiled with the --with-readline option. As of PHP 7.1. 0 the interactive shell is also available on Windows, if the readline extension is enabled. Using the interactive shell you are able to type PHP code and have it executed directly.

Does PHP have a REPL?

PHP has a REPL; if you haven't used it yet, run php –a in a terminal. This will take you to the interactive PHP prompt at which you can enter your code. All programming language REPLs work essentially the same way.

What is CLI PHP?

PHP's Command Line Interface (CLI) allows you to execute PHP scripts when logged in to your server through SSH. ServerPilot installs multiple versions of PHP on your server so there are multiple PHP executables available to run.


Video Answer


2 Answers

If following your command with Ctrl + D isn't working, you probably don't have Interactive Shell (which apparently gives input after each line). That requires compiling php with special options. But if php -a says interactive mode, you can type directly into it and send Ctrl + Z at the end of the file.

php -a interactive mode enabled  <?php echo "hello there world!"; phpinfo(); ?> ^Z 

(Hit enter)

hello there world! phpinfo.... 

There's more information in the comments in the PHP comments.

like image 53
Josiah Avatar answered Sep 23 '22 11:09

Josiah


Ctrl+d will trigger an end-of-file condition and cause the script to be executed.

See also How does the interactive php shell work?

Interactive Shell and Interactive Mode are not the same thing, despite the similar names and functionality.

If you type php -a and get a response of 'Interactive Shell' followed by a php> prompt, you have interactive shell available (PHP was compiled with readline support). If instead you get a response of 'Interactive mode enabled', you DO NOT have interactive shell available and this article does not apply to you.

So if you get only "Interactive mode enabled", then you'll only be able to type in PHP code and then when you're done, send PHP an EOF to execute it.

"EOF" means "end-of-file".

like image 32
jayhendren Avatar answered Sep 19 '22 11:09

jayhendren