Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php require_once or include inside HTML head tag does not put the code inside head but in body

Tags:

php

I want to share the content of my HTML head tag among several pages but I am facing a weird error when I use require_once inside a HTML head tag. Let me explain better.

If I have the next code:

<!DOCTYPE html>
<html>
<head>
    <title>Datos Soluciones Informáticas</title>        
        <meta charset="UTF-8">
        <link rel="stylesheet" href="/css/main.css">
</head>

and I inspect the code, everthing looks as expected.

enter image description here

However, If I move the content of my head tag to a external file /snippets/head.php

<meta charset="UTF-8">
<link rel="stylesheet" href="/css/main.css">

And then write in my index.php file the next code:

<!DOCTYPE html>
<html>
<head>
    <title>Datos Soluciones Informáticas</title>        
    <?php require_once('/snippets/head.php'); ?>    
</head>

The inspect shows that the code is not inserted in the proper place:

enter image description here

It is not just the problem that the inspect does not work but the page does not behave as expected. I have the same issue with include instead require_once

The raw output obtained with view-source:localhost in chrome looks good but the page is not rendered well

<!DOCTYPE html>
<html>
<head>
    <title>Datos Soluciones Informáticas</title>        
    <meta charset="UTF-8">
<link rel="stylesheet" href="/css/main.css">
</head>
<body>

I am using Xampp 6.1 Build 7601 in a Windows 7 machine as my local environment.

Does anyone knows what I am missing?

like image 749
Sergio del Amo Avatar asked Dec 27 '22 09:12

Sergio del Amo


1 Answers

Another shot:

Does your included file start with an invisible byte order mark (BOM)? Then remove it by setting the proper character encoding.

See http://php.net/manual/en/function.include.php which contains this comment:

AVOID ZERO BYTE ORDER MARK!

I was having problems with include/require (once or not). I created an include-opening.php which had the initial structure of the page, and then included this page in all other pages. The result was looking "crashed", so I did compare including or just pasting the html code into the page. The hardcoded version displayed ok, even with the source code being exactly the same.

So I opened the include file with notepad++ and set the encoding to UTF-8 (no BOM) and voila, everything is working great now.

like image 133
Eric Avatar answered Jan 25 '23 23:01

Eric