snippet php upload file

25 01 2008

pada suatu kesempatan, mungkin kita butuh fungsi untuk mengupload file. berikut ini ada snippet yg saya dapat dari http://snippets.bigtoach.com. semoga berguna.

<?php
function upload_files($form, $location='./', $types=array()){
    $ret = array();
    $location = $location === NULL || $location === '' ? './' : $location;
    $location = $location{(strlen($location) - 1)} === '/' ? $location : $location . '/';
    $types = is_array($types) ? $types : array($types);
    if(!is_dir($location) || !is_writable($location) || !isset($_FILES[$form])){
        return;
    }
    if(is_array($_FILES[$form]['error'])){
        foreach($_FILES[$form]['error'] as $key=>$value){
            $ret[$key] = array('uploaded'=>false, 'error'=>$value, 'typematch'=>false, 'name'=>$_FILES[$form]['name'][$key], 'mime'=>$_FILES[$form]['type'][$key], 'size'=>$_FILES[$form]['size'][$key]);
            if($value == UPLOAD_ERR_OK) {
                $ret[$key]['uploaded']  = true;
                if(sizeof($types) === 0 || in_array(substr($_FILES[$form]['name'][$key], strtolower(strrpos($_FILES[$form]['name'][$key], '.')+1)), $types)){
                    move_uploaded_file( $_FILES[$form]['tmp_name'][$key], $location . $_FILES[$form]['name'][$key]);
                    $ret[$key]['typematch'] = true;
                }
            }
        }
    }else{
        $ret = array('uploaded'=>false, 'error'=>$_FILES[$form]['error'], 'typematch'=>false, 'name'=>$_FILES[$form]['name'], 'mime'=>$_FILES[$form]['type'], 'size'=>$_FILES[$form]['size']);
        if($_FILES[$form]['error'] == UPLOAD_ERR_OK) {
            $ret['uploaded'] = true;
            if(sizeof($types) === 0 || in_array(strtolower(substr($_FILES[$form]['name'], strrpos($_FILES[$form]['name'], '.')+1)), $types)){
                move_uploaded_file( $_FILES[$form]['tmp_name'], $location . $_FILES[$form]['name']);
                $ret['typematch'] = true;
            }
        }
    }
    return $ret;
}
?>

cara pakainya:

<?php
// make form as a single file upload with formname 'file'
$files = upload_files('file');
// uploads the single file to the current directory no matter the filetype

// make form as a single upload with formname 'image'
$files = upload_files('image', './images/', array('gif', 'jpg', 'jpeg', 'png'));
// uploads the single file to the images directory with file extensions of gif, jpg, jpeg, or png

// make a form as an array upload with formname 'images'
$files = upload_files('images',NULL,'png');
// uploads multiple files to the current directory as long as the file extension is png
?>