PHP in interactive mode

php

 

Although PHP is specially designed to meet Web requests, it can also be run in a terminal prompt  through php cli. At the terminal, we can run it in different ways, and in this post we will see what they are.

Running a script by terminal:

To run a PHP script from the terminal, just run the command “php” followed by the path to the file to be executed.

 

Running a PHP code by terminal:

To run a PHP code through the terminal, just run the command “php” passing the “-r” parameter, followed by the command to be executed. Note that the command must be delimited by single or double quotes. You may not use the PHP code delimiters to delimit commands (like <? Php and?>), Although you can close it and open it again. Here’s an example:

This can be useful for performing rapid tests for the small terminal, without the need to create a script only to see the result.

One drawback is that if you use double quotes, and you want to run any command involving variables, you need to escape the “$” symbol. Also, if you want to use the same quotes used to delimit the command also needs to escape it, like this:

Note that we can execute more than one command. Simply enclose them by “;”.

Running a PHP code by interactive terminal:

To perform a sequence of PHP codes through the terminal, interactively, simply run the “php” passing the parameter “-a”.

When executing this command, a prompt will be shown in PHP, as shown below:

 

In PHP prompt, you can run PHP commands and the result is shown how a command is completely interpreted. In this case, we can create variables, run loops and print results more easily than the previous form (with “-r”). That’s because we don’t need to worry about escaping quotes and variables.

See an example of a loop executed at the interactive prompt:

 

Note that after adding the first line, we opened a key. With this, the PHP changes the prompt to “php {“. So we closed the keys, the third row inserted, PHP executes the entire block set.

To end the interactive mode, simply run the command “exit” or “quit”. Note that it is different from running the PHP command “exit (0);”. In this case, only the value being set is returned to the shell.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">