douzhi7754 2015-12-26 16:05
浏览 64

使用php从mysql下载页面获取PDF文件

I made a php page which supported pdf file download. Each pdf file brought from mysql server. However, I met a problem the files which I downloaded the php page wrong file and I can't open. However, its file size were equal to the original files from mysql server and I can open them.

How can I fix this problem??

hear are my php code.

</head>
<?php

session_start();
require_once 'login.php';
$db_server = mysql_connect($db_hostname,$db_username,$db_password);

if(!$db_server) die("Unable to connect to MySQL: ".mysql_error());

mysql_query("set session character_set_connection=utf8;");
mysql_query("set session character_set_results=utf8;");
mysql_query("set session character_set_client=utf8;");

mysql_select_db($db_database)
or die("Unable to select database : " .mysql_error());
$row=0;

$doc_id=$_GET["q"];
$User_ID=$_SESSION["user_id"];
$User_type=$_SESSION["user_type"];

$sql = "Select `title`, `file` From Original_Reports Where `document_id` = '".$doc_id."';";
$results = mysql_query($sql);

$filename = mysql_result($results, 0, 0);
$filedata = mysql_result($results, 0, 1);
$mimetype = 'application/pdf';
$fileSize = filesize($filedata);

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: $mimetype");
$header="Content-Disposition: attachment; filename=".$filename.";";
//$header="Content-Disposition: download; filename=".$filename.";";
header($header);
header("Content-Transfer-Encoding: binary");
header("Content-length: ".$fileSize);
// @readfile($filedata);
echo $filedata;
?>
  • 写回答

1条回答 默认 最新

  • doulao3078 2015-12-26 16:20
    关注

    The issue is withthe following line:

    $filedata = mysql_result($results, 1);
    

    This code tries to get the 1st field from the 2nd record of the resultset. You are looking up the record based on the id, you are not going to have a 2nd record in your resultset. Change your code to:

    $filedata = mysql_result($results, 0, 1);
    

    to fetch the 2nd field from the 1st record of the resultset.

    Some additional advice:

    • mysql module has been deprecated, use mysqli or pdo instead
    • always check the return value of database calls to handle errors
    评论

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画