...

View Full Version : Seeking help with random file names



maverickd
07-11-2012, 11:29 PM
Hello, I have been fiddling with a code I found online which uploads files, but once I upload them it keeps their names and so I began trying to create unique names for each file. I was able to make each file name unique but it kept leaving off extension and so I was wondering if somebody could help me with it.



<?php

$upload_dir = 'uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');
$random_digit= rand(0,100);


if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}


if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){

$pic = $_FILES['pic'];

if(!in_array(get_extension($pic['name']),$allowed_ext)){
exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
}


if(move_uploaded_file($pic['tmp_name'],$upload_dir.$pic['name'].$random_digit)){
exit_status('File was uploaded successfuly!');
}

}

exit_status('Something went wrong with your upload!');


// Helper functions

function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}

function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>

firepages
07-12-2012, 02:05 AM
you are not actually adding the extension to your new filename....


$ext=get_extension($pic['name']);
if(!in_array($ext,$allowed_ext)){
exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
}


if(move_uploaded_file($pic['tmp_name'],$upload_dir.$pic['name'].$random_digit.'.'.$ext)){
exit_status('File was uploaded successfuly!');
}

maverickd
07-12-2012, 02:36 AM
you are not actually adding the extension to your new filename....


$ext=get_extension($pic['name']);
if(!in_array($ext,$allowed_ext)){
exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
}


if(move_uploaded_file($pic['tmp_name'],$upload_dir.$pic['name'].$random_digit.'.'.$ext)){
exit_status('File was uploaded successfuly!');
}


Ah, that makes a lot of sense haha, thanks a lot for clearing that up!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum