Skip to content

Instantly share code, notes, and snippets.

@tkdave
Created September 13, 2012 21:07
Show Gist options
  • Save tkdave/3717647 to your computer and use it in GitHub Desktop.
Save tkdave/3717647 to your computer and use it in GitHub Desktop.
PHP4 upload handler
<?php
class Bumpslide_Util
{
static public function CreatePath( $path ) {
$folders=explode('/',$path);
$existingPath= (($os = getenv('OS')) && (substr_count($os, 'Win')>0)) ? '' : '/';
foreach($folders as $folder){
if($folder=='') continue;
if(!file_exists($existingPath.$folder)){ @mkdir($existingPath.$folder); }
$existingPath.=$folder.'/';
}
if (file_exists($path)) return true;
return false;
}
/**
* Store an uploaded file to a unique folder within the upload path
*
* Return path relative to provided upload path.
*/
static public function ProcessUpload( $file, $upload_path, $sub_folder='', $folder_date_format='Y-m', $memory_limit='500M', $time_limit=20 ) {
ini_set('memory_limit', $memory_limit);
set_time_limit($time_limit);
if($sub_folder=='') $sub_folder = md5( time() . $file['tmp_name'] );
// sanitize upload path (no final /)
$upload_path = dirname( $upload_path.'/.' );
$path = sprintf('%s/%s/%s/', $upload_path, date( $folder_date_format ), $sub_folder );
if(!self::CreatePath( $path )) {
throw new Exception('Unable to create upload folder: '.$path );
} elseif ($file['error'] != UPLOAD_ERR_OK) {
throw new Exception( self::UploadErrorMessage( $file['error'] ) );
} else {
$temp_file = $file["tmp_name"];
$saved_file = $path . $file["name"];
if( move_uploaded_file($temp_file, $saved_file ) ) {
return substr( $saved_file, strlen($upload_path)+1 );
} else {
throw new Exception("Unable to move uploaded file $temp_file to $saved_file");
}
}
return false;
}
static public function UploadErrorMessage($error_code) {
switch ($error_code) {
case UPLOAD_ERR_INI_SIZE:
return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
case UPLOAD_ERR_FORM_SIZE:
return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
case UPLOAD_ERR_PARTIAL:
return 'The uploaded file was only partially uploaded';
case UPLOAD_ERR_NO_FILE:
return 'No file was uploaded';
case UPLOAD_ERR_NO_TMP_DIR:
return 'Missing a temporary folder';
case UPLOAD_ERR_CANT_WRITE:
return 'Failed to write file to disk';
case UPLOAD_ERR_EXTENSION:
return 'File upload stopped by extension';
default:
return 'Unknown upload error';
}
}
}
@tkdave
Copy link
Author

tkdave commented Sep 13, 2012

Usage:
$saved_file = Bumpslide_Util::ProcessUpload( $_FILES['FileData'], dirname(FILE).'/uploads/' );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment