Use php -r to execute inline PHP code without files, e.g., php -r "echo 'Hello, World!';". 2. Run a PHP file via php script.php. 3. Pass arguments accessible through $argv. 4. Make scripts executable with #!/usr/bin/env php and chmod +x. 5. Validate syntax with php -l.
If you want to execute PHP code or scripts from the command line, using the PHP CLI is a straightforward approach. Here are several methods to achieve this:
The operating environment of this tutorial: MacBook Pro, macOS Sonoma
The PHP command-line interface provides the -r option to run PHP code directly without creating a file. This is useful for quick tests or small operations.
Note: Do not include tags when using the -r flag.
You can execute a standalone PHP file by passing its path to the php command. This is the most common way to run PHP applications via CLI.
te to the directory containing the file using cd.PHP CLI allows passing arguments to scripts, which can be accessed via the $argv and $argc variables inside the script.
On Unix-like systems, you can make a PHP script executable by adding a shebang line at the top and setting file permissions.
This method treats the PHP script like a native shell script.
Before running a script, you can validate its syntax using the -l (lint) option to prevent runtime errors.
This is especially helpful when debugging large scripts or deploying code.