Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- form.html
- <!DOCTYPE html>
- <html>
- <head>
- <title>PHP File Uploads</title>
- <meta charset="UTF-8">
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css">
- </head>
- <body>
- <h1>PHP File Uploads</h1>
- <form method="post" enctype="multipart/form-data" action="handleFile.php">
- <label for="file1"> Select File to upload</label>
- <input type="file" name="file1" id="file1" required>
- <button type="submit">Upload</button>
- </form>
- </body>
- </html>
- handlefile.php
- <?php
- // Check if the uploads directory exists; if not, create it
- $uploadDir = __DIR__ . "/uploads/";
- if (!is_dir($uploadDir)) {
- mkdir($uploadDir, 0777, true);
- }
- // Check if a file was uploaded
- $data = $_FILES["file1"];
- $code = $data["error"];
- if ($code !== UPLOAD_ERR_OK) {
- echo "Error uploading file: " . $code;
- exit("Upload Error");
- }
- $src = $data["tmp_name"];
- $dest = $uploadDir . basename($data["name"]);
- // Move the uploaded file to the destination directory
- if (move_uploaded_file($src, $dest)) {
- echo "File uploaded successfully.<br>",
- "Size: ", $data["size"], " bytes<br>",
- "Type: ", $data["type"], "<br>";
- // Provide a preview or download link based on file type
- $fileType = $data["type"];
- $fileUrl = "uploads/" . basename($data["name"]);// Check if the uploaded file is an image
- if (strpos($fileType, 'image') === 0) {
- echo "<h2>File Preview:</h2>";
- echo "<img src='$fileUrl' alt='File Preview' style='max-width: 500px;'><br>";
- } else {
- // Provide a download link for non-image files
- echo "<h2>Download File:</h2>";
- echo "<a href='$fileUrl' download>Click here to download the uploaded file</a><br>";
- }
- } else {
- exit("Failed to move uploaded file.");
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement