breakLine for cli script

I use this to set breakLine in my cron script, cron might be run web-based or via CLI.

if (PHP_SAPI != 'cli') {
    $br = "<br />";
} else {     
    $br = PHP_EOL;    
}

Is it fine cron script via cli? or should I have this?

if (PHP_SAPI != 'cli' || PHP_SAPI != "cli-server") {

Or better to have below?

if (!strstr(PHP_SAPI, 'cli' ) {

No answer yet please?

strpos would be better than strstr.

So you suggest for 3rd code block I gave above (with strops change), rather than 1st and 2nd code block above?

If it were me? Shorthand it.

$br = (strpos(PHP_SAPI,'cli') === FALSE) ? "<br />".PHP_EOL : PHP_EOL;

If this is not cli, why concatenate "<br />".PHP_EOL and why not just <br /> ?

Because your source code should look pretty too.

What is the difference of cli and cli-server? Is this the same thing on different servers?

cli-server is a script utilizing PHP’s inbuilt server (only available in PHP >= 5.4), designed for developmental and test purposes only - it’s not designed to replace a web server. It’s severely limited in functionality [1 request at a time, etc.]

I wouldn’t do this kind of thing at all because this piece of code implies you are going to output pieces of data - either to the browser or to CLI - and delimit them with line breaks. The problem is that when outputting to a browser you will need to run your data through htmlspecialchars() in order to be able to print all characters and avoid weird stuff going on when <, > or & is outputted (CLI doesn’t need this). Then you will have to have another PHP_SAPI condition somewhere else in your code and this logic will get scattered in different places.

I’d suggest doing it in 2 separate and independent steps - first prepare your text using simple \n newlines and then format it for desired output. For CLI: if PHP_EOL is \n you can output the text as it, otherwise you can replace \n with PHP_EOL. For HTML you run the text through nl2br(htmlspecialchars($text)) - this will ensure proper rendering of all characters and combinations of them (almost - in HTML you may need to add a white-space css rule if you want multiple spaces to be rendered like in CLI):

// $text uses \n as newlines
function outputText($text) {
  if (PHP_SAPI == 'cli') {
    if (PHP_EOL != "\n") {
      $text = str_replace("\n", PHP_EOL, $text);
    }
    echo $text;

  } else {
    echo nl2br(htmlspecialchars($text));
  }
}

Or, you can do it line by line:

// $line is one line of text excluding newline
function outputLine($line) {
  if (PHP_SAPI == 'cli') {
    echo $line . PHP_EOL;

  } else {
    echo htmlspecialchars($line) . "<br />\n";
  }
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.