PHP Classes

PHP Upload File Unique Name: Process uploads and store them with unique names

Recommend this page to a friend!
  Info   View files Example   View files View files (2)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2023-11-22 (1 month ago) RSS 2.0 feedNot yet rated by the usersTotal: 54 This week: 1All time: 10,514 This week: 108Up
Version License PHP version Categories
un 1.0The PHP License5PHP 5, Files and Folders, Validation, G...
Description 

Author

This package can process uploads and store them with unique names.

It provides a PHP script to process an uploaded file by checking if it has one of the supported file name extensions.

The script also checks if the file has the name of a file that has not yet been uploaded.

If the file passes all the checks, the script moves the file to a separate directory using a hash of the original file name to create a new file named for the stored file.

Picture of Ahmed Abdulla
  Performance   Level  
Name: Ahmed Abdulla <contact>
Classes: 11 packages by
Country: Bahrain Bahrain
Innovation award
Innovation award
Nominee: 1x

Recommendations

Example

<?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.";
}
?>


  Files folder image Files  
File Role Description
Accessible without login Plain text file upload.php Example upload page
Accessible without login Plain text file index.html Data upload page

 Version Control Unique User Downloads Download Rankings  
 0%
Total:54
This week:1
All time:10,514
This week:108Up