0

I am extracting some info from a database using MySQL, I'm sending the result to an Ajax function, and then I display the result on a web page.

Here is my PHP code:

        $views = $connection->execute("SELECT profilePic FROM users");
        foreach($views as $views)
        {
            echo "<tr><td><img src='".$views['profilePic']."' /></td></tr>";
        }

The warning "Headers already sent" appears because of this part of the code:

<img src='".$views['profilePic']."' />

Which looks like this when parsed:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPgAAAD4CAYAAADB0SsLAAAgAElE [TRUNCATED] ..." >

If I remove the img part, there is no warning:

    $views = $connection->execute("SELECT profilePic FROM users");
    foreach($views as $views)
    {
        //this throws no warning:
        echo "<tr><td></td></tr>";
    }

Who exactly is triggering the warning? What rule is being applied?

SamHecquet
  • 1,818
  • 4
  • 19
  • 26
andreini
  • 188
  • 1
  • 3
  • 17
  • The rule is very very simple. You cannot send any output before sending headers. That's it. There's nothing more to it. Use [output buffering](http://php.net/manual/ro/function.ob-start.php) if you want to send output at a later state. Or simply store any output in a variable and send it after sending the headers. – Andrei Nov 22 '17 at 09:27
  • @Andrew That's what I thought initially, but why isn't the warning triggering when I only send echo "" ? That's what baffles me. – andreini Nov 22 '17 at 09:50

1 Answers1

2

If your PHP Code is from your Controller the "echo" causing the warning. You have to do everything that outputs HTML code in your view template.

$this->set(compact('views'));

This makes your views Array available in your functions view template.

ndm
  • 59,784
  • 9
  • 71
  • 110
  • The code is in the Controller, yes. But when I only echo "" there is no warning. Only when I add the img part. – andreini Nov 22 '17 at 09:53
  • 1
    @niandrei Because you have PHP output buffering enabled, and the image string exceeds the buffers size, which causes it to be flushed, ie output is being generated, while that short string does fit into the buffer, and is being kept there until CakePHPs response emitter sends the response. Long story short, [**controllers should _never_ echo data**](https://stackoverflow.com/questions/42816125/cakephp-3-4-2-testing-posts-response-always-returning-null/42819969#42819969). – ndm Nov 22 '17 at 15:12
  • Thank you so much for the explanation @ndm ! – andreini Nov 22 '17 at 15:25