6 jun
2017

Best practice: where to put the PHP code?

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.

So I do:

<?php
include("somefile.inc");
function bla()
{
    ...
}

if (fails)
    echo "Error: ...<br />";

?>
<!DOCTYPE>
<html>
    <head>
        <script>
            ...
            <?php echo $someString; ?>
            ...
        </script>
    </head>
    <body>
        ...
    </body>
</html>

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:

<!DOCTYPE>
<html>
    <head>
        <script>
            ...
            <?php echo $someString; ?>
            ...
        </script>
    </head>
    <body>
        <div class="error_block">
            <?php
            include("somefile.inc");
            function bla()
            {
                ...
            }

            if (fails)
                echo "Error: ...<br />";

            ?>
        </div>

        ...

    </body>
</html>

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.

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.

Anyone can give their 2 cents on this issue? Thanks.

COMENTARIOS

DEJA TU COMENTARIO

© 2017 website by Rubit Corporation