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?
How to unlink file securly in php?
753 views Asked by Amir H At
2
There are 2 answers
6
On
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.
..
from path, sanitize and validate path if it's correct.