Insertion of pdf and doc documents

Asked

Viewed 8,180 times

-2

I’m doing a Backoffice in which I have to insert documents .doc and .pdf but I don’t know how to do it, someone can help?

<form name="form" method="post" action="envia_pdf.php" enctype="multipart/form-data">
<label> Selecione o arquivo PDF: </label>
<input type="file" name="pdf" id="pdf" /><br />
<input type="submit" name="envia" value="Enviar" />
</form>

And this code below is the code of the PHP file:

<?php 

// Verifica se o campo PDF está vazio
if ($_FILES['pdf']['name'] != "") {

// Caso queira mudar o nome do arquivo basta descomentar a linha abaixo e fazer a modificação
//$_FILES['pdf']['name'] = "nome_do_arquivo.pdf";

// Move o arquivo para uma pasta
move_uploaded_file($_FILES['pdf']['tmp_name'],"documentos/".$_FILES['pdf']['name']);

// $pdf_path é a variável que guarda o endereço em que o PDF foi salvo (para adicionar na base de dados)
$pdf_path = "../documentos/".$_FILES['pdf']['name'];

} else {
// Caso seja falso, retornará o erro
 echo "Não foi possível enviar o arquivo";
}

?>

The problem is that when I press the button for the document to be sent, it does not give me any error but only that the document is not sent to the database or to the folder that is referred to in the code.

That’s the problem with this code.

  • 2

    This task can be divided into sub-activities such as, creating the form, uploading/uploading and saving to the database. Decide whether to save the pdf to the bank as a blob(or equivalent) or just its path, to know some of the advantages see: It is wrong to write byte of images in the database?

  • The form I have already done, but only that I do not know how to receive/upload and save in the bank and in the folder where all documents will be

  • 1

    Good, then edit the question and put the form code (select the code and use the button { } to format it.

  • there is my form, and now I have also a php file in which has some input code

  • When asking questions always put the source code if it is too long to leave only relevant part, error messages, do not forget to describe the problem a way to do this is to say what you want to do and what result the system should return and avoid terms like não funciona prefer to detail ex: the screen was blank and not enter the record, this helps a lot who will answer. If you tried something, also ask the question, e.g.: I tried to annoy A and got error 000, I followed this link and gave error 1111. Now all that remains is to describe the problem :).

  • Do you have write permission in this folder? To force the error display, add at the beginning of your php: ini_set('display_errors', true); error_reporting(E_ALL);

  • I do not have permission to write because this does not appear me any message when I do Submit

  • Add a bar before documents: move_uploaded_file($_FILES['pdf']['tmp_name'],"/documentos/".$_FILES['pdf']['name']); Or set the full path to the uploads folder

Show 3 more comments

1 answer

3

In HTML you can put like this:

<form name="form" method="post" action="envia_pdf.php" enctype="multipart/form-data">
    <fieldset class="infraFieldset">
        <legend class="infraLegend">Enviar Arquivos</legend>
        <label id="lblArquivo" for="txtArquivo" class="infraLabelObrigatorio">Documento:</label>
        <input type="file" id="txtArquivo" name="txtArquivo" value="" />
        <button type="submit" accesskey="S" name="sbmSalvar" class="infraButton"><span class="infraTeclaAtalho">E</span>nviar</button>
</form>

In PHP:

$pathToSave = $_SERVER["DOCUMENT_ROOT"].
"/pasta onde quer salvar/";

/*Checa se a pasta existe - caso negativo ele cria*/
if (!file_exists($pathToSave)) {
    mkdir($pathToSave);
}

if ($_FILES) { // Verificando se existe o envio de arquivos.

    if ($_FILES['txtArquivo']) { // Verifica se o campo não está vazio.
        $dir = $pathToSave; // Diretório que vai receber o arquivo.
        $tmpName = $_FILES['txtArquivo']['tmp_name']; // Recebe o arquivo temporário.

        $name = $_FILES['txtArquivo']['name']; // Recebe o nome do arquivo.
        preg_match_all('/\.[a-zA-Z0-9]+/', $name, $extensao);
        if (!in_array(strtolower(current(end($extensao))), array('.txt', '.pdf', '.doc', '.xls', '.xlms'))) {
            echo('Permitido apenas arquivos doc,xls,pdf e txt.');
            header('Location: '.suapagina.php);
            die;
        }

        // move_uploaded_file( $arqTemporário, $nomeDoArquivo )
        if (move_uploaded_file($tmpName, $dir.$name)) { // move_uploaded_file irá realizar o envio do arquivo.        
            echo('Arquivo adicionado com sucesso.');
        } else {
            echo('Erro ao adicionar arquivo.');
        }    
    }  
}
  • where it says "/folder where you want to save/" put all or so : .. /documents

  • ai depends on its structure. will probably put only the /documents without the ..

  • I already have another PDF insertion code, but now there is a problem that is the following :the code sends the file to the referred folder but does not send the file name to the database what would you have to do for the file to go to the referred folder and the file name to go to the database

  • You’ve got my problem?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.