Skip to content

Write a program to upload and download files.

File: upload.php

<?php

// Directory for storing uploaded files

$uploadDir = ‘uploads/’;

if (!is_dir($uploadDir)) {

    mkdir($uploadDir, 0755, true);

}

// Handle File Upload

if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’ && isset($_FILES[‘file’])) {

    $fileName = basename($_FILES[‘file’][‘name’]);

    $targetFile = $uploadDir . $fileName;

    if (move_uploaded_file($_FILES[‘file’][‘tmp_name’], $targetFile)) {

        echo “File uploaded successfully: $fileName<br>”;

    } else {

        echo “File upload failed.<br>”;

    }

}

// Display Uploaded Files

$files = array_diff(scandir($uploadDir), [‘.’, ‘..’]);

?>

<!DOCTYPE html>

<html lang=”en”>

<head>

    <meta charset=”UTF-8″>

    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

    <title>Upload and Download Files</title>

</head>

<body>

    <h1>File Upload and Download</h1>

    <!– File Upload Form –>

    <form action=”index.php” method=”post” enctype=”multipart/form-data”>

        <label for=”file”>Choose a file to upload:</label>

        <input type=”file” name=”file” id=”file” required>

        <button type=”submit”>Upload File</button>

    </form>

    <h2>Uploaded Files</h2>

    <ul>

        <?php foreach ($files as $file): ?>

            <li>

                <a href=”download.php?file=<?php echo urlencode($file); ?>”>

                    <?php echo htmlspecialchars($file); ?>

                </a>

            </li>

        <?php endforeach; ?>

    </ul>

</body>

</html>

File: download.php

<?php

// Directory for storing uploaded files

$uploadDir = ‘uploads/’;

if (isset($_GET[‘file’])) {

    $file = basename($_GET[‘file’]);

    $filePath = $uploadDir . $file;

    if (file_exists($filePath)) {

        // Send file for download

        header(‘Content-Description: File Transfer’);

        header(‘Content-Type: application/octet-stream’);

        header(‘Content-Disposition: attachment; filename=”‘ . basename($file) . ‘”‘);

        header(‘Content-Length: ‘ . filesize($filePath));

        readfile($filePath);

        exit;

    } else {

        echo “File not found.”;

    }

} else {

    echo “No file specified.”;

}

Explanation:

  1. Upload Directory: The uploads/ folder is created dynamically if it doesn’t exist.
  2. Upload Logic:
    • The index.php file handles file uploads using move_uploaded_file.
    • Displays uploaded files in a list with links for downloading.
  3. Download Logic:
    • The download.php script reads the file from the server and forces a download using appropriate HTTP headers.

How to Use:

  1. Save index.php and download.php in the same directory on a PHP-enabled server.
  2. Create an uploads/ folder in the same directory or let the script create it automatically.
  3. Access index.php in your browser to upload files.
  4. Click on the file name to download the uploaded files.