Search code examples
phpheadinject

Manipulate HTML page via PHP


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.


Solution

  • 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