phpshtml

How to run shtml include in php


I have dozens of .shtml files on the server which include this statement to include .inc files:

 <!--#include virtual="../v4/rightmenu.inc" -->

This is exactly how it shows on the source which is working just fine.

I am wondering whether I can run this on my php code without changing it since the current files has this kind of inclusion a lot and I don't want to mess with a lot of code like this one.

I just don't want to change it to something like <?php include "../v4/rightmenu.inc"; ?>


Solution

  • Use mod_rewrite to route all requests to .shtml files through a single php file. For exapmle: _includeParser.php

    A very rough sketch of such a file could be:

    /**
     * This function should return the contents of the included file
     */
    function getIncludeFileContents($match) {
        list (, $file) = $match;
        // return something for $file
    }
    
    /**
     * This function should return a php-readable path for the initially requested .shtml file
     */
    function getRealpath($uri) {
      // return the real path of the requested uri
    }
    
    // Map the requested uri to file
    // 'REDIRECT_URL' could be something different for your configuration, have a look at the $_SERVER array
    // to get the correct value if something fails here
    $realpath = getRealpath($_SERVER['REDIRECT_URL']); 
    
    // parse each include statement
    // the regex pattern here could need some tweaking
    $output = preg_replace_callback(
      '@<!--#include virtual="(.+?)" -->@i',
      'getIncludeFileContents',
      file_get_contents($realpath)
    );
    
    // output the final contents
    echo $output;
    

    Of course a solution like this could be optimized by some caching or other methods.