-2

Hello I have INCLUDED a PHP file in the end of an HTML page. Now I want to add a style file before the end of the tag HEAD. But I need to do this via this php file, I have no choice.

I have and index.php file and at the end of this file I am loading script.php I need to add a script in the header of index page using the script.php

Folder structure:

  • index.php
  • script.php

The index.php file have this code:

<!DOCTYPE html>

<html>
 something
</head>

<body>
   something
</body>
</html>
<?php 
   include "script.php"
?>

How can I put something in the head of the HTML/PHP when I have the script.php file at the end of a page.

Ignacio Correia
  • 3,611
  • 8
  • 39
  • 68

3 Answers3

1

There is no direct way to do this. I can think about 2 nasty workarounds for your problem though:

  1. If the script has buffering activated (called ob_start somewhere before HEAD was closed), you could get it as a string and clean it wirh ob_get_clean, then insert your code and ECHO it again. Could look like this:

    <?php
    $output = ob_get_clean();
    $output = substr_replace($output, $your_code, strpos($output, '</head>'), 0);
    echo $output;
    ?>
    
  2. Since modern browsers are quite forgiving, you actually can put style tags after the closing html and they will still work. I woudln't do this though, since it's bad habit

Felk
  • 7,720
  • 2
  • 35
  • 65
0

Create IF logic within your included PHP page, and then include it into both the HEAD and at the end of your HTML.

Within your HTML, set a variable before the HEAD's include, and then reset the same variable after the HEAD's include.

Regarding the IF logic, set it up so TRUE only runs the style sheet, and FALSE skips over the style sheet and runs the rest of the PHP script.

KiloVoltaire
  • 265
  • 3
  • 10
0

what you could do is this:

  • put ob_start(); at the start of your page or all pages.. ( i hope for you this is possible)
  • use ob_get_contents(); to get all the contents into a variable:
  • inject your code with a replace
  • clean the output buffer with ob_end_clean()
  • echo the modified code.

so this code will look like this:

<?php ob_start();
//a lot of your code and html here
$codeToInject="yourcode";
$content=ob_get_contents();
$content=str_replace("</head>",$codeToInject."</head>");
ob_end_clean();
echo $content;
?>

But be aware.. this is NOT the way to go. It will potentially slow down your page. Its not a clean way of coding, actually its tricking around. if possible you should reconcider refactoring your code in a way this is not needed.

Mark Smit
  • 582
  • 4
  • 12