Jump to content

Delete a file using unlink does not work


angelali

Recommended Posts

So how to do it, help me...  :shrug:

PHP applications, and any application in general, takes proper planning and logical thinking.

 

My suggestion is: before you start any application, plan it all out.  Write down the steps that are required and how the results of those steps will be achieved.  Organization is everything.

 

Say to yourself, "When the user clicks the button to delete x images, what does the code need to do?"

 

OK - it needs to gather the appropriate reference points so the images in question can be manipulated (E.g. as you gathered in <input type="checkbox" name="delete[]" value="'.$row['img_ID'].'"/>).

 

Now, I need to delete those from the database using those ID's... check!  I also need to remove them from the appropriate directory... ummmm... to do that I will need the image names.  How do I get those?  Oh ya!  From the database.

 

As you continue writing applications you will come across ways to make your code more efficient through trial and error.

Link to comment
Share on other sites

Permission denied again  :( I passed 5 hours determining this damn problem, I have even broken 2 bottles because of this...

OK - what is "permission denied"?  Please, save yourself some time and grief and expand on this before being asked.  Permission denied could be a million things.  Are you seeing any errors?  Is it a file permissions issue?  Is it a folder permissions issue?  Is it a database permissions issue?
Link to comment
Share on other sites

Warning: unlink(images/) [function.unlink]: Permission denied in C:\xampp\htdocs\troll\includes\images.php on line 53

 

The above the warning message. I set all permissions of my folders as FULL CONTROL on Windows, I don't know why iyt keeps asking this. Secondly, as the query is exeuting the image names which are stored in database, with that query $row['imgname'], I put it in a variable, and assign it to unlink function to delete the image.

Link to comment
Share on other sites

Warning: unlink(images/) [function.unlink]: Permission denied in C:\xampp\htdocs\troll\includes\images.php on line 53

 

The above the warning message. I set all permissions of my folders as FULL CONTROL on Windows, I don't know why iyt keeps asking this. Secondly, as the query is exeuting the image names which are stored in database, with that query $row['imgname'], I put it in a variable, and assign it to unlink function to delete the image.

Did you alter the code I gave you?  If so, please post it.
Link to comment
Share on other sites

I had a small typo (had mysql_fetch_row() instead of mysql_fetch_assoc() which I intended to use).  This is updated:

 

//Connect to database 
$connect = mysql_connect('localhost', 'root', '') or die ('Connection Failed');
mysql_select_db('imgdatabase', $connect) or die ('Connection Failed');

//Display images
$display = mysql_query("SELECT * FROM photos WHERE email='$reg'"); // are you sanitizing $reg?
echo "<form action='images.php' method='post'>";
echo "<table>
<tr>
<th>#</th>
<th>Your images</th>
<th>Image names</th>
<th><input type='submit' value='Delete'/></th>
</tr>";
echo "<hr/>";
while($row = mysql_fetch_array($display)) {
echo "<tr>";
echo "<td>".$row['img_ID']."</td>";
echo "<td><img src='images/".$row['imgame']."' alt='alt text' width='200' height='150' class='thumb'/> </td>";
echo "<td><a href='images/".$row['imgname']."' target='_blank'>".$row['imgname']."</a></td>";
echo '<td><input type="checkbox" name="delete[]" value="'.$row['img_ID'].'"/></td>';
echo "</tr>";
}
echo "</table>";
echo "</form>";

//Delete images details in database
if (isset($_POST['delete'])) {
$ids = array_map('mysql_real_escape_string', $_POST['delete']);
$sql = "SELECT `imgname` FROM `photos` WHERE `img_ID` IN (". implode(',', $ids) .")";
if ($result = mysql_query($sql)) {
	if (mysql_num_rows($result) > 0) {
		while ($row = mysql_fetch_assoc($result)) {
			unlink('images/'. $row['imgname']);
		}
		$del = mysql_query("DELETE FROM photos WHERE img_ID IN (".implode(',', $ids).")");
	}
	else {
		echo 'Please select a file to delete.'; // you can change up your error handling to be showed to the user
	}
}
else {
	trigger_error(mysql_error()); // remove once everything is working
}
}
mysql_close($connect);
?>

Link to comment
Share on other sites

Notice: Undefined index: imgname in C:\xampp\htdocs\troll\includes\images.php on line 53

 

And the permission denied warning.. I get the notice after correcting your codes earlier, forgot to paste it...when I replied you the previus message

Link to comment
Share on other sites

If I have asked you your country, this means I would invite you for a good day on the beach in my country, enjoying some chicks, beers and the sand....because IT IS WORKING PERFECTLY LOLLLLLLLLLL  :D  :D  :D  :P  :)  :D Thank youuuuuuuuuuuuu

 

