Hiding HTML In Command Line PHP

Tuesday, August 5, 2008 - 12:04

Printing out stuff with PHP is basically essential to any program, but problems can arise if you want to use the same script for command line scripting and web site scripting because of the need to print out HTML. The $_SERVER super global array contains a variable called SERVER_PROTOCOL, which contains the protocol that the client is using to access the script. If the client access through the web then the protocol will contain something like 'HTTP 1.1'. If the script is being run from the command line then this super global variable SERVER_PROTOCOL would exist.

It would therefore be possible to print out HTML or new line characters depending on if the protocol variable exists. The following function can be used instead of the print() function to print out an HTML <br /> tag when the SERVER_PROTOCOL variable exists and new lines when it is not present.

1
2
3
4
5
6
function printLine($string) {
if(isset($_SERVER['SERVER_PROTOCOL'])){
 print $string_message.'<br />';
}else{
 print $string_message."\n";
}

This can be used in the following manner, in a browser window:

printLine("Hello, world!"); // Hello, world!<br />

Or running on the command line (also known as the shell):

printLine("Hello, world!"); // Hello, world!\n

This code can be adapted to whatever you need to do.

Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Add new comment