skip to Main Content

So, I have a PHP script that we’re going to call template.php, it has all the intelligence I need.

Today I have several files in a folder with names like name1.php, name2.php and others.
All these files have the same content: <?php include('template.php') ?>.

The intelligence of template.php uses the filename of the URL to distinguish one file from another.

The problem is that I have to create these files physically, inside the folder.

My question is (and I haven’t found anything out there): using .htaccess can I make the server run a script based on the URL with a template?

Example:

  • Assume the template.php file exists in the folder.
  • No other files are present in the folder.
  • Customer accesses www.example.com/name1.php or www.example.com/name2.php
  • .htaccess identifies the file and proceeds with executing the script based on template.php and the file name, such as name1.php or name2.php.

Can you give me an idea or point out where I can acquire more knowledge on the subject?

2

Answers


  1. I would point all traffic to template.php. Then within template.php you can do your execution, then in include the requested file (if it exists).

    You could do error handling before or after the execution of the template.php file depending on if you want it to execute based on whether or not the requested file exists.

    .htaccess would look something like:

    <IfModule mod_rewrite.c>
        RewriteBase /
        RewriteRule ^template.php$ - [L]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . /template.php [L]
    </IfModule>
    

    Then your template.php

    <?php
    #template.php execution code
    
    $requested_uri = $_SERVER['REQUEST_URI'];
    
    if( file_exists($requested_uri) ){
        include $requested_uri;
    }else{
        #404 or other error handling
    }
    
    Login or Signup to reply.
  2. You could add a condition to check so it is not the template.php file and rewrite to this file otherwise e.g:

    RewriteEngine on
    RewriteCond %{REQUEST_URI} !^/templates/template.php$ [NC]
    RewriteRule ^templates/(.*)$ /templates/template.php?name=$1 [L]
    

    Here we are sending the name of the requested file as a query string to the template.php file:

    <?php
    $requestedTemplateFileName = $_GET['name'] ?? 'default.php';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search