What should I do with this: 

 

else {
      trigger_error(mysql_error()); // remove once everything is working
   }

 

You said remove it if it is working properly...

Link to comment
Share on other sites

Haha, good to hear!

 

Well, you can remove (or comment out) that line and replace with any sort of error logging and control.  If that condition is reached, that means that the query failed and it's good to know why.

 

Something to modify in the code for better handling would be:

 

in your form

<th><input type='submit' value='Delete'/></th>

 

change to:

<th><input name='delete_button' type='submit' value='Delete'/></th>

 

Then change your entire "delete" condition block to:

 

//Delete images details in database
if (isset($_POST['delete_button'])) { // this is check to make sure button was clicked
if (isset($_POST['delete']) && !empty($_POST['delete'])) { // added to ensure at least one image was selected

	// you can also play around with ways to ensure all ID's in $_POST['delete'] are integer values and add control here

	$ids = array_map('mysql_real_escape_string', $_POST['delete']);
	$sql = "SELECT `imgname` FROM `photos` WHERE `img_ID` IN (". implode(',', $ids) .")";
	if ($result = mysql_query($sql)) {
		if (mysql_num_rows($result) > 0) {
			while ($row = mysql_fetch_assoc($result)) {
				unlink('images/'. $row['imgname']);
			}
			$del = mysql_query("DELETE FROM photos WHERE img_ID IN (".implode(',', $ids).")");
		}
		else {
			echo 'No matches in the db.'; // you can change up your error handling to be showed to the user
		}
	}
	else {
		trigger_error(mysql_error()); // remove once everything is working
	}
}
else {
	echo 'Please select a file to be deleted';
}
}

Link to comment
Share on other sites

And also for the array_map, can I insert strip_tags as well in it like:

 

$ids = array_map('mysql_real_escape_string', 'strip_tags', $_POST['delete']);

 

 

 

No, but you can do:

 

$ids = array_map('mysql_real_escape_string', $_POST['delete']);
$ids = array_map('strip_tags', $ids);

 

Or, just revert back to your foreach() loop like you had before.  array_map is just cleaner IMO.

Link to comment
Share on other sites

OK will change this... Mr Marcus, thank you very much man! I love Canada as well, so sad too far.... I live in the Indian Ocean... I'm new in PHP, well not that new, but I started with it in last December. My objective is not to be professional in it, as I'm more on front-end development than back-end. However, I'm a guy who wants to have at least an Intermediate level of knowledge in different back-end languages rather than mastering a single language.

 

I'm still learning, have a lot to do, I have OO to learn (A real pain this OO), and after that, will touch Ruby... Too sad, ColdFusion is almost dead, else I would master it...as I love it..

 

Well, I added you as buddy list, thank you again man, you are great prince..  ;)

Link to comment
Share on other sites

Glad I could help.

 

Learn the fundamentals first.  Be comfortable working with the basic aspects of the language first (E.g. $_GET/$_POST, form handling, database access, etc), then have a peek at OO.  As is the same in any aspect of life, don't try to run before you can walk.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.