maverickd
07-11-2012, 10: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);
}
?>
<?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);
}
?>