Writing PHP in <head>

17,570

Solution 1

No, storing PHP variables in the head is not the proper way to do it. In fact, when you do this, your variables are NOT stored inside the head, PHP is server side, HTML/CSS/Javascript are client side.

You want to store your variables before there is even any HTML that is outputted.

However, if you do something like this :

<head>
    <title>PHP Head Test</title>
    <?php $data; ?>
</head>

It's not actually doing anything, if you wanted to display it, you would use echo. This code does absolutely nothing except declare $data if it wasn't declared before-hand.

Generally, you should have most of your PHP code out of your HTML file, they should be in completely different files and the PHP code should include the HTML file. In this case, the PHP code that you put in the HTML file will have access to all PHP variables that were available in the file where it was included.

Solution 2

I am planning to use PHP to store preprocessed MySQL data into a variable to use in Javascript. Is the the proper place to store these values?

just do something like that;

<script>
    function Myfunction() {
        var myVariableGeneratedByPhp = <?php echo $data; ?>;
        // use your variable here
    }
</script>
Share:
17,570
projeqht
Author by

projeqht

Software Developer &amp; Trance DJ

Updated on June 17, 2022

Comments

  • projeqht
    projeqht almost 2 years

    Is it valid to store PHP variables/values inside the <head> tag? Are there any disadvantages or advantages to writing PHP with HTML in this format? Does it even matter?

    I sampled the following code as direct input through the W3C Validator:

    <!DOCTYPE html> 
    <html>
    <head>
      <title>PHP Head Test</title>
      <?php $data; ?>
    </head>
    </html>
    

    And I get 1 error:

    Line 5, Column 4: Saw <?. Probable cause: Attempt to use an XML processing instruction in HTML. (XML processing instructions are not supported in HTML.)
    <?php $data; ?>
    

    But I'm guessing that's because it's validating an .html file that has php code in it.

    I am planning to use PHP to store preprocessed MySQL data into a variable to use in Javascript. Is the <head> the proper place to store these values?

    NOTE: I am not trying to print out data in the head, that would be silly. I am asking about storing preprocessed data from MySQL to PHP (to be used in Javascript) in the <head>.