Skip to content

Instantly share code, notes, and snippets.

@natecavanaugh
Created May 7, 2012 22:27
Show Gist options
  • Save natecavanaugh/2631022 to your computer and use it in GitHub Desktop.
Save natecavanaugh/2631022 to your computer and use it in GitHub Desktop.
upload
function checkFiles($filearr, $uploaddir, $requireimage=false, $filter=array())
{
$maxsize = ini_get("upload_max_filesize");
$final = array('errors' => array(),
'files' => array(),
'result' => array()
);
foreach($filearr as $input => $filearray){
//for every file upload field
if(is_array($filter)){
$use = !in_array($input, $filter) ? true : false;
} else {
$use = !preg_match($filter, $input) ? true : false;
}
if($use){
foreach($filearray as $ind => $val){
//for every element in each upload
if ($ind == "name") {
$file_pieces = remExtension($val, true);
if(count($file_pieces) == 2){
$val = dirify($file_pieces[0]).$file_pieces[1];
}
$name = time().'_'.$val;
}
if ($ind == "tmp_name") {
$tmp_name = $val;
}
if ($ind == "size") {
$size = $val;
}
if ($ind == "type") {
$type = $val;
}
if ($ind == "error") {
$error = $val;
}
}
if (file_exists($tmp_name)) {
$final['files'][$input] = $_FILES[$input];
$final['files'][$input]['name'] = $name;
unset($final['files'][$input]['tmp_name']);
$max_size = (isset($_POST['MAX_FILE_SIZE'])) ? $_POST['MAX_FILE_SIZE'] : (intval(ini_get('upload_max_filesize')) * 1024 * 1024);
if ($size > $max_size) {
if ($max_size < 1024) {
$maxfilesize = "$max_size bytes";
} else if ($max_size < 1048576) {
$maxfilesize = number_format($max_size/1024) ." KB";
} else {
$maxfilesize = number_format($max_size/1048576) ." MB";
}
$final['errors'][$input][] = sprintf(L_ERR_UPLOAD_HEAVY, $name, $maxsize);
} else if ($final['files'][$input]['error'] == 1) {
$final['errors'][$input][] = sprintf(L_ERR_UPLOAD_HEAVY, $name, $maxsize);
}
if ($requireimage) {
if (!getimagesize($tmp_name)) {
$final['errors'][$input][] = sprintf(L_ERR_UPLOAD_NOT_IMAGE, $name);
}
}
if (!empty($final['errors'])) {
$final['result'][$input]['uploaded'] = 0;
} else {
if (is_dir($uploaddir)) {
$upfile = "$uploaddir/$name";
if (move_uploaded_file($tmp_name, $upfile)) {
if (substr(sprintf('%o', fileperms($upfile)), -3) < 644) {
chmod($upfile, 0644);
}
$final['result'][$input]['uploaded'] = 1;
if (getimagesize($upfile)) {
$dims = getimagesize($upfile);
$final['files'][$input]['width'] = $dims[0];
$final['files'][$input]['height'] = $dims[1];
}
} else {
$final['result'][$input]['uploaded'] = 0;
}
} else {
$final['result'][$input]['uploaded'] = 0;
$final['errors'][$input][] = L_ERR_UPLOAD_MISSING_DIR;
}
}
}
}// filter
}
return $final;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment