10

I'm debugging a PHP script that runs a couple SQL queries and emails a set of users. I'm sure this is a very basic thing, but every time I try to echo, print, or print_r it doesn't appear while running the script.

So say I have this in the script:

print("This should print");
echo "on the command line";

When I run the script via command line php script.php it doesn't actually print anything to the command line while running the script.

Is there a way of having PHP print to console? I feel like I'm missing something extremely basic here.

AlbertEngelB
  • 16,016
  • 15
  • 66
  • 93
  • 3
    That code should work just fine assuming there is no code executed earlier that closes stdout or redirects it e.g. to a file or enables an output buffer. – ThiefMaster Dec 05 '13 at 14:23
  • php -c index.php http://php.net/manual/en/install.windows.commandline.php – gvgvgvijayan Dec 05 '13 at 14:25
  • Possible duplicate of http://stackoverflow.com/questions/4323411/php-write-to-console – Anvesh Dec 05 '13 at 14:25
  • @ThiefMaster It would seem that printing variables isn't handled the way I'm used to. Printing strings work fine, whoops! – AlbertEngelB Dec 05 '13 at 14:27
  • As recommended by answers, `flush()` could solve your problem but there is a simpler solution: just add a new line character (`"\n"`) at the end of your messages. It is the magic that automatically triggers a flushing of the console. – axiac Jul 29 '18 at 21:56

4 Answers4

4

A good approach could be:

function log($message)
{
    $message = date("H:i:s") . " - $message - ".PHP_EOL;
    print($message);
    flush();
    ob_flush();
}

It will output to your terminal each line you call. Just use :

log("Something");
log("Another line");
Tiago Gouvêa
  • 15,036
  • 4
  • 75
  • 81
3

Thats the method of doing it.

Things to check for are output buffering http://php.net/manual/en/function.ob-flush.php

Is that code actually being run ? Make sure it doesnt branch before it gets there

exussum
  • 18,275
  • 8
  • 32
  • 65
2

The following code working fine for me.

<?php
    print("This should print");
    echo "on the command line";
?>

with tags.

Anvesh
  • 91
  • 10
2

I know it is old, but I am going post my own solution to this just in case if someone would run into similar situation. I had a problem that a legacy command line PHP script wouldn't print or echo anything to the terminal when DSN is incorrectly configured and the script got stuck for very long time (not sure how long, never waited for it to terminate by itself). After putting ob_end_flush() in the entry line of the script, the output came back to the terminal. So it turned out that all output was buffered and since the script stuck at some point, the output stayed buffered and so never went to the terminal.

geliba187
  • 357
  • 2
  • 11