How to upload and download file with php


How to upload and download file with php



Stp1- create a index.php file

<html>
<head>
<title>PHP File Upload example</title>
</head>
<body>

<?php

if(isset($_POST['submit_file'])) :
if(isset($_FILES['file'])) :
$filepath = "images/" . $_FILES["file"]["name"];
if(file_exists($filepath)) {

// if file found
echo 'File Exists!';
} else {
if(move_uploaded_file($_FILES['file']['tmp_name'], $filepath)) {

// file uploaded
echo '<img src="' . $filepath . '" alt=""  height="100px" width="100px"> <br> <a href="download.php?url=' . $filepath . '">Download</a>';
} else {

// file couldn't be uploaed
echo 'Image couldn\'t be uploaded';
}
}
endif;
endif;

?>

<form action=" " method="POST" enctype="multipart/form-data">
Select image :
<input type="file" name="file"><br/>
<input type="submit" value="Upload" name="submit_file"> <br/>

</form>
</body>
</html>

Step2-create a images folder and download.php file
<?php
$file_path = $_REQUEST['url'] ?? '';
if (file_exists($file_path)) {

    header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
    header("Content-Type: application/zip");
    header("Content-Disposition: attachment; filename=" . $file_path);
    readfile($file_path);
    die();
} else {
    die("Error: File not found.");
}
?>
Previous
Next Post »
Thanks for your comment