如何在下载后重定向到链接页面

时间:2015-05-09 12:10:08

标签: php

我正在使用一个简单的downloadcounter来计算txt文件中的下载量。 在 downloads 文件夹中,我有一个名为 download.php 的文件,其中包含以下代码:

<?php
$Down=$_GET['Down'];
?>

<html>
<head>
<meta http-equiv="refresh" content="0;url=<?php echo $Down; ?>"> 
</head>
<body>

<?php

$filePath = $Down.".txt";

// If file exists, read current count from it, otherwise, initialize it to 0
$count = file_exists($filePath) ? file_get_contents($filePath) : 0;

// Increment the count and overwrite the file, writing the new value
file_put_contents($filePath, ++$count);

// Display current download count
echo "Downloads:" . $count;

?> 

</body>
</html>

我使用的链接位于downloads文件夹之外的文件中,如下所示:

<a href="downloads/download.php?Down=download.zip">Download</a>

到目前为止,此工作正常。 点击链接后,网址会给我:http://localhost/downloads/download.php?Down=download.zip并下载zip文件。

我想要实现的目标:立即重定向回链接页面;我在 download.php

中的回声后添加了标题位置
// Display current download count
//echo "Downloads:" . $count;
header('Location: http://localhost/link.php');

现在他马上回来了,他在文本文件中以1递增,但不再下载zip文件了。 为什么重定向后文件不再下载?

3 个答案:

答案 0 :(得分:3)

主要方法是首先转到“之后”页面,然后开始下载。在您的情况下,您希望将用户重定向到link.php,因此您需要首先将页面重定向到link.php,其中应该包含带有您真实下载网址的html刷新meta-equiv标记。将下载该文件,不会影响当前页面。

由于您的前后页面相同,您可以使用link.php?download=true传递参数。如果下载为true,则打印meta-equiv标记。

我希望你能得到基本的想法。

答案 1 :(得分:2)

请尝试以下操作来下载文件。

**var nsq = require('nsqjs');
var r = require('rethinkdb');
var nsqdd = (process.env.NSQD_RETH || "localhost:4161").split(",");
var connection = null;
r.connect( {host: 'localhost', port: 28015, db:'test', authKey:''}, function(err, conn) {
    if (err) throw err;
    connection = conn;
})
var eventreader;
eventreader = new nsq.Reader('ev_topic', 'ev_channel', {
    lookupdHTTPAddresses: nsqdd
});
eventreader.connect();
eventreader.on('message', function (msg) {
    r.table('rethinkdb_test').insert(msg.json()).run(conn);
    console.log('Received message [%s]: %s', msg.id, msg.body.toString());
    msg.finish();
});**

答案 2 :(得分:1)

我使用了另一种方法,用户点击下载链接页面上的链接,而不离开当前页面,计数器实时递增。因此无需重定向到另一个或相同的页面,因为文件是透明计算的,无需离开当前页面。下载计数器imho应该是透明的,因此它更安全,没有人应该直接访问php脚本。另请注意,我首选的方法是使用文件扩展名来限制操作,因此用户只能下载某些文件,还要注意更好的方法是使用.htaccess拦截匹配的文件并将它们传递给php脚本...最后我还集成到了我的项目jquery所以计数器通过ajax实时更新...所以没有必要重新加载页面来查看结果......

.htaccess(位于root / files /中)

RewriteEngine on
RewriteRule ^(.*).(rar|zip)$ /php/doing_download.php?file=$1.$2 [R,L]

doing_download.php(位于root / php中)

<?php
  $downloads_folder = $_SERVER['DOCUMENT_ROOT'] . '/files/';
  $counters_folder = $_SERVER['DOCUMENT_ROOT'] . '/files/counter/';
  if (!empty($_GET['file'])) {
    $file = basename($_GET['file']);
    $type = array("zip", "rar");
    $exts = strtolower(substr(strrchr($file, "."), 1));
    if (!in_array($exts, $type)) {
      header("HTTP/1.0 403 Forbidden");
      exit('File not allowed!');
    } else {
      if (file_exists($downloads_folder . $file)) {
        if (file_exists($counters_folder . md5($file) . '_counter.txt')) {
          $fp = fopen($counters_folder . md5($file) . '_counter.txt', "r");
          $count = fread($fp, 1024);
          fclose($fp);
          $fp = fopen($counters_folder . md5($file) . '_counter.txt', "w");
          fwrite($fp, $count + 1);
          fclose($fp);
        } else {
          $fp = fopen($counters_folder . md5($file) . '_counter.txt', "w+");
          fwrite($fp, 1);
          fclose($fp);
        }
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $file . '"');
        header('Content-Transfer-Encoding: binary');
        header('Connection: Keep-Alive');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . sprintf("%u", filesize($downloads_folder . $file)));
        $fh = fopen($downloads_folder . $file, "rb");
        while (!feof($fh)) {
          echo fgets($fh);
          flush();
        }
        fclose($fh);
        exit;
      } else {
        header("HTTP/1.0 404 Not Found");
        exit('File not found!');
      }
    }
  }
?>

count_download.php(位于root / php /中)

<?php
  function get_download_count($file = null) {
    $counters = $_SERVER['DOCUMENT_ROOT'] . '/files/counter/';
    if ($file == null) return 0;
    $count = 0;
    if (file_exists($counters . md5($file) . '_counter.txt')) {
      $fp = fopen($counters . md5($file) . '_counter.txt', "r");
      $count = fread($fp, 1024);
      fclose($fp);
    } else {
      $fp = fopen($counters . md5($file) . '_counter.txt', "w+");
      fwrite($fp, $count);
      fclose($fp);
    }
    return $count;
  }
?>

call_download.php(位于root / php中)

<?php
  include($_SERVER["DOCUMENT_ROOT"] . "/php/count_download.php");
  $item['item1'] = get_download_count('exampleA.zip');
  $item['item2'] = get_download_count('exampleB.zip');
  echo json_encode($item);
?>

static_download.php(位于root / php中)

<?php
  include($_SERVER["DOCUMENT_ROOT"] . "/php/count_download.php");
  $item['item1'] = get_download_count('exampleA.zip');
  $item['item2'] = get_download_count('exampleB.zip');
?>

download.js(位于root / jsc /中)

$(document).ready(function() {
  $.ajaxSetup({cache: false});
  getStatus();
});
function getStatus() {
  $.getJSON('php/call_download.php', function(data) {
    $('#item1').html(data.item1);
    $('#item2').html(data.item2);
  });
  setTimeout("getStatus()",1000);
}

index.php(位于root /)

<?php include($_SERVER["DOCUMENT_ROOT"] . "/php/static_download.php"); ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Download Page</title>
<script type="text/javascript" src="jsc/jquery.min.js"></script>
<script type="text/javascript" src="jsc/download.js"></script>
</head>
<body>
File: <a href="files/exampleA.zip">exampleA.zip</a>&nbsp; - &nbsp;Downloaded <span id="item1"><?php echo $item['item1']; ?></span> Times<br />
File: <a href="files/exampleB.zip">exampleB.zip</a>&nbsp; - &nbsp;Downloaded <span id="item2"><?php echo $item['item2']; ?></span> Times<br />
File: <a href="test/test.zip">test.zip</a><!-- this file never will be counted since is located in other folder --><br />
</body>
</html>

Here, you can download all files and test them!

根据Lawrence Cherone和我的回答:https://stackoverflow.com/a/29105023/4432311

PS:您可能需要更改php脚本中的文件夹...我的脚本假设您正在服务器的根目录中进行测试...

相关问题