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!阅读原文】。感谢您的支持!

您可能感兴趣的

MAC下安装和配置memcache 本文记录了在MAC的OSX下为php安装和配置 memcache 的方法 OSX一般自带apache和php,不需要安装 安装服务端 memcache 是项目名,而在服务端的驻留进程叫 memcached (linux的守...
php实现百度音乐采集下载 简介: 支持 歌名+歌手 此方式下载,所以支持百度mp3(新歌TOP100、歌曲TOP500、经典老歌、热门对唱、相声小品荟萃、摇滚歌曲榜)下载。 在网上没找到php cli方式的下载百度mp3的脚本,很奇怪,php挺流行就...
Converts the generated date string javascript to a... everyone my problem is that my JS code generates date in format "Thu Jan 10 2013 00:00:00 GMT+0200 (FLE Standard Tim...
pfSense 2.4.3 发布,包含重要的安全修复补丁... pfSense 2.4.3 已发布,本次更新包含重要的安全修复和 bug 修复,还引入了一些新特性,具体如下。 值得关注的更新 包含一些重要的安全修复补丁: Kernel PTI mitigations for Me...
PHP | MySQL Database Introduction What is MySQL? MySQL is an open-source relational database management system (RDBMS). It is the most popular databa...