Php unable to load .pdf file from database, file contents stored in mysql database

I wrote code in php that will echo a PDF file. When I try to repeat this PDF file, the browser page turns gray and a download icon appears in the lower left corner, after which it does not show this pdf file.

that I can assure that the code before receiving data from the database is ideal. No error or error. After receiving the data, I used the following headers to echo this file. I am not sure about these headings.

$mimetype = 'application/pdf'; $disposition = 'attachment'; header('Content-type: $mimetype'); header('Content-Disposition: inline; filename="$question"'); header('Content-Transfer-Encoding: binary'); header('Content-length: ' . strlen($question)); header('Accept-Ranges: bytes'); echo "$question"; 

NOTE. I used the .pdf extension in content-decposition.but, but it didn't do me any good. The readfile () function was also used, and that also did not help me. Can someone tell me what is wrong there?

+4
source share
1 answer

The main reason page is changing into gray colors is because the browser cannot correctly determine the type of content.

Try the following:

 header("Content-type: $mimetype"); header('Content-Disposition: inline; filename="'.$question.'"'); // Filename should be there, not the content 

Instead:

 header('Content-type: $mimetype'); header('Content-Disposition: inline; filename="$question"'); 

It seems that you have invalid quotes, so the content type is not specified correctly.

EDIT

To clear, let's say $question is binary PDF content.
Here is what your code should look like:

 header('Content-type: application/pdf'); header('Content-Disposition: inline; filename=anything.pdf'); header('Content-Transfer-Encoding: binary'); echo $question; 

ERRORS DEVELOPING

Discuss the source code and your mistakes.

 $mimetype = 'application/pdf'; $disposition = 'attachment'; // First error: you have single quotes here. So output is 'Content-type: $mimetype' instead of the 'Content-type: application/pdf' header('Content-type: $mimetype'); // Second error. Quotes again. Additionally, $question is CONTENT of your PDF, why is it here? header('Content-Disposition: inline; filename="$question"'); header('Content-Transfer-Encoding: binary'); // Also bad: strlen() for binary content? What for? header('Content-length: ' . strlen($question)); header('Accept-Ranges: bytes'); echo "$question"; 

ONE MORE EDITING

I have another request ... I want to change the file name to $ year.pdf .. $ year can have values ​​like 2007 .. how can I do this?

Try the following:

 $year = '2013'; // Assign value header('Content-Disposition: inline; filename='.$year.'.pdf'); 

Instead:

 header('Content-Disposition: inline; filename=anything.pdf'); 
+6
source

Source: https://habr.com/ru/post/1469270/


All Articles