Site logo
Authors
  • avatar Nguyễn Đức Xinh
    Name
    Nguyễn Đức Xinh
    Twitter
Published on
Published on

Detailed Guide on PHP Command Line (CLI) and Essential Commands for PHP Developers

The PHP command line interface (CLI) is a powerful tool for developers, enabling them to perform various tasks efficiently. Whether you're debugging, running scripts, automating tasks, managing servers or managing dependencies, mastering the PHP CLI can significantly enhance your productivity.

What is PHP Command Line Interface (CLI)?

The PHP CLI is a command-line interface for running PHP scripts directly in the terminal or command prompt. Unlike executing PHP code through a web server, the CLI enables developers to:

  • Run scripts without a web server.
  • Automate routine tasks.
  • Debug applications.
  • Test code snippets quickly.

PHP CLI making it ideal for automation, maintenance tasks, and debugging.

Benefits of Using PHP CLI

  • Performance: CLI scripts bypass the overhead of web servers, resulting in faster execution.
  • Automation: Useful for cron jobs, data processing, and system tasks.
  • Flexibility: Allows integration with other CLI tools and shell scripts.

How to Access PHP CLI

To access the PHP CLI, open your terminal and type:

php -v

This command displays the current PHP version installed on your system. If PHP is installed correctly, you should see the version details.

Common PHP Command Line Commands

1. Check PHP Version

To verify your PHP installation and version:

php -v

This command also provides additional information about PHP build date and configuration.

2. Run a PHP Script

You can execute PHP scripts directly from the command line:

php script.php
php -f script.php

Replace script.php with the path to your PHP file.

2. Runs a single line of PHP code

Runs a single line of PHP code without a script file

php -r 'echo "Hello World\n";'

3. Start a Built-in Web Server

For quick testing and development, PHP offers a built-in web server:

php -S <addr>:<port> [-t docroot] [router]

example:

php -S localhost:8000

php -S localhost:8000 -t public 

This command starts a simple web server. By default, it serves files from the current directory. You can specify a different directory or router script if needed.

4. Check PHP Configuration

To view detailed PHP configuration information:

php -i

This command outputs information similar to phpinfo() in a browser.

5. Test PHP Code with Interactive Shell

Use the interactive mode to test PHP code snippets quickly:

php -a

This opens an interactive shell where you can write and execute PHP code line by line. Type PHP code directly, press Enter and see immediate results:

echo "Sum 1 + 1 is: " . (1 + 1) . "\n";

5. PHP config

Provides build flags and configuration options for PHP extensions.

php-config
php -a

This opens an interactive shell where you can write and execute PHP code line by line.

6. Lint PHP Files

Check PHP files for syntax errors without executing them:

php -l script.php

This command checks the script for syntax errors and displays a message indicating whether the script is syntactically correct.

6. Strips comments and whitespace

Strips comments and whitespace from a PHP script

php -w filename.php

8. Execute Cron Jobs

PHP scripts can be executed as cron jobs to automate repetitive tasks:

* * * * * /usr/bin/php /path/to/your/script.php

Set the appropriate schedule and file path for your use case.

9. Debugging with PHP CLI

Use var_dump() or print_r() within scripts to output data to the terminal for debugging. For advanced debugging, consider tools like Xdebug:

php -dxdebug.mode=debug script.php

10. View Installed PHP Modules

To list all installed PHP extensions:

php -m

This helps in verifying required modules for your project.

Generating Code with phpize

phpize is a crucial tool for building PHP extensions. It creates the necessary files and directories for compiling and installing extensions.

cd extension_source_directory
phpize 
./configure 
make 
sudo make install

This sequence prepares the extension for compilation, configures it, builds the extension, and finally installs it into your PHP environment.

Writing CLI Scripts

Accessing Command-Line Arguments

Command-line arguments are accessible via the $argv array:

<?php
if ($argc > 1) {
    echo "Argument: " . $argv[1] . "\n";
} else {
    echo "No arguments provided.\n";
}

Run the script:

php script.php hello

Reading User Input

Use fgets() to read input:

<?php
echo "Enter your name: ";
$name = trim(fgets(STDIN));
echo "Hello, $name!\n";

Handling Output

Customize output with:

<?php
fwrite(STDOUT, "This is standard output\n");
fwrite(STDERR, "This is an error message\n");

Automating Tasks with PHP CLI

Creating Cron Jobs

Automate scripts using cron jobs on Linux:

  1. Open the crontab editor:

    crontab -e
    
  2. Add a cron job:

    * * * * * /usr/bin/php /path/to/script.php
    

Parsing and Processing Data

PHP CLI excels at handling data processing tasks:

<?php
$file = fopen("data.csv", "r");
while (($row = fgetcsv($file)) !== false) {
    print_r($row);
}
fclose($file);

Debugging with PHP CLI

Using var_dump() and print_r()

Debug PHP scripts by outputting variable details:

<?php
$data = ["key" => "value"];
var_dump($data);

Enabling Error Reporting

Run PHP scripts with full error reporting:

php -d display_errors=1 script.php

Tips for Optimizing PHP CLI Usage

Use Aliases

Create aliases for frequently used commands to save time. For example:

alias phps="php -S localhost:8000"

Combine Commands

You can chain commands with && for streamlined workflows:

php -l script.php && php script.php

Leverage Environment Variables

Set environment variables for custom configurations:

PHP_ENV=development php script.php

Conclusion

The PHP CLI is an indispensable tool for developers, offering extensive capabilities for running and managing scripts, debugging, and automating tasks. By mastering these commands, you can streamline your workflow and become a more efficient PHP developer.