title: Best practice: where to put the PHP code?
body: <p>I do admit this question is going to be a bit vague, but I will try to explain what I'm trying to accomplish by a few examples. I have some PHP code that loads a bunch of variables from the MySQL database, contains some declarations, some functions to quickly output HTML code etc. However I would love to do all that stuff before anything is sent to the client.</p>
  
  <p>So I do:</p>
  
  <pre><code>&lt;?php
  include("somefile.inc");
  function bla()
  {
      ...
  }
  
  if (fails)
      echo "Error: ...&lt;br /&gt;";
  
  ?&gt;
  &lt;!DOCTYPE&gt;
  &lt;html&gt;
      &lt;head&gt;
          &lt;script&gt;
              ...
              &lt;?php echo $someString; ?&gt;
              ...
          &lt;/script&gt;
      &lt;/head&gt;
      &lt;body&gt;
          ...
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>This is all fine and ok, until I get an error. The echo will not show in the browser because it's before all HTML... So I modified:</p>
  
  <pre><code>&lt;!DOCTYPE&gt;
  &lt;html&gt;
      &lt;head&gt;
          &lt;script&gt;
              ...
              &lt;?php echo $someString; ?&gt;
              ...
          &lt;/script&gt;
      &lt;/head&gt;
      &lt;body&gt;
          &lt;div class="error_block"&gt;
              &lt;?php
              include("somefile.inc");
              function bla()
              {
                  ...
              }
  
              if (fails)
                  echo "Error: ...&lt;br /&gt;";
  
              ?&gt;
          &lt;/div&gt;
  
          ...
  
      &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>Now I can actually see errors, which is good. But now the problem arises that in the header, or scrips, I cannot access variables that will be loaded later on in the newly created error_block.</p>
  
  <p>I really don't like splitting the code in the error_clock to some above the HTML document and some in the error_block. And I also don't want to use PHP's die() function which abrubtly ends the execution.</p>
  
  <p>Anyone can give their 2 cents on this issue? Thanks.</p>