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!");
}
}