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

i just want to show a image to visitor in the same time delete this image from the server.

i tried this

show the image. delete the record from database. delete the image from server using unlink().

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

but when the page loads it deletes the file from server before it shows to visitor.

After searching i found that PHP is executed in the stack prior to rendering the output.

So how i do this using ajax jquery. That is: load the page and show the image then execute the ajax code and delete the image.

Please give some ajax code. i am not familiar with 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>

and to delete on php side (delete.php):

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

With using AJAX it's possible what image will not be deleted. Connection problem or disabled javascript.

You need to do:

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

and in image.php write:

// 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);

Also don't use mysql_*... You can use PDO or Mysqli.

Here is the working code,

<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>

In test.php, you could do,

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

?>