0

Possible Duplicate:
.htaccess rewrite image file to php script

How can I execute a PHP script when a user visits a page/file that is not a PHP file?

For example, if they visited a .css file, how would I make it so that I could execute php code before they got access to it?

Community
  • 1
  • 1
Max Hudson
  • 9,961
  • 14
  • 57
  • 107

2 Answers2

1

This is a more simplistic approach, but you can have PHP output the CSS and configure the server to parse CSS files as PHP files:

So, if you're using Apache, you'd do something like this:

AddType application/x-httpd-php .css

Then, in your CSS file, do this:

<?php
// Code to execute because user is accessing CSS file

// Output CSS below here
header("Content-type: text/css"); 
?>
body {
}
nickb
  • 59,313
  • 13
  • 108
  • 143
0

Instead of adding handlers to your non php files which implies that apache would try to parse them as php and may find errors (such as XML files that have <?xml?> declarations) you could do the following:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]        # if URI is not index
    RewriteCond %{REQUEST_FILENAME} !-f   # and URI is not file on disk
    RewriteCond %{REQUEST_FILENAME} !-d   # and URI is not directory on disk
    RewriteRule . /index.php [L]          # redirect to index
</IfModule>

Redirect all traffic for non-existing URI to your main application bootstrap usually index.php.

And adapt the above by adding a rule only for a specific (set of) file(s) to be redirected even though they do exists. After you redirect you check $_SERVER['REQUEST_URI'] and find out where the request originally came from and if it's your css file you fopen the file, read it process it then echo its processed contents to the user.

This approach protects the file from being downloaded.

Mihai Stancu
  • 15,848
  • 2
  • 33
  • 51
  • It will only be dealing with CSS, HTML, JavaScript, and image files. Does this still apply? – Max Hudson Jun 28 '12 at 04:09
  • If you do want all HTML/CSS/JavaScript files to have PHP logic then the other solution with `AddType` is easier, if you specifically don't want Apache to try and execute every HTML/CSS/JavaScript as PHP because only a few of the HTML/CSS/JavaScript files will be having the PHP logic, then this solution is better – Mihai Stancu Jun 28 '12 at 05:52