Odie Ardhia Odie Ardhia - 1 month ago 8
PHP Question

PHP file upload. The image is displayed, then deleted automatically

I want a user can only upload DOC and XLS file. But if the file is an image, the image file is displayed in the web page (upload.php) and then deleted automatically from the server.

Here is my piece code:

if (file_exists("uploads/" . $_FILES["file"]["name"])) {
echo "<br>File already exists!.<br>";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"]);
if (($_FILES["file"]["type"] == "image/gif" )
||($_FILES["file"]["type"] == "image/jpeg" )
||($_FILES["file"]["type"] == "image/jpg" )
||($_FILES["file"]["type"] == "image/png" )
&& in_array($extension, $allowedExts)){
echo '<br><br><img src="uploads/'.rawurlencode($_FILES["file"]["name"]).'" style="height:30%;"><br>';
} else {
echo '<br><br><a href="uploads/'.rawurlencode($_FILES["file"]["name"]).'"><p><strong>Download File</strong></p></a><br>';
}
}

Answer

You may write a handler for such image.

echo '<br><br><a href="uploads/handle.php?imagename='.rawurlencode($_FILES["file"]["name"]).'"><p><strong>Download File</strong></p></a><br>';

And this is how you write the handle.php

<?php
header('Content-Type: image/jpeg');
$src = "image path goes here".$_GET['imagename']; 
readfile($src);
unlink("image path goes here".$_GET['imagename']);
?>