强制下载文件php后保存在目录中?

时间:2014-07-11 08:50:47

标签: php mysql csv download vps

我正在创建一个包含公司业务数量的大型mysql数据库。 我最终能够创建代码,允许将结果保存为名为“/ uploads”的特定目录中的csv。一切正常。现在我需要一个按钮,在查询和保存csv文件之后下载文件。

代码是这样的:

 <?php
include 'includes/connection.php';

if(isset($_POST['submit']))
{
$cap = $_POST ['cap'];
$prov = $_POST ['provincia'];
$citta = $_POST ['citta'];


$filename = 'uploads/'.strtotime ("now").'.csv';

$sql = mysql_query("SELECT * FROM business_total  WHERE cap LIKE'%$cap%' AND provincia LIKE '%$prov%' AND citta LIKE '%$citta%'") or die(mysql_error());
$num_rows = mysql_num_rows($sql);
echo 'totale risultato: '.'<b>'.$num_rows.'</b>'.'<br/>';
if($num_rows >= 1)
{

$row = mysql_fetch_assoc($sql);
$fp = fopen($filename,"w"); 

$seperator = "";
$comma = "";

//$name è la prima righa, quella dei valori
foreach($row as $name => $value)
{
    $seperator.= $comma.''.str_replace('','""',$name);
    $comma =",";

}
$seperator .="\n";

fputs($fp,$seperator);
mysql_data_seek($sql, 0);

//Primo row per le testate, questo row per il contenuto query

while($row = mysql_fetch_assoc($sql))
{

$seperator = "";
$comma = "";

//$name è la prima righa, quella dei valori
foreach($row as $name => $value)
{
    $seperator.= $comma.''.str_replace('','""',$value);
    $comma =",";

}
$seperator .="\n";


fputs($fp,$seperator);
}
fclose($fp);




}
else
{
echo 'Non ci sono risultati compatibili con la tua ricerca';
}




}



?>

 <HTML>
  <head>


 </head>

 <body>
  <br>
  <br>
  <br>
  <br>
  <form method="post" action="index.php">


 <input type="text" name="cap" placeholder="Cerca per cap"/><br>
  <input type="text" name="provincia" placeholder="Cerca per prov"/><br>
  <input type="text" name="citta" placeholder="Cerca per citta"/><br>
   <input type="submit" name="submit" value="submit"/>



 </form>






  </body>


   </HTML>      

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。 在php关闭标记之前添加了这篇文章(?&gt;) 这是代码:

                        $qfile = $filename;


                        echo $qfile;



                if (file_exists($qfile)) {
                    header('Content-Description: File Transfer');
                    header('Content-Type: application/octet-stream');
                    header('Content-Disposition: attachment; filename='.basename($qfile));
                    header('Expires: 0');
                    header('Cache-Control: must-revalidate');
                    header('Pragma: public');
                    header('Content-Length: ' . filesize($qfile));
                    readfile($qfile);
                    exit;
    }







 ?>