Search code examples
phpjavascriptuploadify

Uploadify - Rename File


I'm using uploadify, but I'm not too sure how to edit the php to rename the uploaded files.

Basically, a user can upload upto 4 files and they should be named something like 1-img-1, 1-img-2, 1-img-3, 1-img-4 - the first number being a user id (which can be accessed via the POST).

Here's the uploadify php script:

<?php
/*
UploadiFive
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
*/

// Set the uplaod directory
$uploadDir = '/img/listing_images/';

// Set the allowed file extensions
$fileTypes = array('jpg', 'jpeg', 'gif', 'png'); // Allowed file extensions

$verifyToken = md5('unique_salt' . $_POST['timestamp']);

if (!empty($_FILES) && $_POST['token'] == $verifyToken) { $i++;
    $tempFile   = $_FILES['Filedata']['tmp_name'];
    $uploadDir  = $_SERVER['DOCUMENT_ROOT'] . $uploadDir;
    $targetFile = $uploadDir . $_FILES['Filedata']['name'];

    // Validate the filetype
    $fileParts = pathinfo($_FILES['Filedata']['name']);
    if (in_array(strtolower($fileParts['extension']), $fileTypes)) {
    // Save the file
    move_uploaded_file($tempFile, $targetFile);
    echo 1;

} else {

    // The file type wasn't allowed
    echo 'Invalid file type.';

}
}
?>

Just wondering if someone could help to show me how I would rename the uploaded files?


Solution

  • generate a unique key and safe the file with that name, untested example:

    $fileParts = pathinfo($_FILES['Filedata']['name']);
    $unique_hash = hash_hmac("md5", file_get_contents($_FILES['Filedata']['name']), SALT);
    $targetFile = $uploadDir . $unique_hash . $fileParts['extension'];