Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I display a pdf retrieved using file_get_contents in php?

Tags:

php

pdf

I want to display, embedded in the HTML, a pdf file which is in a directory up to the document root.

Document root points to /var/www/web1/web and the pdf file is in /var//www/web1/docs/pdf, so I can't point it from the html.

I'm using PHP and I tried some suggestions like get_file_contents, base64_encode, .... but didn't worked.

All examples I find are to make download the pdf or to convert it into a jpg, but this is not what I need.

Any suggestions?

like image 220
Carlos Avatar asked Nov 26 '25 13:11

Carlos


1 Answers

Simply load the pdf content by a php page, we call it viewer.php, then embed the PHP page as it would be the document itself: <embed src="viewer.php" width="80%" height="900px" />

In the viewer.php file:

<?php
//Load file content
$pdf_content = file_get_contents('../unreachable_file_outside_webserver.pdf');
//Specify that the content has PDF Mime Type
header("Content-Type: application/pdf");
//Display it
echo $pdf_content;

Otherwise another solution for bigger files (easier on RAM due to bufferized read/output without storing content in RAM) use readfile

<?php
header("Content-Type: application/pdf");
readfile("../unreachable_file_outside_webserver.pdf");
like image 142
GrowingBrick Avatar answered Nov 28 '25 03:11

GrowingBrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!