Question

I am using Uploadify and when a person uploads the file I want the file name to be a random generated file name. Numbers would be fine.

Here is the current PHP I am using:

<?php

$targetFolder = '/uploads'; 

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

if (!empty($_FILES)) {
  $tempFile = $_FILES['Filedata']['tmp_name'];
  $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
  $targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];


// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png','doc','docx','pdf','xlsx','pptx','tiff','tif','odt','flv','mpg','mp4','avi','mp3','wav','html','htm','psd','bmp','ai','pns','eps'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);

if (in_array($fileParts['extension'],$fileTypes)) {
    move_uploaded_file($tempFile,$targetFile);
    echo '1';
} else {
    echo 'Invalid file type.';
    }
 }
?>

I tried replacing this:

$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];

with this (per this answer):

$fileParts = pathinfo($_FILES['Filedata']['name']);
$targetFile = rtrim($targetPath,'/') . '/' .rand_string(20).'.'.$fileParts['extension'];

but that did not work, in fact, it stopped the file from uploading at all.

How do I modify the script to create random file names? Note: I know almost no PHP, please make any answer clear for a beginner.

Was it helpful?

Solution

I'd use uniqid() as I have no idea what rand_string is or where it comes from, eg

$fileParts = pathinfo($_FILES['Filedata']['name']);
$targetFile = sprintf('%s/%s.%s', $targetPath, uniqid(), $fileParts['extension']);

Another thing I never do is rely on DOCUMENT_ROOT. Instead, use a path relative from the current script. For example, say your script is in the document root

$targetPath = __DIR__ . '/uploads';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top