PHP can run in two main ways: from the command line or through a web server. Knowing the difference helps you choose the right way to run your PHP code.
0
0
PHP CLI vs web server execution
Introduction
You want to run a quick script without opening a browser.
You need to run background tasks or scheduled jobs.
You are building a website that users access through a browser.
You want to test PHP code quickly on your computer.
You want to handle web requests and show web pages.
Syntax
PHP
php script.php # Run PHP script from command line
// Or access PHP file via web server URL like http://localhost/script.phpPHP CLI means running PHP scripts directly in the terminal or command prompt.
Web server execution means PHP runs when a user visits a web page through a browser.
Examples
This script prints a message when run from the command line.
PHP
<?php // CLI example echo "Hello from CLI!\n";
This script shows a message when accessed via a browser.
PHP
<?php // Web server example echo "Hello from web server!";
Sample Program
This program detects if PHP is running from the command line or through a web server and prints a message accordingly.
PHP
<?php if (php_sapi_name() == 'cli') { echo "Running in CLI mode\n"; } else { echo "Running in web server mode"; }
OutputSuccess
Important Notes
CLI scripts do not have access to web server variables like $_SERVER['HTTP_HOST'].
Web server execution can handle HTTP requests and send HTML responses.
Use CLI for scripts that do not need a browser, like automation or maintenance tasks.
Summary
PHP CLI runs scripts directly in the terminal without a browser.
Web server execution runs PHP when users visit web pages.
Choose CLI for command-line tasks and web server mode for websites.