簡體   English   中英

使用AJAX / PHP刪除文件

[英]Delete files with AJAX/PHP

問題


我想使用AJAX/PHP刪除文件。

但是php表示我通過AJAX發送的文件名不是文件,但是當我直接轉到鏈接時,可以刪除文件。 看看我當前的PHP,我已經在IF / ELSE語句中檢查了字符串是否是帶有以下文件的文件: is_file ,結果為false

沒有is_file話是這樣的:

Warning: unlink("image.jpg") [function.unlink]: Invalid argument in C:\\wamp\\www\\images\\users\\delete.php on line 8

所謂的ajax文件位於文件夾中,我也想刪除這些文件。

的PHP


<?php
    // I save the file sources from the URL what was sent by AJAX to these variables.
    $photo_id = $_GET['photo_id'];
    $thumbnail_id = $_GET['thumbnail_id'];

    function deletePhotos($id){
        // If is a file then delete the file.
        if(is_file($id)){
            return unlink($id);
        // Else show error.
        } else {
            echo $id . " is not a file, or there is a problem with it.<br />" ; 
        }
    }

    if(isset($photo_id)){
        deletePhotos($photo_id);
    }
    if(isset($thumbnail_id)){
        deletePhotos($thumbnail_id);
    }

 ?>

AJAX


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.php?photo_id=\""+photos+"\"&thumbnail_id=\""+thumbnails+"\"", true);
        xmlhttp.send();
    }

您的ajax請求的數據用引號引起來。

//Bad
delete.php?photo_id="1234"

//Good
delete.php?photo_id=1234

//So use this:
xmlhttp.open("GET", "http://192.168.2.104/images/users/delete.php?photo_id="+photos+"&thumbnail_id="+thumbnails, true);
  • 您需要提供is_file的完整路徑。 像image.jpg這樣的部分路徑不會告訴它該文件的位置。 如果應該相對於文檔根目錄,則需要在該目錄前面添加。

  • 這是我見過的最危險的腳本之一。 您可以將任何文件傳遞到photo_id,只要Web服務器具有正確的權限,它將刪除該文件。 您至少應確保將其限制為僅刪除特定目錄中的文件。

您可能需要指定路徑,例如

file_exists( realpath('.') . '/' . $id );

(假設您的文件與腳本位於同一文件夾中)與他人所說的一樣,除非有其他安全措施,否則這是危險的腳本!

嘗試在帖子中使用trim或獲取變量,例如:

$photo_id=trim($_GET['blah..blah']);

在我的情況下,問題是$photo_id返回文件名-當它應為“文件名”時,它返回類似“ \\ nfilename”的內容,因此我添加了trim並且它現在對我有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM