Home > Article > Backend Development > PHP file upload_PHP tutorial
A PHP file upload example, it can support txt, rar, zip, jpg, jpeg, gif, png, swf, wmv, avi, wma, mp3, mid, jar, jad, exe, html, htm, css, js ,doc' upload, music files, etc. are all available.
A PHP tutorial file upload example, it can support txt, rar, zip, jpg, jpeg, gif, png, swf, wmv, avi, wma, mp3, mid, jar, jad, exe, html, htm , css tutorial, js, doc' upload, music files, etc. are all available.
php file upload
echo'
function uploadfile($inputname)
{
$immediate=$_get['immediate'];
$attachdir='../pictures';//Upload file saving path, Do not end with /
$urldir="../pictures";
$dirtype=2;//1: Save to directory by day 2: Save to directory by month 3: Save to directory by extension It is recommended to use Save by day
$maxattachsize=2097152;//Maximum upload size, the default is 2m
$upext='txt,rar,zip,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3 ,mid,jar,jad,exe,html,htm,css,js,doc';//Upload extension
$err = "";
$msg = "";
$ upfile=$_files[$inputname];
if(!empty($upfile['error']))
{
switch($upfile['error'])
{
case '1':
$err = 'The file size exceeds the upload_max_filesize value defined in php.ini';
break;
case '2':
$err = 'The file size exceeds the html Defined max_file_size value';
break;
case '3':
$err = 'File upload incomplete';
break;
case '4':
$err = 'No file uploaded';
break;
case '6':
$err = 'Missing temporary folder';
break;
case '7':
$ err = 'Failed to write file';
break;
case '8':
$err = 'Upload interrupted by other extensions';
break;
case '999':
default:
$err = 'No valid error code';
}
}
elseif(empty($upfile['tmp_name']) || $upfile['tmp_name'] == 'none')$err = 'No file uploaded';
else
{
$temppath=$upfile['tmp_name'];
$fileinfo=pathinfo($upfile['name'] );
$extension=$fileinfo['extension'];
if(preg_match('/'.str_replace(',','|',$upext).'/i',$extension))
{
$filesize=filesize($temppath);
if($filesize > $maxattachsize)$err='File size exceeds '.$maxattachsize.' bytes';
else
{
switch($dirtype)
{
case 1: $attach_subdir = 'day_'.date('ymd'); break;
case 2: $attach_subdir = 'month_'. date('ym'); break;
case 3: $attach_subdir = 'ext_'.$extension; break;
}
$attach_dir = $attachdir.'/'.$attach_subdir;
if(!is_dir($attach_dir))
{
@mkdir($attach_dir, 0777);
@fclose(fopen($attach_dir.'/index.htm', 'w'));
}
php_version < '4.2.0' && mt_srand((double)microtime() * 1000000);
$filename=date("ymdhis").mt_rand(1000,9999).'.' .$extension;
$target = $urldir.'/'.$attach_subdir.'/'.$filename;
move_uploaded_file($upfile['tmp_name'],$target);
if($immediate=='1')$target='!'.$target;
$msg=str_replace('../',"",$target);
}
}
else $err='The extension of the uploaded file must be: '.$upext;
@unlink($temppath);
}
return array('err'=>$err ,'msg'=>$msg);
}
?>