W3docs

Execute a string of PHP code on the command line

To execute a string of PHP code on the command line, you can use the "php" command followed by the "-r" option and the string of code in quotes.

To execute a string of PHP code on the command line, you can use the "php" command followed by the "-r" option and the string of code in quotes. For example:

Example of executing a string of PHP code on the command line

php -r 'echo "Hello, world!";'

This will execute the code echo "Hello, world!"; and print Hello, world! to the console.

You can also save your PHP code in a file with the .php extension and then run the file via the command line with the php command followed by the file name, for example:

Example of saving and executing PHP code in a file with the .php extension in command line

php myfile.php

This will execute the code in myfile.php.

Note: When passing complex strings to the -r flag, you may need to escape internal quotes or carefully mix single and double quotes to prevent shell parsing errors.