Reputation: 15
I'm trying to delete a file from uploads folders, but the code is not working.
It's deleting the row from the database, but not the file from the folder.
<?php
extract($_REQUEST);
include_once('include/dbcon.php');
$dell= $_GET['del'];
$sql1=mysqli_query($conn, "SELECT * FROM notes WHERE notes_id='$dell'");
$row1=mysqli_fetch_array($sql1);
$delfile= $row1["file_path"];
unlink("uploads/".$delfile);
mysqli_query($conn, "DELETE FROM notes WHERE notes_id='$dell'");
header("location: deshboard.php");
?>
Upvotes: 1
Views: 62
Reputation: 398
I am assuming that the row in the database is the relative file path from within the uploads folder here. When using unlink people sometimes use the realpath function to get the absolute pathname name.
Your code will look something like this:
unlink(realpath('uploads/' . $delfile));
Also, your code is vulnerable to SQL Injection, please consider using prepared statements when using variables within your queries
Upvotes: 3
Reputation: 312
The read and write permissions in the uploads folder might be the problem.
To check file permission you can use the following to check if the file is writable:
//Make sure to always get the full file path from $delfile
$delfile = /* path to the uploads folder */ . $row1["file_path"];
if (is_writable($delfile)) {
print 'YES!!!: I am writeable';
} else {
print 'NO!!!: File not writable, please fix me';
}
To check if the file is readable simply swap is_writable()
with is_readable()
Learning how to use chmod helped me a lot when working with files/folders and its permissions.
Upvotes: 1
Reputation: 1083
First of all retrieve the full path of file :
$delfile = dirname(__FILE__) . $row1["file_path"];
Then make sure the file permissions is set to 0777:
chmod($delfile , 0777);
Final Result:
<?php
extract($_REQUEST);
include_once('include/dbcon.php');
$dell= $_GET['del'];
$sql1=mysqli_query($conn, "SELECT * FROM notes WHERE notes_id='$dell'");
$row1=mysqli_fetch_array($sql1);
$delfile = dirname(__FILE__) . $row1["file_path"];
if (is_file($delfile )) {
chmod($delfile , 0777);
if (unlink($delfile )) {
//'File deleted';
mysqli_query($conn, "DELETE FROM notes WHERE notes_id='$dell'");
header("location: deshboard.php");
} else {
//'Cannot remove that file';
}
} else {
//'File does not exist';
}
?>
Upvotes: 0