【问题标题】:How in .htaccess do I return the file requested but then run a PHP script?如何在 .htaccess 中返回请求的文件,然后运行 ​​PHP 脚本?
【发布时间】:2017-08-07 18:54:03
【问题描述】:

我想要做的是收集播客的下载数据。当请求剧集的 .mp3 文件时,我想将其跟踪到我的 Google Analytics 帐户。

我发现 Stack Overflow 文章展示了如何将请求重定向到 PHP 脚本,该脚本跟踪数据到 Google Analytics,然后返回 .mp3 文件,但是,由于某种原因,这在 Safari 和 iOS 中中断(但仍然有效)在 Chrome 中)。

这是我用于 .htaccess 文件的内容:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule (.*).(mp3) download.php?file=$1.$2 [R,L]
</IfModule>
# END WordPress

所以我想知道是否有办法编写我的 .htaccess 文件以正常返回文件,然后调用我的 download.php 脚本,该脚本将只处理 Google Analytics 跟踪,如果它因任何原因失败不会干扰收听文件的人。

谢谢!

【问题讨论】:

    标签: php apache .htaccess mp3


    【解决方案1】:

    您可以尝试设置一个脚本,该脚本使用Measurement Protocol(可能使用 cURL)将数据发送到 Google Analytics(分析)服务器端,并为文件提供适当的标头,以便不涉及重定向。

    下载.php:

    <?php
    
    $filename = $_GET['file'];
    
    $data = array('v'=>'1',
                  'tid'=>'UA-XXXXX-Y',
                  'cid'=>'555',
                  't'=>'event',
                  'ec'=>'sound'
                  'ea'=>'download'
                  'el'=>$filename);
    $url = 'https://google-analytics.com/collect';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    
    if(file_exists($filename)) {
        header('Content-Type: audio/mpeg');
        header('Content-Disposition: filename="test.mp3"');
        header('Content-length: '.filesize($filename));
        header('Cache-Control: no-cache');
        header("Content-Transfer-Encoding: chunked"); 
    
        readfile($filename);
    } else {
        header("HTTP/1.0 404 Not Found");
    }
    

    或者,您可以尝试使用 cron 作业脚本解析 apache 访问日志,但这似乎很消耗内存且过于复杂。

    编辑:我添加了 GAMP 代码并将语法更改为更积极

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-03
      • 2014-05-16
      • 1970-01-01
      • 2017-05-29
      相关资源
      最近更新 更多