如何使用php脚本下载特定文件(csv)

时间:2015-03-03 06:25:30

标签: php csv downloading

我从php脚本生成每日报告,它位于文件夹中,如下所示

report_2015_02_15.csv
report_2015_02_16.csv
report_2015_02_17.csv
report_2015_02_18.csv
report_2015_02_19.csv

我向用户发送一封包含下载链接的电子邮件,一旦他们点击下载链接,下载脚本就会触发并准备下载。它目前将所有文件放入一个数组中对其进行排序并找到最新的下载文件,

此方法有一个流程,即使您转到2周大的电子邮件并点击下载链接,它也会为您提供最新报告,而不是提供两周的旧报告。

那么有人可以告诉我一种方法来发送我的电子邮件中的下载链接与其相应的文件的关系吗?

电子邮件脚本

$down_link = Config_Reader::readProjectConfig('tad')->base_url.'CSVDownload.php;

$mail = new Zend_Mail ();
$sentFromEmail = $config->sentFromrec;
$tr = new Zend_Mail_Transport_Sendmail ( '-f' . $sentFromEmail );
Zend_Mail::setDefaultTransport ( $tr );
$mail->setReturnPath($sentFromEmail);
$mail->setFrom ( $sentFromEmail, 'Reporting' );

$email_body = "Hi,<br /><br />Download the weekly details of adtracker projects, by clicking the link below.
<br /> <a href=".$down_link.">Report</a><br /><br />Thank You.";

$mail->setBodyHtml ( $email_body );
$mail->addTo ( $weeklyReportRec);
$mail->setSubject ( "Report" );

try {
        $mail->send ();
    } catch ( Exception $e ) {
        echo "Mail sending failed.\n";
    }

下载脚本

$basePath = "$download/dailyReport/";
$csvFiles = glob($basePath."/*.csv");
if(count($csvFiles)){
    array_multisort($csvFiles, SORT_DESC);
    $csvFile = $csvFiles[0];
}else{
    exit("Server error!");
}

$h = fopen($csvFile, "r");
$contents = fread($h, filesize($csvFile));

2 个答案:

答案 0 :(得分:0)

您可以在下载链接上使用指示报告日期的查询参数。 ... / CSCDownload.php?日期= 2015/2月17日

这将允许您从可用列表中选择相应的报告。

答案 1 :(得分:0)

你可以使用像这样的东西作为下载脚本。我做了最小的修改才能让它发挥作用:

$date = $_GET['date'];
$basePath = "$download/dailyReport/";
$csvFiles = glob($basePath."/*.csv");

$file = $basePath . 'report_' . $date . '.csv';
$found = false;

foreach($csvFiles as $csvFile){
    if($file === $csvFile){
        $found = $csvFile;
        // You have found the file, so you can stop searching
        break;
    }
}
if(false === $found){
    exit("Server error!");
}

$h = fopen($found, "r");
$contents = fread($h, filesize($found));

现在您可以使用“example.com/getcsvfile.php?date=2015_02_15”在浏览器中调用脚本而不必担心注入,因为您检查文件是否是csv文件之一。