2012-03-30 92 views
2

我有一个小型网站,其中有几个PDF可供免费下载。我使用StatCounter来观察页面加载的数量。它也显示我的PDF下载数量,但它只考虑用户点击我网站链接的下载量。但是,如何通过“外部”访问PDF(例如直接从Google搜索)?我如何计算这些?有没有可能使用像StatCounter这样的工具?在服务器上访问文件(例如PDF)的次数

谢谢。

+1

如果你使用Apache的重定向* .pdf请求与mod_rewrite到一个PHP脚本。增加计数器,然后读取实际的PDF内容并将其发送到浏览器。 – strkol 2012-03-30 11:01:08

+0

@strkol谢谢!你能举个例子说明这个重定向命令应该是这样吗? – Ivan 2012-03-30 11:14:05

回答

1

的.htaccess(重定向的* .pdf请求的download.php):

RewriteEngine On 
RewriteRule \.pdf$ /download.php 

的download.php:

<?php 
$url = $_SERVER['REQUEST_URI']; 
if (!preg_match('/([a-z0-9_-]+)\.pdf$/', $url, $r) || !file_exists($r[1] . '.pdf')) { 
    header('HTTP/1.0 404 Not Found'); 
    echo "File not found."; 
    exit(0); 
} 

$filename = $r[1] . '.pdf'; 
// [do you statistics here] 
header('Content-type: application/pdf'); 
header("Content-Disposition: attachment; filename=\"$filename\""); 
readfile($filename); 
?> 
0

您将不得不创建一种方法来捕获来自服务器的请求。

如果您使用的是php,最好的方法是使用mod_rewrite。 如果您使用.net,一个HttpHandler。

您必须处理该请求,调用statcounter,然后将pdf内容发送给用户。

1

您可以使用来检查文件被访问的次数。如果他们提供访问日志和日志分析软件的访问权限,请询问您的托管服务提供商

1
在PHP

,它会是这样的(未经测试):

$db = mysql_connect(...); 
$file = $_GET['file']; 
$allowed_files = {...}; // or check in database 
if (in_array($file, $allowed_files) && file_exists($file)) { 
    header('Content-Description: File Transfer'); 
    header('Content-Type: application/pdf'); 
    header('Content-Disposition: attachment; filename='.basename($file)); 
    header('Content-Transfer-Encoding: binary'); 
    header('Expires: 0'); 
    header('Cache-Control: must-revalidate'); 
    header('Pragma: public'); 
    header('Content-Length: ' . filesize($file)); 
    ob_clean(); 
    flush(); 
    mysql_query('UPDATE files SET count = count + 1 WHERE file="' . $file . '"') 

    readfile($file); 
    exit; 
} else { 
    /* issue a 404, or redirect to a not-found page */ 
} 
+0

尽管使用PDO或参数化查询会更好,并且使用mod_rewrite而不是GET变量,因此URL对用户而言看起来更自然。 – 2012-03-30 11:34:14