使用href到两个链接(PHP和一个网页)

using href to two links(php and a webpage)

本文关键字:一个 网页 PHP 两个 href 使用 链接      更新时间:2023-09-26
While($enreg=mysql_fetch_array($res))
{
   $link_d.="<a href='"$enreg[link]'" target='"_blank'"><font color='"red'">clic here to download</font></a></td>"
}

我想使用 href 所以它会导致下载链接,也将 id 发送到 PHP 文件,这样我就可以得到文件被下载了多少次!我们如何将href用于多个链接!

你不能。 一个链接只能指向一个资源。

相反,你应该做的是让你的PHP脚本重定向到该文件。 该链接指向带有计数器的 PHP 脚本,然后设置一个 Location: 标头(自动设置重定向的 302 状态代码(,其值是要重定向到的 URL。

此外,您应该在 HTML 上下文中使用的任何变量数据周围使用 htmlspecialchars(),以确保生成有效的 HTML。

理想情况下,您会进行一些检查以查看它是否是人工下载(网络爬虫可能会触发它 - 我们将在链接中放置no-follow,这将有所帮助(。您也可以使用数据库,但这会变得更加复杂。我的首选方法是使用Google Analytics Events。但这里有一个简单的PHP脚本,可以满足您的需求,而不需要其他解决方案的复杂性。

首先修改您的链接以使用跟踪器脚本并 urlencode

$link_d.= '<a style="color:red" href="tracker.php?url='.urlencode($enreg[link]).'" target="_blank">click here to download</a>';

}

然后创建一个脚本来记录下载(跟踪器.php(

 <?php
// keep stats in a file - you can change the path to have it be below server root
// or just use a secret name - must be writeable by server
$statsfile = 'stats.txt';
// only do something if there is a url
if(isset($_GET['url'])) {
  //decode it
  $url = urldecode($_GET['url']);
  // Do whatever check you want here to see if it's a valud link - you can add a regex for a URL for example
  if(strpos($url, 'http') != -1) {
    // load current data into an array
    $lines = file($statsfile);
    // parse array into something useable by php
    $stats = array();
    foreach($lines as $line) {
      $bits = explode('|', $line);
      $stats[(string)$bits[0]] = (int)$bits[1];
    }
    // see if there is an entry already
    if(!isset($stats[$url])) {
      // no so let's add it with a count of 1
      $stats[$url] = 1;
    } else {
      // yes let's increment
      $stats[$url]++;
    }
    // get a blank string to write to file
    $data = null;
    // get our array into some human readabke format
    foreach($stats as $url => $count) {
      $data .= $url.'|'.$count."'n";
    }
    // and write to file
    file_put_contents($statsfile, $data);
  }
  // now redirect to file
  header('Location: ' . $url);
}

你不能。

锚点旨在导致一个资源。

您要执行的操作是通过使用计算命中并重定向到资源的中间脚本来提示解决。

例如。

<a href="redirect.php?id=42">Click here to download</a>

重定向.php

// Increment for example, a database :
// UPDATE downloads SET hits = (hits + 1) WHERE id=42
// Get the URI
// SELECT uri FROM downloads WHERE id=42
// Redirect to the URI
// (You may also need to set Content-type header for file downloads)
header( "Location: $uri" );

您可以通过将 uri 作为第二个参数传递来优化这一点,这样你就不需要在重定向时获取它。

<a href="redirect.php?id=42&uri=/files/example.pdf">Click here to download</a>

收集此类统计信息的另一种方法是使用统计提供商提供的一些JavaScript工具,例如Google Analytics或Piwik,向click事件添加侦听器。

它对您的基本代码的侵入性较小,但不会让您轻松地在站点中重用收集的数据(例如,如果您想显示"热门下载"列表(。

例如,使用

下载脚本创建一个文件download.php并通过它路由所有下载。在此页面中更新计数器并使用适当的标题进行下载。

例如:

网址可能download.php?id=1&file=yourfile

download.php

//get id and file
//database operation to update your count
//headers for download