Warning when trying to delete a file

1

I am trying to delete a file that is stored on my server, but the following warning occurs:

  

Notice: Undefined variable: path_pdf in   C: \ xampp \ htdocs \ repositoryApp \ appRegisterEvents \ mainApp \ deleteFile.php   on line 8

     

Warning: unlink (../ Uploads / Files /): Permission denied in   C: \ xampp \ htdocs \ repositoryApp \ appRegisterEvents \ mainApp \ deleteFile.php   on line 8

     

Notice: Undefined variable: path_pdf in   C: \ xampp \ htdocs \ repositoryApp \ appRegisterEvents \ mainApp \ deleteFile.php   on line 9 The file could not be deleted:

I am running the function as follows:

<a class="btn btn-danger btn-sm  glyphicon glyphicon-remove"
   ng-href="mainApp/deleteFile.php">
</a>

As it is a single file per user, I then need to look up the file name to locate it and be able to delete it with the function unlink() but the warning returns and it does not erase the specified file.

<?php
    session_start();
    $id_empresa  = $_SESSION['usuario']['id_empresa'];
    require 'conexion.php';

    $selectFile = $mysqli->query("SELECT ruta_pdf FROM empresa WHERE id_empresa=".$id_empresa.";");

  if (!unlink("../Uploads/Files/".$ruta_pdf['ruta_pdf'])) {
    echo "No se pudo borrar el fichero: ".$ruta_pdf['ruta_pdf'];
  }
  else {
    echo "El fichero ".$ruta_pdf['ruta_pdf']." ha sido eliminado";
  }

  $updateFile = "UPDATE empresa
                                        SET ruta_pdf = ''
                                    WHERE 'empresa'.'id_empresa' = '$id_empresa'";

  if(mysqli_query($mysqli, $updateFile))
    {
        echo "Datos actualizados correctamente";
    header("Location: ../");
    }
    else
    {
        echo "Error al actualizar: " . $mysqli->error;
    }
?>
    
asked by jecorrales 11.08.2017 в 16:46
source

1 answer

2

Your problem is that you are trying to access a record that has returned a query without previously obtaining them with a mysqli::fetch() :

<?php
session_start();
require 'conexion.php';

/* Esta es la consulta SQL */
$selectFile = $mysqli->prepare("
  SELECT ruta_pdf
  FROM empresa
  WHERE id_empresa = ?
");
/* Comprobamos si la consulta se preparó correctamente */
if ($selectFile === false) {
  die('Error SQL: ' . $mysqli->error);
}
/* Asignamos al primer "?" el valor de "id_empresa" */
$selectFile->bind_param('i', $_SESSION['usuario']['id_empresa']);
/* Comprobamos si la consulta se ejecutó correctamente */
if ($selectFile->execute() === false) {
  die('Error SQL: ' . $selectFile->error);
}
/* Cada vez que llamemos a "fetch" se asignará el resultado a $ruta_pdf */
$selectFile->bind_result($ruta_pdf);
/* Aquí obtenemos el registro (si lo hay) */
if ($selectFile->fetch() !== true) {
  die('No existe el registro a borrar');
}

if (!unlink("../Uploads/Files/".$ruta_pdf)) {
  echo "No se pudo borrar el fichero: ".$ruta_pdf;
} else {
  echo "El fichero ".$ruta_pdf." ha sido eliminado";
}
    
answered by 11.08.2017 / 16:50
source