如何使用php输出一个js文件,并检测该文件是否被嵌入或直接打开


How to use php to outout an js file and detect if file was embed or open directly

如何使用php输出js文件并检测文件是否嵌入或直接连接我想用php输出一些js文件它很简单,就像:

header(Content-Type: text/javascript);

但我想知道这个文件是否嵌入了一个网页中,比如:

<script src='http://foo.com/foo.js'></script>

或直接在浏览器中打开http://foo.com/foo.js感谢

您无法区分接收端的差异。这两种情况下的请求都是相同的,web服务器将以完全相同的方式提供foo.js。如果控制嵌入javascript的HTML页面,则可以构建一个令牌/哈希方案(就像防止CSRF一样)来验证对文件的请求是否不是直接请求。例如:

<script src="http://foo.com/foogenerator.js.php?k=SOMERANDOMVALUE"></script>

然而,这样做的问题在于,它包括让PHP解析器生成javascript的开销,而不仅仅是由web服务器直接提供的静态文件。它也可能对浏览器缓存产生影响。

您可以使用.htaccess将请求重新路由到PHP文件,例如:(我没有测试它,但我认为它应该可以工作)

Options -MultiViews
RewriteEngine on
RewriteBase /
#if not a directory and ends in .js, then rewrite URL to /dir/js_handler.php and append the query string
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_URI} '.js$
RewriteRule ^(.+)$ /dir/js_handler.php [L,QSA]

.htaccess文件通常位于站点的根目录下,或者可以将其放在包含所有javascript文件的文件夹中。

然后在js_handler.php文件中,您可以进行某种检查
最简单(但不安全)的选择是:

if ($header['Referer']=='mydomain.com'){
    //it was requested by loading the HTML page
} else {
    //it was requested directly
}

要获得$header,请参阅本文
一个更彻底的方法是使用随机生成的访问密钥并对此进行验证。您可以让cron作业每隔五分钟左右生成一个新密钥,然后使用SQL或将其写入文件。例如:

$file_path = //some path
$randKey = generateRandomKey();
$keyArray = json_decode(file_get_contents($file_path),true);
$keyArray[1] = $keyArray[0];//move the first element to the 2nd.
$keyArray[0] = $randKey; //set the first element to $randKey
file_put_contents($file_path,json_encode($keyArray) );

然后,当你交付一个HTML页面时(假设你是通过PHP完成的):

<?php
    $keyArray = json_decode(file_get_contents($file_path),true);
    $randKey = $keyArray[0]; 
?>
<head>
    <script type="text/javascript" 
            src="/path/to/myscript.js?secret=<?=$randKey?> ></script>
</head>

然后在js_handler.php:中

$keyArray = json_decode(file_get_contents($file_path),true);
if (in_array($_GET['secret'],$keyArray){
    //deliver the js file
} else {
    //deliver 404 page
}

对于脚本的位置,请使用$_SERVER['REQUEST_URI']。您应该能够仅include javascript文件并让脚本终止。不过,您可能需要设置标题。我不完全确定,现在无法测试。