Is it possible to add php code to html page w/o converting the page to php?

I believe there is, but I don’t know it.
When I changed sites over from html file to php, I used a redirect in the htaccess to send any request for pages with the html extension to ones with the php extension:-

RedirectMatch 301 (.*)\.html$$1.php

That should take care of any back-links you already have, and open new possibilities for the site with all that php can do.
As an alternative, if all you need to do is change the year, it could be done with a little simple javascript.

1 Like

Your server needs to know which pages to pass through the PHP pre-processor (or through any other pre-processor, come to that). That’s what the .php extension is for. Whilst it is (I think) possible to instruct the server to pass .html files through the PHP pre-processor, you’d have to be nuts to do so.

I do recall reading about that, so I think it’s possible. But I don’t remember exactly how, because I took the other route and used php extensions instead. That seemed to logical way to proceed. The redirect took care of any links and the indexes while they updated.


Thank you for your post.

Your suggestion seems like the way to go if I want to have my cake and eat it too. I am about one step above n00b in regards php, but will happily try to work this out. I’m also sure the world will not come to an end if my back-links break, but it would be an embarrassment to say the least.

I appreciate your help.


I hear you on the ‘nuts’ aspect of this, so I don’t think I’ll be trying to do that.

Thanks for your post.

1 Like

That’s only my view. You’ll probably get more comments in the coming hours…

Instead of doing that I just added the following line to my .htaccess so that files with a .html extension get parsed for PHP as if they had a .php extension

AddHandler application/x-httpd-php .html

A bigger concern than backlinks for me would be the SE indexes, as they will take a while to update to your new page structure.
So when you appear on someone’s SERP it may link to which will give a 404 error, and that can be bad for business.
Fortunately, the redirect in the htaccess should solve the problem for both SERPS and backlinks.

Another strategy you may consider since you are making a change, is to go for an extension agnostic structure, where every page is index.php or index.html but in its own meaningfully named directory. So the url will be something like That way the extension could be absolutely anything or change to anything else in the future, and not make the slightest difference to your URLs, links or indexing.

When you realise the power of what php can do for you and the site, it can become addictive.


Most Cms and Frameworks use three lines in a .htaccess file to redirect all urls to a common file, usually index.php. The common file validates the url, extension, case sensitivity, etc and redirects to the specific request. Regardless of the possible url variations, a nearest match web-page is generated with a meta canonical reference to the preferred web-page url and possibly a 301 http response status code.

As an example, try the following link

  1. With no extension
  2. Another extension such as .html, .php, .tom, .dick or…
  3. Change case of “superman” to “SUPERMAN”, “SuperMan”, etc
  4. A numeric database table column id = 967
  5. A numeric reference, 967 preceded and/or followed by words separated with left slash separators.
  6. With or without www prefix

In each case, view the source code and notice the SEO friendly, canonical reference.

When back on the desktop the unique id will be supplied.

Added database table column id record = 967
Current site is a backup because of a recent MySQL hiccup. Hopefully, today will be up to date with the live search text box, etc

An alternative way is using rewrite rules:

RewriteEngine On
RewriteRule (.+)\.html$ $1.php

in a .htaccess file. Which method will work depends on the server configuration.

1 Like

That will work for directing links to old “.html” pages to their similarly named “.php” pages.

If there are a lot of “.html” files, there may be a way to change the extensions to “.php” in bulk.
I am likely remembering incorrectly, but I vaguely recall mention that VIM or some CLI app could do it easily.

If not, what I would do is the AddHandler first and then once they were all “.php” do the Rewrite 301 until all the old URLs died away.

Yes, indeed, with the rewrite method the files would need to be renamed to the .php extension.

Why Rewrite 301? I think the goal here is to retain the .html URLs intact. In any case I think the .php extension doesn’t make sense to be part of the public URLs and it’s more elegant to leave them with .html. This should be an internal technical change not visible to the outside world.

1 Like

I was intrigued as to what was involved so wrote the following which requires testing.

I have tested it locally and onlne it works fine, also can see online demo [color=blue]Here[/color]

Three files are required and source for each file is shown online when “Home” is selected.

File: .htaccess

 relocates all URLs to index.php

File: index.php

# Has ONE-OFF  
1. copies all HTML files in source directory 
2. to PHP directory
3. renames all .html files to .php

File: funcs.php

// Debug ONLY - renders arrays with line-feeds
function fred( $val )

//  Only required ONCE
//  copies and renames HTML files to PHP
//      $src to $dst // source to destination
function copyHtml2Php( $src, $dst )

//  return URL without ext
function showRequestNoExt()

//  Cosmetic Only - required for Demo
//  renders relevant .php page with menu
function getMenu($page)

Source Files:



RewriteEngine on
# RewriteBase /

DirectoryIndex index.php index.html index.htm research_002.html

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?$1 [L] 

# last line


error_reporting(-1); ini_set('display_errors','1');

# Essential
    require 'funcs.php';

#    copy all .html files to new directory 
#    and change extension
  $src  = 'htmlfiles/'; // with a trailing slash
  $dst  = 'phpfiles/';  // with a trailing slash
  $copy = false;
  if( $copy )
      copyHtml2Php( $src, $dst );

# show web-page request
    #echo '<br>$page: ', 
    $pageName = showRequestNoExt();

# validate request
    # echo '<br>page: ',
    $pageName = $dst .$pageName .'.php';

# Maybe show page    
    # echo strpos('index', $page);
    if( file_exists($pageName) && strpos($pageName,'index') )
        echo $contents = file_get_contents($pageName);
        // header('Location: ' .$page);

        # Show menu
        if('index' !== $pageName) 
            echo getMenu($pageName);
            echo '<h3>Yes we have no ' .$pageName .'</h3>';
    }// last line



