Advertisement
vvccs

wt_11_fileupload

Oct 13th, 2024 (edited)
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.79 KB | None | 0 0
  1. form.html
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>PHP File Uploads</title>
  6. <meta charset="UTF-8">
  7. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css">
  8. </head>
  9. <body>
  10. <h1>PHP File Uploads</h1>
  11. <form method="post" enctype="multipart/form-data" action="handleFile.php">
  12. <label for="file1"> Select File to upload</label>
  13. <input type="file" name="file1" id="file1" required>
  14. <button type="submit">Upload</button>
  15. </form>
  16. </body>
  17. </html>
  18.  
  19. handlefile.php
  20.     <?php
  21.     // Check if the uploads directory exists; if not, create it
  22.     $uploadDir = __DIR__ . "/uploads/";
  23.     if (!is_dir($uploadDir)) {
  24.     mkdir($uploadDir, 0777, true);
  25.     }
  26.     // Check if a file was uploaded
  27.     $data = $_FILES["file1"];
  28.     $code = $data["error"];
  29.     if ($code !== UPLOAD_ERR_OK) {
  30.     echo "Error uploading file: " . $code;
  31.     exit("Upload Error");
  32.     }
  33.     $src = $data["tmp_name"];
  34.     $dest = $uploadDir . basename($data["name"]);
  35.     // Move the uploaded file to the destination directory
  36.     if (move_uploaded_file($src, $dest)) {
  37.     echo "File uploaded successfully.<br>",
  38.     "Size: ", $data["size"], " bytes<br>",
  39.     "Type: ", $data["type"], "<br>";
  40.     // Provide a preview or download link based on file type
  41.     $fileType = $data["type"];
  42.     $fileUrl = "uploads/" . basename($data["name"]);// Check if the uploaded file is an image
  43.     if (strpos($fileType, 'image') === 0) {
  44.     echo "<h2>File Preview:</h2>";
  45.     echo "<img src='$fileUrl' alt='File Preview' style='max-width: 500px;'><br>";
  46.     } else {
  47.     // Provide a download link for non-image files
  48.     echo "<h2>Download File:</h2>";
  49.     echo "<a href='$fileUrl' download>Click here to download the uploaded file</a><br>";
  50.     }
  51.     } else {
  52.     exit("Failed to move uploaded file.");
  53.     }
  54.     ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement