1

I need to delete image files in my /var/www/mysite/postImage folder with unlink() function in php. But I'm absolutely worried about if somebody hacked into my site and was using it .. or . in the path and try to delete something in upper level folder. I'm using JQuery to send the path and because it's client side programming it's dangerous. I know , I can bypass dots when uploading files but what if somebody changes the path in client side by adding dots to it? My question is how to prevent somebody from doing that?

Damian Silva
  • 336
  • 3
  • 19
Amir H
  • 1,116
  • 1
  • 11
  • 25
  • Related question: [Preventing Directory Traversal in PHP but allowing paths](http://stackoverflow.com/q/4205141/53114) – Gumbo Jun 14 '15 at 09:39

2 Answers2

1

The Thumb Rule should be that, you should depend least on the data from client side.

Now according to your question it seems that you are sending the full file path that is to be deleted.

So IMHO, you should just send the file name and let the server-side php decide(append) the directory in which the file is to be deleted.

// example
$filename = $_POST['fname']; // something like xyz.png
$filename = str_replace('/','',$filename); // strip any forward slash.

if(empty($filename)){
die('File Name Invalid'); // seems like all the characters in file name were slashes.
}

$directory = 'some/folder/that/contain/images/postImage/';
$filepath = $directory . $filename;
unlink($filepath);

Now about someone else using this functionality, just keep a login system, and check if the user is logged in.

Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88
  • This fails on Windows systems where ```\``` is the directory separator. – Gumbo Jun 14 '15 at 09:38
  • Sure, this is just a proof of concept, meant to give a rough Idea, and one can always improvise like using `stripslashes()` and `DIRECTORY_SEPARATOR ` etc. Since OP didnt post any code, I shall just leave my example as is, Thanks for pointing out though. – Mohd Abdul Mujib Jun 14 '15 at 10:40
  • Windows allows both ```\``` and `/` as directory separator. Using `DIRECTORY_SEPARATOR` alone wouldn’t cover that. – Gumbo Jun 14 '15 at 10:45
  • I meant If the code added `$filename = stripslashes($filename);` on line no. 4, wouldn't that take care of it? – Mohd Abdul Mujib Jun 14 '15 at 10:49
  • A `basename` would also suffice. – Gumbo Jun 14 '15 at 10:54
  • exactly, the possibilities of methods for completing any task in php are (relatively)endless and more based on creativity and skills ;) – Mohd Abdul Mujib Jun 14 '15 at 10:58
1
  1. Make sure apache user has proper rights(writing only in website directory)
  2. Cut .. from path, sanitize and validate path if it's correct.
  3. You can also use realpath() function.
Robert
  • 19,800
  • 5
  • 55
  • 85