Removing an image via unlink does not work

1

I have the following code below:

//carrega a imagem anterior
$img = $db->prepare("select ipco_descr_multimidia,ipco_arquivo from ipco_multimida where ipco_id_questao_fk = :id ");
$img->bindParam(':id',$id);

//executa a query
$img->execute();

//recupera os valores da tabela
$resultado = $img->fetchAll();
$caminho = $resultado['ipco_arquivo'];
$nome = $resultado['ipco_descr_multimidia'];

//apagar o arquivo antigo da pasta
if(file_exists($caminho.$nome)) {
    @unlink($caminho.$nome);
    //exit;
}

Multimedia table:

ipco_descr_multimidia | ipco_arquivo
1413297340.jpg        | ./img/upload/

When I run the code, it does not delete the image inside the img / upload folder.

    
asked by anonymous 14.10.2014 / 18:30

1 answer

4

By your code, there are some things that can be improved so that there is more coherence between what you want and what you are doing. On the other hand, some of the suggestions are aimed at solving potential security problems:

  • Uses the PDO statement fetch() that returns you a line instead of fetchAll() .

    This point solves the problem that led you to ask the question.

  • Use the is_file() function to check if the file exists because it only returns TRUE if a file exists and is in fact a file.

  • Check the values before using them, as you can see below using the empty() .

  • Do not hide system errors, your code must be prepared to deal with them. The unlink() function returns FALSE when something goes wrong. If something went wrong, you should act accordingly either by informing the user or by taking alternative measures for the task in question.

  • Example of your code as described above:

    /* Carrega a imagem anterior
     */
    $img = $db->prepare("
      SELECT ipco_descr_multimidia, ipco_arquivo
      FROM ipco_multimida
      WHERE ipco_id_questao_fk = :id
    ");
    $img->bindParam(':id', $id);
    
    // executa a query
    $img->execute();
    
    // recupera os valores da tabela
    $resultado = $img->fetch();
    
    $caminho = $resultado['ipco_arquivo'];
    $nome = $resultado['ipco_descr_multimidia'];
    
    /* apagar o arquivo antigo da pasta
     */
    if (!empty($caminho) && !empty($nome) && is_file($caminho.$nome)) {
    
        if (!unlink($caminho.$nome)) {
          die("Ups... correu mal!");
        }
    }
    
        
    14.10.2014 / 20:15