Display longblob field contents containing PDF file

6

I have a question regarding the longblob data that is stored in the Database.

I currently have this for the other data:

echo "<tr><td>Email:</td>";
echo "<td>";

if ($exibe['Email']) {
    echo $exibe['Email'];
} else {
    echo 'N/D';
}

echo "</td></tr>";
echo "<tr><td>Alvara Numero:</td>";
echo "<td>";

if ($exibe['AlvaraNumero']) {
    echo $exibe['AlvaraNumero'];
} else {
    echo 'N/D';
}

echo "</td>   </tr>";

And now I want to show the attachment:

echo "<tr><td>Alvara Anexo:</td>";
echo "<td>";

I do not know what is the best way to show or download to see the file.

    
asked by anonymous 14.02.2014 / 11:09

2 answers

4

The document stored in the database will have to be collected in an isolated PHP file, so that it contains the headings suitable for the correct interpretation of the data.

One solution is to apply a link in the code displayed in your question, which will call the file responsible for presenting the document through a parameter identifier of the desired line in your table:

Link to document

Example of creating a link to a PHP file with a parameter to be passed to it:

echo '
<tr>
  <td>
    Alvara Anexo:
  </td>
  <td>
    <a href="caminho/ficheiro_mostra_pdf.php?id='.$exibe["id"].'" title="">
      Clique para ver documento PDF
    </a>
  </td>
</tr>';

Notes:
I'm assuming you have a id column to identify the row in the table that contains the document. You should update / rectify the entry name in the array $exibe to the name of the column that actually exists in your table.

Filing document

Below is the code for the file named ficheiro_mostra_pdf.php that will collect the binary data of the line it received and output to the browser with a suitable header for PDF document:

  

NOTE: I'm using PHP mysql_ * because I have since your remaining questions use this method for querying the database, however, I advise you to choose other methods since this PHP extension is being removed.

<?php
// para debug, remover as 3 linhas quando em produção
error_reporting(E_ALL ^ E_DEPRECATED);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);


// verifica se existe identificador
if (isset($_GET["id"]) && ctype_digit($_GET["id"])) {

    // apanha identificador
    $id = $_GET["id"];

    /* define os acessos à base de dados
     */
    define("HOST", "localhost");     // Database Name
    define("DBUSER", "utilizador");  // Database user
    define("PASS", "password");      // Database password
    define("DB", "nome-base-dados"); // Database name

    // estabele ligação à base de dados
    $ligacao = mysql_connect(HOST, DBUSER, PASS) or die('Erro:' . mysql_error());

    // escolhe a base de dados
    $db = mysql_select_db(DB) or die(LANG_DB_CONNECT_FAIL);

    // consulta base de dados
    $resultado = mysql_query("SELECT meu_campo_blob FROM minha_tabela WHERE id='".$id."'");

    // verifica se recebeu algo
    if ($resultado) {

        // verifica se temos uma única linha
        if (mysql_num_rows($resultado)==1) {

            // recolhe os dados binários
            $registo = mysql_fetch_array($resultado);

            // verifica se contem dados
            if (is_array($registo) && isset($registo["meu_campo_blob"]) && $registo["meu_campo_blob"]!='') {

                $ficheiro = $registo["meu_campo_blob"];

                // cabeçalho identificador para o navegador
                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: '.strlen($ficheiro));

                // faz saída para o navegador
                print $ficheiro;

            } else {
                echo "Sem conteúdo para gerar o PDF.";
            }

        } else {
            echo "O número de resultados não é 1.";
        }

    } else {
        echo "Não foi possível seleccionar o campo da base de dados";
    }

    // fecha a ligação à base de dados
    mysql_close($ligacao);

} else {
    echo "Não foi possível apurar o identificador do registo pretendido.";
}

?>

The checks performed are basic to ensure a minimum of viability in the solution. However, you should ensure that access to this file is properly protected from unauthorized access.

Headers

Alternatively, you can add more headers to better control the output of your document, such as the cache indication, the output encoding type, and the size of the output:

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($ficheiro));
    
14.02.2014 / 13:07
2

Depending on the file format you can not view it directly on the page, but you should link to the download of it.

Displaying files directly on the page

If the file is of type text (txt, xml, html, etc.) you can display it directly on the page. Use a <textarea> , <pre> or even <div> tag with the proper CSS.

Let's look at an example:

.conteudo-texto {
    display: block;
    unicode-bidi: embed;
    font-family: monospace;
    white-space: pre-wrap;
    width: 100%;
}
echo "<tr><td>Alvara Anexo:</td>";
echo "<td><div class='conteudo-texto'>" . htmlentities($exibe['AlvaraConteudo']) . '</div></td>';

Demo on Jsfiddle

It is also possible to limit the size and place the scroll bar, if necessary, by adding the CSS overflow: scroll; .

Demo on Jsfiddle

The same principle can be applied if the attachment is an image. Simply display it in place with maximum width and height sizes.

Displaying files in frame , iframe or popup

PDFs and some other types of binary files are recognized by browsers and plugins, but should be displayed on a separate page.

New page

To display a PDF on a new page, simply create a link with the target attribute with _blank value. The link should point to a PHP page which, in turn, will display the contents of the file.

Example for a PDF:

echo '<a href="visualizar_anexo.php?AlvaraNumero=' . $exibe['AlvaraNumero']) 
   . '" target="_blank">Abrir anexo</a>';

So the PHP file would have something like:

<?php
if (isset($_GET['AlvaraNumero'])) {
    try {
        // recupera dados do alvará
        $conteudo_arquivo = ...
        $tamanho_arquivo = ...
        $nome_arquivo = ...

        header("Content-length: $tamanho_arquivo");
        header("Content-type: application/pdf");
        header("Content-disposition: inline; filename=$nome_arquivo");
        echo $conteudo_arquivo; 
    } catch (PDOException $e) {
        // tratar erro
    }
}

Popup

To display in a popup, just add a Javascript event on the link.

Example:

$('a').click(function() {
    w = 600;
    h = 600;
    x = 10;
    y = 10;
    window.open(this.href, 'anexo', "resizable=no, toolbar=no, scrollbars=no, menubar=no, status=no, directories=no, width=" + w + ", height=" + h + ", left=" + x + ", top=" + y);
    return false; //inibe o clique original para não abrir a nova janela
});
                                    
14.02.2014 / 13:35