Page 1 of 1

If else unlink question

Posted: Thu Aug 19, 2010 6:41 am
by mrlayance
Easy one first think in the morning... Just not for me...

Code: Select all

<?php
if(isset($_GET['file'])){ 
unlink($_GET['file']);
	echo "File removed, go back and refresh the page.";
} else {
	echo "Nope, try again.  Might be premission problem";
}
?>
If the statement works and the file exists, the file is removed. If the file is missing or not readable the else does not work...

Warning: unlink(xxxx.jpg) [function.unlink]: No such file or directory in /xxx/xxx/xx/removefile.php on line 3
File removed, go back and refresh the page.

Re: If else unlink question

Posted: Thu Aug 19, 2010 7:12 am
by shawngoldw
You're only checking if a file is being passed into your script, not that the file exists.

Code: Select all

if(isset($_GET['file']) && file_exists($_GET['file'])){ 
You should also really be validating $_GET['file']. I can go to yoursite.com/?file=index.php
You don't want that.

edit: actually, is_file might be a better choice than file_exists

Shawn

Re: If else unlink question

Posted: Thu Aug 19, 2010 7:43 am
by mrlayance
Thanks for the reply. The && did the trick.

This is what I came up with for some basic security. I just want images removed at any time.

Code: Select all

<?php
$image = $_GET['file'];

if(preg_match("/.(jpg|JPG)/", $image) && unlink($image)){
	echo "File removed, go back and refresh the page.";
} else {
	echo "Nope, try again.  Might be premission problem";
}
?>
Let me know if you see some huge holes.

Re: If else unlink question

Posted: Thu Aug 19, 2010 7:51 am
by shawngoldw
That should be pretty secure. The only thing I can think of is someone deleting a logo or background image or something. I imagine the images you want to be able to delete are within a specific folder, or a set of specific folders? I would also make sure that $image is pointing to a folder you expect it to.


Shawn

Re: If else unlink question

Posted: Thu Aug 19, 2010 8:14 am
by mrlayance
I see what you mean, I can delete images still 2 directorys up... Not sure how I would keep the script from travelling outside a directory?

I think the following works, but I get a sucessfully deleted message but the file is still in place. Not the case without basename.

$image = basename($_GET['file']);

Re: If else unlink question

Posted: Thu Aug 19, 2010 9:39 am
by shawngoldw
You're php script is not in the same folder as the images, is it? If not then basename is not going to work. How are the images stored, are they all in the same folder?

If so, I would just pass the name of the file into the script, without a path or .jpg, eg. image1.
I would check that the get variable is alphanumeric, maybe also accept . or - or _ depending on how you're doing things.
Then check if (SOMEPATH . clean get var . ".jpg") exists.
Then i would unset (SOMEPATH . clean get var . ".jpg").


Shawn