PHP Classes

File: upload.php

Recommend this page to a friend!
  Classes of Ahmed Abdulla   PHP Upload File Unique Name   upload.php   Download  
File: upload.php
Role: Example script
Content type: text/plain
Description: upload page
Class: PHP Upload File Unique Name
Process uploads and store them with unique names
Author: By
Last change:
Date: 6 months ago
Size: 1,351 bytes
 

Contents

Class file image Download
<?php
// Define the path to the upload directory
$targetDir = "uploads/";
// Make sure the upload directory exists
if (!file_exists($targetDir)) {
   
mkdir($targetDir, 0777, true);
}

if (isset(
$_FILES["file"])) {
   
// Get the file extension
   
$fileType = strtolower(pathinfo(basename($_FILES["file"]["name"]), PATHINFO_EXTENSION));
   
// Allowed file types
   
$allowedTypes = ['jpg', 'png', 'jpeg', 'gif'];

   
// Check if the file is an image
   
if (in_array($fileType, $allowedTypes)) {
       
// Generate a unique name for the file
       
$uniqueFileName = md5(time() . rand()) . "." . $fileType;
       
$uniqueFilePath = $targetDir . $uniqueFileName;

       
// Check if file already exists
       
if (!file_exists($uniqueFilePath)) {
           
// Try to upload the file
           
if (move_uploaded_file($_FILES["file"]["tmp_name"], $uniqueFilePath)) {
                echo
"The file " . htmlspecialchars($uniqueFileName) . " has been uploaded.";
            } else {
                echo
"Sorry, there was an error uploading your file.";
            }
        } else {
            echo
"File already exists. Please try again.";
        }
    } else {
        echo
"Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    }
} else {
    echo
"No file was uploaded. Please try again.";
}
?>