Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening pdf with mysql and php

Tags:

php

mysql

pdf

I'm storing pdf's on the filesystem and path in database table. I want now based on the ID to open corresponded PDF document in the browser. How can I open and read PDF's? What I have so far is this

require_once("database.php");

if(isset($_GET['upload_id']) && is_numeric($_GET['upload_id']))
{
    $fileFolder='uploads/';

    $sql = "SELECT file FROM documents WHERE upload_id = :id"; 
    $result = $pdo->prepare($sql);
    $result->bindParam(":id", $_GET['upload_id']);
    $result->execute();                 

    $resArray = $result->fetchAll();

    $file = $resArray['file'];

    header('Pragma: public');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Content-Type: application/pdf');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: '.filesize($fileFolder.$file));
    @read($fileFolder.$file);

}

When I click on the button and tried to open the pdf I got this message in the Chrome

Failed to load PDF document RELOAD

like image 259
S.I. Avatar asked Dec 05 '25 07:12

S.I.


2 Answers

You can get your file name using fetch(PDO::FETCH_ASSOC); which Return next row as an array indexed by column name

$sql = "SELECT file FROM documents WHERE upload_id = :id"; 
$result = $pdo->prepare($sql);
$result->bindParam(":id", $_GET['upload_id']);
$result->execute();     
$resArray = $result->fetch(PDO::FETCH_ASSOC);
$file = $resArray['file'];// get your file name

By using fetchAll

Pass PDO::FETCH_COLUMN, 0

 $result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
 $file = $resArray[0];// get your file name
like image 146
Saty Avatar answered Dec 06 '25 21:12

Saty


try the following:

require_once("database.php");

if(isset($_GET['upload_id']) && is_numeric($_GET['upload_id']))
{
    $fileFolder='uploads/';

    $sql = "SELECT file FROM documents WHERE upload_id = :id"; 
    $result = $pdo->prepare($sql);
    $result->bindParam(":id", $_GET['upload_id']);
    $result->execute();                 

    $resArray = $result->fetchAll();

    $file = $resArray['file'];

    $myFilePath = $fileFolder . $file;

    if (file_exists($myFilePath)) {

        // the file exists, so open it
        header('Pragma: public');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Content-Type: application/pdf');
        header('Content-Transfer-Encoding: binary');
        header('Content-Length: '.filesize($fileFolder.$file));
        @read($fileFolder.$file);

    } else {

        // the file doesn´t exits
        // handle the error if neccessary
        echo "the file doesn´t exist";

    }

}
like image 34
Michael Avatar answered Dec 06 '25 22:12

Michael



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!