0
0
PhpHow-ToBeginner · 3 min read

How to Run PHP from Command Line: Simple Guide

To run PHP from the command line, use the php command followed by the script filename, like php script.php. This executes the PHP code directly in your terminal without a web server.
📐

Syntax

The basic syntax to run a PHP script from the command line is:

  • php: The command to run the PHP interpreter.
  • script.php: The PHP file you want to execute.
  • Optional arguments can be added after the filename.
bash
php script.php
💻

Example

This example shows a simple PHP script that prints a message. Running it from the command line will display the message in the terminal.

php
<?php
// script.php
echo "Hello from PHP command line!\n";
Output
Hello from PHP command line!
⚠️

Common Pitfalls

Common mistakes when running PHP from the command line include:

  • Not having PHP installed or not added to your system's PATH, causing php command not found errors.
  • Running the script without the php command (e.g., just typing the filename).
  • Forgetting to add \n for new lines in output, making terminal output hard to read.
bash
# Wrong: running script without php command
# $ ./script.php

# Right: run with php command
# $ php script.php
📊

Quick Reference

Tips for running PHP scripts from the command line:

  • Use php -v to check your PHP version.
  • Run scripts with php filename.php.
  • Add #!/usr/bin/env php at the top of scripts and make them executable to run directly on Unix systems.
  • Use php -a for interactive shell mode.

Key Takeaways

Use the command php script.php to run PHP scripts from the terminal.
Make sure PHP is installed and added to your system PATH to use the php command.
Add newline characters \n in your PHP output for clear terminal display.
Use php -v to verify PHP installation and version quickly.
For Unix, add a shebang line to run PHP scripts directly as executables.