PHP Classes

File: saveFileWithUniqueName.php

Recommend this page to a friend!
  Classes of ra br   PHP Upload File Save to Directory with Unique Name   saveFileWithUniqueName.php   Download  
File: saveFileWithUniqueName.php
Role: Example script
Content type: text/plain
Description: Function to verify unique name in uploaded file
Class: PHP Upload File Save to Directory with Unique Name
Save an uploaded file with a unique name
Author: By
Last change:
Date: 10 months ago
Size: 900 bytes
 

Contents

Class file image Download
<?php

function saveFile($file, $path) {
   
$count = 0;
   
$originalFileName = $file['name'];
   
$fileName = $originalFileName;

    while (
file_exists($path . '/' . $fileName)) {
       
$count++;
       
$fileName = pathinfo($originalFileName, PATHINFO_FILENAME) . '(' . $count . ').' . pathinfo($originalFileName, PATHINFO_EXTENSION);
    }

    if (!
file_exists($path)) {
       
mkdir($path, 0777, true);
    }

   
move_uploaded_file($file['tmp_name'], $path . '/' . $fileName);

    if (
file_exists($path . '/' . $fileName)) {
        return
$fileName;
    } else {
        return
false;
    }
}

/**
 * How to USE
 */

/*
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $uploadDir = 'uploads';
    $uploadedFile = $_FILES['file'];

    $savedFileName = saveFile($uploadedFile, $uploadDir);

    // Here you can save the information to a DataBase
}
*/