Hiding HTML In Command Line PHP

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.

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.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
3 + 2 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.