Error uploading a pdf file


I am trying to upload a file to a folder where you can store .pdf files, but only upload the file name to the database, but I can not upload the file.


if (isset($_POST['add'])) {
    if (!empty($_POST['titulo']) && !empty($_POST['texto']) && !empty($_POST['archivo'])) {
        $add = $conn->prepare("INSERT INTO punioyletra (titulo, texto, archivo) VALUES (:titulo, :texto, :archivo)");
        $add->bindValue(':titulo', $_POST['titulo']);
        $add->bindValue(':texto', $_POST['texto']);
        $add->bindValue(':archivo', '../../pdf' . $_POST['archivo']);

        header('location: ../');
    } else {
        echo '<div class="cmpl">Hay campos vacios</div>';

This is the form

<form action="" method="post" enctype="multipart/form-data">
<input type="text" name="titulo" placeholder="Titulo" autocomplete="off"><br>
<textarea name="texto" placeholder="Texto"></textarea><br>
<input type="file" name="archivo">
<button class="srbs-btn-primary btn" name="add">Publicar</button>

As a result, it gives me that there are empty fields. If I remove the opsion to upload files, everything works.

asked by Stn 05.12.2018 в 03:37

1 answer


You need to refer to the file, it's not worth $_POST['archivo'] because the file fields are managed a little differently.

Before the imputation in the database you have to verify that in $_FILES you get what you expect. This variable works the same as $_POST , it is an array where you get the information of the form, you can see its contents with:

  echo '<pre>';
  echo '</pre>';

This will familiarize you with its structure.

Once you know that the file has reached the server, you have to copy its final location and then save in database what you need (usually the path and final name of the uploaded file).

This copying process is done using the function: move_uploaded_file()

As an example:

$uploads_dir = '/ficheros_subidos';
foreach ($_FILES['archivo']['error'] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["archivo"]["tmp_name"][$key];
        // basename() puede evitar ataques de denegación de sistema de ficheros;
        // podría ser apropiada más validación/saneamiento del nombre del fichero
        $name = basename($_FILES["archivo"]["name"][$key]);
        move_uploaded_file($tmp_name, "$uploads_dir/$name");

Source: link

You have more information in the official documentation: link

answered by 05.12.2018 в 09:20