// DEBUG Only - renders arrays with line-feeds
function fred($val)
    echo '<pre>';
    echo '</pre>';

//  Only required ONCE
//  copies and renames HTML files to PHP
//      $src to $dst // source to destination
function copyHtml2Php( $src, $dst )
      $htmlFiles = glob('*.html');
     // fred($htmlFiles);

  if( count($htmlFiles) )
      $ok = is_dir($dst) ? NULL :  mkdir( $dst, 0777, true);
      // echo '>>>' .$ok .'<<<';

      foreach( $htmlFiles as $file)
          // echo '<br>'.$file;
          // echo '<br>',
          $newPhpFile = str_replace('.html', '.php', $file);

          // echo '<br>',
          $srcFile = $src .$file;
          $tmpFile = $dst .$file;
          $newPhpFile = str_replace('.html', '.php',$tmpFile);

          if( ! file_exists($newPhpFile))
              $ok = copy($srcFile, $newPhpFile);
              # echo '<br> >>>' .$ok .'<<<';
          }    //==============================================


//    Extract URL and remove extension
function showRequestNoExt()
    $result = NULL;

    // echo '<br>$result: ',    
        $result = $_SERVER['REQUEST_URI'];

    // echo '<br>$lastSlash: ',    
        $lastSlash = strrpos($result, '/');

    // echo '<br>$page: ',
        $webPage = substr($result, 1+$lastSlash);
        if( empty($webPage) ) {
            // echo 'NO Web-Page';
            // echo '<br>',    
            $result = strstr($webPage, '.', TRUE);
            // echo '<br>';    

    return $result;

//  Cosmetic Only - required for Demo
function getMenu($page)
    $title = 'Is it possible to add PHP code to HTML Pages';
    $sp    = '';
//$file  = strstr(__FILE__, 'downloads/');
    $file  = $_SERVER['QUERY_STRING'];
    $srv   = print_r($_SERVER,1);
    $src   = empty($file) ? '' : 'display:none;';
    $funcs = highlight_file('funcs.php', 1);
    $index = highlight_file('index.php', 1);
    $htacc = highlight_file('.htaccess', 1);

$result = '<!DOCTYPE html><html lang="en-us">
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="viewport"     content="width=device-width, initial-scale=1"/>
<title>' .$title .'</title>
#main   {background:#f0f0f0; color:#333; margin:0; padding:0;}
div, h1 {background:#333; color:snow;}
a       {color:snow;}
h2 a    {float:left; color:#00f; padding:2em;}
.bgs    {color:snow;}
.clb    {clear:both;}
dl      {margin:0 0 2em 4.2em;}  
dl dt   {font-size: 1.42em; font-weight:700;}
dl dd   {color:blue; min-height:1.42em;}
.flr    {float:right;}
.mga    {margin: auto;} .mg4 {margin: 4.2em 0 0}
.src    {width:88%; margin:2em auto; background-color:#fff; color:#000;
           border:solid 1px #000; padding: 0.42em; fo-weight:700;}
.src    {' .$src .'}
.tac    {text-align:center;}  
.w88    {width:88%;}    .w99 {width:100%;}        
<div class="fll; wid99 mga">
    <div class="flr bgs"><a href="' .$sp .'">SitePoint Forum</a></div>
    <h1 class="clb">' .$title .'</h1>
<hr class="clb" />
. '<dt>URL:</dt><dd>'  .$file .'</dd>' 
. '<dt>File:</dt><dd>' .$page .'</dd>' 
. '<dt>Date:</dt><dd>' .date("Y M D - H:i:s") .'</dd>'

<div id="main" class="w88 mga tac">
    <h2> <a href="index.php"> Home </a> </h2>
    <h2> <a href="tom.html"> tom.html </a> </h2>
    <h2> <a href="dick.html"> dick.html </a> </h2>
    <h2> <a href="harry.html"> harry.html </a> </h2>

<div id="footer" class="clb mg4">
    <h5>footer goes here</h5>

<div class="src">Source: <b> .htaccess</b><br /><hr />'
<div class="src">Source: <b>index.php</b><br /><hr />'
<div class="src">Source: <b>funcs.php</b><br /><hr />'

return $result;
// last line

I believe the latest trend is to remove all extensions both for security reasons and to make SEO simpler with less clutter.

Perhaps php is overkill for one very simple thing and we are over-complicating things.

<script>var today=new Date(); year=today.getFullYear(); document.write(year);</script>
1 Like

that call is for Netscape 4 and earlier and should never be used with more modern browsers such as IE4.

Also using JavaScript means it doesn’t display when JavaScript is turned off.

A simple one line addition to the .htaccess is all that is needed to turn on PHP for .html files so doing that is even simpler than using JavaScript.

As old as that, wow. I took that snippet of code from what I used to have before moving from html to php, some time ago. Don’t recall where I found it, just that it seemed to work.

it does in certain limited situations if you jumble the JavaScript in with the HTML. It doesn’t work if you keep the JavaScript separate as is possible (and recommended) in all the browsers released after Netscape 4.

I used document.write() until I switched to XHTML and Firefox complained about it.

When I researched the problem it was an “OMG I’m that far behind” moment. And that was years ago.

I spread myself thin and it has become more difficult, if not impossible, to keep up with even one technology let alone the many I have interest in.

At first the createElement() , setAttribute() and appendChild() et al. seemed more verbose than was needed, but now I am comfortable with it and it comes naturally.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.