In PHP programming, the header() function is a very common tool used to send raw HTTP header information to the client, such as setting redirection, specifying content type, cache control, etc. However, can the header() function still work when we run the PHP script in mode? This article will give you a detailed answer.
First, we need to understand what the PHP CLI pattern is. CLI (Command Line Interface) is to run PHP scripts directly through the command line, rather than parsing them through a web server (such as Apache and Nginx). Usually we enter:
php script.php
In this case, PHP no longer acts as a tool for generating web pages, but is just a normal script executor.
The main function of the header() function is to send HTTP header information to the client (browser), such as:
header('Location: https://m66.net/welcome');
exit;
This code will tell the browser to redirect to the specified URL.
But note: header() does not output the actual content, it just modifies the response header . In other words, its role is entirely dependent on the HTTP protocol between PHP and the Web server.
Direct answer: It cannot be used, or it doesn’t make sense if you use it .
The reasons are as follows:
In CLI mode, PHP directly writes the output to standard output (stdout), without HTTP protocol, no request header, and no response header.
The header() function internally checks whether it is running in an environment with SAPI (Server API) cli . If so, it will not generate a real HTTP header when calling, and will not report an error, but the result is just that it has no effect on stdout.
For example, run the following code:
<?php
header('Content-Type: application/json');
echo json_encode(['status' => 'ok']);
In a web environment, the browser receives the Content-Type header and recognizes it as JSON. But run under the CLI:
php script.php
You will only see the output:
{"status":"ok"}
Because the terminal does not understand or handle HTTP headers at all.
To summarize:
? The call to header() under CLI will not report an error, but it is equivalent to an invalid operation.
? No HTTP response headers are sent because the CLI does not have an HTTP layer.
? You can continue to use echo , print_r and other functions to output text to the terminal.
If you also call header() when writing CLI scripts, it is recommended:
Confirm whether the code serves both the Web and the CLI. If so, it is best to add SAPI detection: