向访问者显示图像并从服务器中删除该图像(在同一页面加载时)


Show a image to visitor and delete that image from the server (on same page load)

>我只想向访问者显示一个图像,同时从服务器中删除此图像。

我试过这个

显示图像。从数据库中删除记录。使用 unlink() 从服务器中删除映像。

echo "image";
$deleteimage = mysql_query("DELETE FROM table WHERE uniqueid= '$id'") or die(mysql_error());
unlink("../image path");

但是当页面加载时,它会在向访问者显示文件之前从服务器中删除文件。

搜索后,我发现PHP在渲染输出之前在堆栈中执行。

那么我如何使用ajax jquery来做到这一点.即:加载页面并显示图像,然后执行 ajax 代码并删除图像。

请提供一些 ajax 代码。 我不熟悉javascript (ajax,jquery)

<!DOCTYPE html>
<html>
<head>
    <script src="jquery.min.js"> </script>
</head>
<body>
<script>
    function unlinkImage(src) {
        $.ajax({
            type:"POST",
            url: "delete.php",
            data:{
                src:src
            }
        }).done(function() {
            alert('done')
        });
    }
</script>
<img src='someimage.png' onload="unlinkImage('someimage.png')" />
</body>
</html>

并在 PHP 端删除(删除.php):

<?php
    $res = unlink($_REQUEST['src']);
?>

使用AJAX,可能不会删除图像。连接问题或禁用javascript

您需要做:

<img src="imgage.php?id=ID" />

并在image.php中写道:

// Select image source
$image = mysql_result(mysql_query("SELECT image FROM table WHERE uniqueid= '".intval($id)."'"), 0, 'image');
// Show image
header('Content-type: image/jpeg'); // Or your image type
readfile($image);
// Delete image
$deleteimage = mysql_query("DELETE FROM table WHERE uniqueid= '".intval($id)."'") or die(mysql_error());
unlink($image);

也不要使用mysql_*...您可以使用PDO或Mysqli。

这是工作代码,

<html>
    <head>
        <title>Log In Page</title>
        <script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
        <script>
            function ImageLoad(obj) {
                var src = $(obj).attr('src');
                $.ajax({
                    type:"POST",
                    url: "test.php",
                    data:{
                        imageSrc:src
                    },
                    dataType:"text",
                    success: function(data) {
                        $('#doneDiv').html(data);
                    }
                });
            }
        </script>
    </head>
    <body>
        <img src="http://s8.postimg.org/9rhympj35/agent_Photo.jpg" onload="ImageLoad(this);">
        <div id="doneDiv"></div>
    </body>
</html>

test.php,你可以做到,

<?php
    $res = unlink($_POST['imageSrc']);
    echo 'done'; 
    // or you can delete from database with your code
?>