David Jawphan David Jawphan - 6 months ago 29
Javascript Question

PHP - how to give path to read pdf?

Select file name and redirect..

index.php

<?php
$book_name = ["Jenkins_Essentials","Asterisk","phalcon"];
echo "<select><option selected>Book Name</option>";
foreach ($book_name as $key => $value) {
echo "<option name='$key'>$value</option>";
}
echo "</select>";
?>
<script type="text/javascript">
$(document).ready(function(){
$("select").on("change",function(){
location.href = "reading.php?title="+$(this).val();

});
});
</script>


reading.php

$title = $_GET["title"];
header("Content-type: application/pdf");
header('Content-Disposition: inline; filename="$title.pdf"');
@readfile('D:\Learning\$title.pdf');//this is my issue


When I redirected it show
Failed to load PDF document
..
My running script file location is as we know
C:\xampp\htdocs
But pdf file place is as shown in above
D:
drive !How to give path to it?

Answer

On your last two lines, PHP isn't including the $title variable, as you are using single quotes and you are using backslashes. Try one of these:

header('Content-Disposition: inline; filename="'.$title.'.pdf"');
@readfile('D:/Learning/'.$title.'.pdf');

or:

readfile("D:/Learning/$title.pdf");

Backslashes are used for escaping characters, so use forward slashes as much as you can. On Windows, you can use both in file paths. Also, for outputting the file, try using this instead of @readfile:

$pdf = file_get_contents('D:/Learning/'.$title.'.pdf');
echo $pdf;

Another note - you should check if the file exists before accessing it. Place at the top of your script:

if(!file_exists('D:/Learning/'.$title.'.pdf')) {
    echo "File doesn't exist.";
    exit();
}

Hope this helps. Wish you the best.

Comments