PHP Classes

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

Recommend this page to a friend!
     
  Info   Example   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
Not enough user ratingsTotal: 62 All time: 10,469 This week: 51Up
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 (2)  
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

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads Download Rankings  
 0%
Total:62
This week:0
All time:10,469
This week:51Up