Tell Apache whether or not to run PHP on requests

综合编程 2018-02-05 阅读原文

I am using PHP with Apache and wonder if there is a way to indicate from the client side that the requested PHP file shouldn't be executed/parsed. By standard, I want all PHP files to be executed when requested, but I want a way to indicate from the client side that the file should not be executed.

A nice solution would be to supply an extra header in the request using JavaScript and then write some code in a .htaccess
file to check if the header is present, and if it is tell apache to not execute the file and just serve it as text.

Using GET parameters or something else would also be okay.

Is this possible? If so, how?

supply an extra header in the request [using JavaScript] and then write some code in a .htaccess file to check if the header is present

You could get Apache to check for this (secret) header and internally rewrite the request to a viewAsSource.php
-type file that then reads the REQUEST_URI
(or a passed query string parameter) and returns the file source instead. Similar to @LucasKrupinski suggestion, except you don't need to include anything in the PHP file itself.

For example, in your root .htaccess
file:

RewriteEngine On

# Block direct access to any file in the /tools directory
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^tools/ - [F]

# Display PHP source...
RewriteCond %{HTTP:X-Action} ^display-source$
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule (.+.php)$ tools/display-source.php?url=$1 [L]

For all .php
requests this checks for the X-Action
HTTP request header having a value of "display-source" and that the requested file exists. If these conditions are met then the request is internally written to a /tools/display-source.php
script, passing the URL in the url
parameter. You could instead check the $_SERVER['REQUEST_URI']
superglobal, but note that this also includes any query string that is passed on the request.

Then, in display-source.php
, something like:

<?php
$url = isset($_GET['url']) ? $_GET['url'] : null;
if (isset($url)) {
    $file = $_SERVER['DOCUMENT_ROOT].'/'.$url;
    // Validate $file....
    // :
    highlight_file($file);
}
Hello, buddy!

责编内容by:Hello, buddy!阅读原文】。感谢您的支持!

您可能感兴趣的

Mongodb basics from php to node.js All over the net i cant find a good tutorial for mongodb basics with node....
Tips for Writing Better Performing PHP Code Should you use single quotes or double quotes when writing PHP? How about URL...
10位顶级PHP大师的开发原则 在Web开发世界里,PHP是最流行的语言之一,从PHP里,你能够很容易的找到你所需的脚本,遗憾的是,很少人会去用“最佳做法...
PHP SPL 原链接 http://www.ruanyifeng.com/blog/2008/07/php_spl_notes.html 首先建议去看...
Expressive 3 Alpha 3 2018-02-08 | By: Matthew Weier O'Phinney Today, we pushed the final ch...