简体   繁体   中英

PDF file from mysql download page using php

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;
?>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM