I'm using UNLINK with PHP
and AJAX
. I know that in this way is very dangerous, because everyone can delete any files. But I need to use AJAX
because I can't reload the page when I delete the files.
So how should I do to allow to delete the file only for the user who owns it?
Please let me know other things too if you think I'm doing here something wrong or something else what you have in mind and you think that it will be useful : )
My PHP code:
<?php
$photo_id = $_GET['photo_id'];
$thumbnail_id = $_GET['thumbnail_id'];
function deletePhotos($id){
return unlink($id);
}
if(isset($photo_id)){
deletePhotos($photo_id);
}
if(isset($thumbnail_id)){
deletePhotos($thumbnail_id);
}
?>
My AJAX code:
function deletePhoto(photo, thumbnail){
var photos = encodeURIComponent(photo);
var thumbnails = encodeURIComponent(thumbnail);
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("media").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "http://192.168.2.104/images/users/delete_photo.php?photo_id="+photos+"&thumbnail_id="+thumbnails, true);
xmlhttp.send();
}
You need to authenticate the user somehow.
Your user needs to be authenticated with a username and a password.
PHP session can be used to remember, and you should use a database table or a text file on the server to store file ownership information.
Then, before unlinking anything, your logic should make sure that the currently "authenticated" user is the owner of the file.