random()
random( $length, $numeric)
Parameters
$length | ||
$numeric |
上传/下载公共方法
uploadify_str(String $file_name, String $fileTypeExts, String $div_id, String $input_id, String $buttonText, String $js_input_id, String $button_id, $path_flag = '') : string
jquery插件上传字符串
String | $file_name | 服务器端接收的文件域的名字 |
String | $fileTypeExts | 可以上传的文件类型,多个用英文;分隔例:.flv;.mp4 |
String | $div_id | 显示进度条的div的id |
String | $input_id | 文件域的id |
String | $buttonText | 按钮显示的文字 |
String | $js_input_id | js操作的input的id |
String | $button_id | 表单提交按钮的id |
$path_flag | 字符串,有值标示不要文件大小和本地文件名,空值有大小和把的文件名 |
插件代码
<?php
/**
* 上传/下载公共方法
*
*/
class Bd_upload{
//产生随机字符
public function random($length, $numeric = 0) {
PHP_VERSION < '4.2.0' ? mt_srand((double)microtime() * 1000000) : mt_srand();
$seed = base_convert(md5(print_r($_SERVER, 1).microtime()), 16, $numeric ? 10 : 35);
$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
$hash = '';
$max = strlen($seed) - 1;
for($i = 0; $i < $length; $i++) {
$hash .= $seed[mt_rand(0, $max)];
}
return $hash;
}
/**
* 获取文件名后缀
* @author dyb 2012-12-12
* @param $filename
* @return string
*/
public function fileext($filename) {
return strtolower(trim(substr(strrchr($filename, '.'), 1)));
}
/*
* 功能:循环检测并创建文件夹
* 参数:$path 文件夹路径
* 返回:
*/
function createDir($path){
if (!file_exists($path)){
$this->createDir(dirname($path));
@mkdir($path, 0777);
}
}
//获取上传路径
function getfilepath($custom_path, $mkdir=false) {
$name1 = gmdate('Ym');
$name2 = gmdate('j');
if($custom_path)
{
$newfilename = './attachment/'.$custom_path;
$this->createDir($newfilename);
return $custom_path;
}
else
{
if($mkdir)
{
$newfilename = './attachment/'.$name1;
if(!is_dir($newfilename))
{
if(!@mkdir($newfilename,0777))
{
return 'error';
}
}
$newfilename .= '/'.$name2;
if(!is_dir($newfilename))
{
if(!@mkdir($newfilename,0777))
{
return 'error';
}
}
}
return $name1.'/'.$name2;
}
}
/**
* 上传文件
* @author dyb 2012-12-12
* @param $FILE
* @param $allowpictype 允许上传的文件类型
* @param $resize_flag 是否缩放标记
* @param $width 缩放的宽
* @param $height 缩放的高
* @return array
*/
public function file_save($FILE,$allowpictype = array(),$resize_flag = FALSE,$width = 0,$height = 0,$custom_path=''){
//检查文件大小
$FILE['size'] = intval($FILE['size']);
if(empty($FILE['size']) || empty($FILE['tmp_name']) || !empty($FILE['error'])) {
return array('status'=>'error','path'=>'无法获取上传文件大小');
}
//判断后缀
$fileext = $this->fileext($FILE['name']);
if(!in_array($fileext, $allowpictype)) {
return array('status'=>'error','path'=>'不允许上传该格式的文件');
}
//获取目录
$date_filepath = $this->getfilepath($custom_path, true);
if($date_filepath=='error') {
return array('status'=>'error','path'=>'创建目录失败');
}
//上传目录
$filepath="./attachment/".$date_filepath;
$filepath = rtrim($filepath, '/').'/';
if (function_exists('realpath') AND @realpath($filepath) !== FALSE){
$filepath = str_replace("\\", "/", realpath($filepath));
}
$filepath = preg_replace("/(.+?)\/*$/", "\\1/", $filepath);
//本地上传
$mtime = explode(' ', microtime());
$new_filename = "$mtime[1]".$this->random(4);
$new_filename_all = "/".$new_filename.".$fileext";
$result_path = "/attachment/".$date_filepath.$new_filename_all;
$new_name = $filepath.$new_filename_all;
$tmp_name = $FILE['tmp_name'];
if(@copy($tmp_name, $new_name)) {
@unlink($tmp_name);
} elseif((function_exists('move_uploaded_file') && @move_uploaded_file($tmp_name, $new_name))) {
} elseif(@rename($tmp_name, $new_name)) {
} else {
return array('status'=>'error','path'=>'无法转移临时图片到服务器指定目录');
}
//检查是否图片
// if(function_exists('getimagesize')) {
// $tmp_imagesize = @getimagesize($new_name);
// list($tmp_width, $tmp_height, $tmp_type) = (array)$tmp_imagesize;
// $tmp_size = $tmp_width * $tmp_height;
// if($tmp_size > 16777216 || $tmp_size < 4 || empty($tmp_type) || strpos($tmp_imagesize['mime'], 'flash') > 0) {
// @unlink($new_name);
// return cplang('only_allows_upload_file_types');
// }
// }
if($resize_flag && $width>0 && $height>0){
$config['image_library'] = 'gd2';
$config['source_image'] = $new_name;
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['width'] = $width;
$config['height'] = $height;
$CI =& get_instance();
$CI->load->library('image_lib', $config);
$CI->image_lib->resize();
$CI->image_lib->clear();
// $thumbpath = $filepath."/".$new_filename."_thumb.$fileext";
// if($CI->image_lib->resize() && file_exists($thumbpath)){
// @unlink($new_name);
// rename($thumbpath, $new_name);
// }
}
return array('status'=>'success','path'=>$result_path);
}
/**
* 创建缩略图
* @param $path 原图路径
* @param $new_filename 新图名称
* @param $width 宽
* @param $height 高
* @return string
*/
public function create_thumb_image($path,$new_filename,$width = 0,$height = 0){
//上传目录
$filepath=".";
$filepath = rtrim($filepath, '/').'/';
if (function_exists('realpath') AND @realpath($filepath) !== FALSE){
$filepath = str_replace("\\", "/", realpath($filepath));
}
$filepath = preg_replace("/(.+?)\/*$/", "\\1/", $filepath);
$config['image_library'] = 'gd2';
$config['source_image'] = $filepath.$path;
$config['new_image'] = $new_filename;
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['width'] = $width;
$config['height'] = $height;
$CI =& get_instance();
$CI->load->library('image_lib', $config);
//$CI->image_lib->initialize($config);
if ( ! $CI->image_lib->resize())
{
echo $CI->image_lib->display_errors();exit;
}
return dirname($path).'/'.$new_filename;
}
public function upload_avatar($savepath, $img, $types=array(),$path=''){
//上传目录
if (empty($path)){
$filepath='./attachment/avatar/';
}else{
$filepath='.'.$path;
}
//$filepath="./attachment/avatar";
$filepath = rtrim($filepath, '/').'/';
if (function_exists('realpath') AND @realpath($filepath) !== FALSE)
{
$filepath = str_replace("\\", "/", realpath($filepath));
}
$filepath = preg_replace("/(.+?)\/*$/", "\\1/", $filepath);
//echo $filepath;exit;
$types = empty($types)? array('jpg', 'gif', 'png', 'jpeg'):$types;
$img = str_replace(array('_','-'), array('/','+'), $img);
$b64img = substr($img, 0,100);
if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $b64img, $matches))
{
$type = $matches[2];
if(!in_array($type, $types))
{
return array('error'=>1,'msg'=>'图片格式不正确','url'=>'');
}
$img = str_replace($matches[1], '', $img);
$img = base64_decode($img);
$photo = md5(date('YmdHis').rand(1000, 9999)).'.'.$type;
file_put_contents($filepath.$photo, $img);
///echo $filepath."+++++++++".$photo;exit;
if (empty($path)){
$path='/attachment/avatar/';
}
return array('error'=>0,'msg'=>'保存图片成功','url'=>$path.$photo,'fileName'=>$photo);
}
return array('error'=>2,'msg'=>'请选择要上传的图片','url'=>'');
/*$result_array = array('src_name' => $filepath."/avatar/src/".$user_id.".png",
'big_name' => $filepath."/avatar/big/".$user_id.".png",
'middle_name' => $filepath."/avatar/middle/".$user_id.".png",
'small_name' => $filepath."/avatar/small/".$user_id.".png",
);
return $result_array;*/
}
/**
* 上传icon图标
* @param $FILE
*/
public function favicon_save($FILE){
//检查文件大小
$FILE['size'] = intval($FILE['size']);
if(empty($FILE['size']) || empty($FILE['tmp_name']) || !empty($FILE['error'])) {
return array('status'=>'error','path'=>'无法获取上传图标大小');
}
//判断名称
if($FILE['name']!='favicon.ico') {
return array('status'=>'error','path'=>'不允许上传该名称的图标');
}
$fileext = $this->fileext($FILE['name']);
//上传目录
$filepath="./attachment";
$filepath = rtrim($filepath, '/').'/';
if (function_exists('realpath') AND @realpath($filepath) !== FALSE){
$filepath = str_replace("\\", "/", realpath($filepath));
}
$filepath = preg_replace("/(.+?)\/*$/", "\\1/", $filepath);
//本地上传
$mtime = explode(' ', microtime());
$new_filename = "$mtime[1]".$this->random(4);
$new_filename_all = "/".$new_filename.".$fileext";
$result_path = "/attachment".$new_filename_all;
$new_name = $filepath.$new_filename_all;
$tmp_name = $FILE['tmp_name'];
if(@copy($tmp_name, $new_name)) {
@unlink($tmp_name);
} elseif((function_exists('move_uploaded_file') && @move_uploaded_file($tmp_name, $new_name))) {
} elseif(@rename($tmp_name, $new_name)) {
} else {
return array('status'=>'error','path'=>'无法转移临时图片到服务器指定目录');
}
@unlink($filepath."/favicon.ico");//删除原来的图标
@rename($new_name, $filepath."/favicon.ico");//重命名新上传的图标
return array('status'=>'success','path'=>"/attachment/favicon.ico");
}
/**
* 得到用户浏览器类型
* @author dyb
* @param $user_agent
* @return string
*/
public function getOSBrowserType($user_agent){
$user_agent = "MSIE";
if(strpos($_SERVER["HTTP_USER_AGENT"],"MSIE")){
$user_agent = "MSIE";
}
if(strpos($_SERVER["HTTP_USER_AGENT"],"Firefox")){
$user_agent = "Firefox";
}
return $user_agent;
}
/**
* 文件下载
* @author dyb
* @param $path 下载路径
* @param $name 文档名称
*/
public function download($path,$name){
if (!file_exists($path)){
header("Content-type: text/html; charset=utf-8");
echo "File not found!";
exit;
} else {
$file = fopen($path,"r");
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length: ".filesize($path));
//Header("Content-Disposition: attachment; filename=".$name);
$ua = $this->getOSBrowserType($_SERVER["HTTP_USER_AGENT"]);
$name = urldecode($name);
$encoded_filename = urlencode($name);
$encoded_filename = str_replace("+", "%20",$encoded_filename);
if (preg_match("/MSIE/", $ua)) {
header('Content-Disposition: attachment;filename="' . $encoded_filename . '"');
} else if (preg_match("/Firefox/", $ua)){
header('Content-Disposition: attachment; filename*="utf8\'\'' . $name . '"');
}else {
header('Content-Disposition: attachment; filename="' . $name . '"');
}
echo fread($file, filesize($path));
fclose($file);
}
}
/**
* jquery插件上传字符串
* @param String $file_name 服务器端接收的文件域的名字
* @param String $fileTypeExts 可以上传的文件类型,多个用英文;分隔例:*.flv;*.mp4
* @param String $div_id 显示进度条的div的id
* @param String $input_id 文件域的id
* @param String $buttonText 按钮显示的文字
* @param String $js_input_id js操作的input的id
* @param String $button_id 表单提交按钮的id
* @param $path_flag 字符串,有值标示不要文件大小和本地文件名,空值有大小和把的文件名
* @return string 插件代码
*/
public function uploadify_str($file_name, $fileTypeExts, $div_id, $input_id, $buttonText, $js_input_id, $button_id, $path_flag = ''){
$root = (PROJECT_NAME != "") ? '/'.PROJECT_NAME : '';
$timestamp = time();
$str = '<div id="'.$div_id.'"></div>';
$str .= '<input id="'.$input_id.'" name="'.$input_id.'" type="file" multiple="true" style="display: none">';
$str .= '<script type="text/javascript">';
$str .= ' $(function() {';
$str .= ' $("#'.$input_id.'").uploadify({';
$str .= ' "formData" : {';
$str .= ' "timestamp" : "'.$timestamp.'",';
$str .= ' "token" : "'.md5('unique_salt' . $timestamp).'",';
$str .= ' "fileTypeExts" : "'.$fileTypeExts.'",';
$str .= ' "file_name" : "'.$file_name.'"';
$str .= ' },';
$str .= ' "swf" : "'.$root.'/public/js/uploadify/uploadify.swf",';
$str .= ' "uploader" : "'.$root.'/admincp/common/upload/'.$path_flag.'",';
$str .= ' "queueID": "'.$div_id.'",';
$str .= ' "multi":false,'; //只允许单个文件上传
$str .= ' "fileObjName":"'.$file_name.'",'; //接收的名字
$str .= ' "buttonText":"'.$buttonText.'",';
$str .= ' "height":24,';
$str .= ' "requeueErrors":true,';
$str .= ' "width":80,';
$str .= ' "fileTypeExts":"'.$fileTypeExts.'",';
$str .= ' "removeTimeout":1,';//进度条自动消失时间,单位为秒
$str .= ' "buttonClass":"search",';
$str .= ' "onSelect":function(){';//选择文件
$str .= ' var file = $("#'.$js_input_id.'").val();';
$str .= ' if (file.length > 0){';//已有上传文件
$str .= ' alert("请先删除已有文件!");';
$str .= ' $("#'.$input_id.'").uploadify("cancel");';
$str .= ' } else {';
$str .= ' $("#'.$button_id.'").css("background-color", "#888");';
$str .= ' $("#'.$button_id.'").attr("disabled", true);';
$str .= ' }';
$str .= ' },';
$str .= ' "onUploadSuccess":function(file, data, response){';//上传成功后js操作
$str .= ' if (data == ""){';//获取后缀名
$str .= ' alert("服务器错误,文件上传失败,请重新上传!");';
$str .= ' return false;';
$str .= ' }';
$str .= ' var str = /\.[^\.]+$/.exec(data);';//获取后缀名
$str .= ' var file_url = "'.site_url("/public/admin/images/icon/").'/" + String(str).substr(1) + ".png";';//上传文件示意图标
$str .= ' var html_str = "<img src=\'"+ file_url + "\' class=\'text-img\' />";';
$str .= ' html_str += \'<a style="font-size:12px;color:red;" href="javascript:if(confirm(\\\'确定删除?\\\'))remove_video(\\\''.$js_input_id.'\\\');">删除</a>\';';
$str .= ' program_upload = $("#'.$js_input_id.'").val(data);';
$str .= ' $("#span_'.$js_input_id.'").html(html_str);';
$str .= ' $("#'.$button_id.'").css("background-color", "");';
$str .= ' $("#'.$button_id.'").attr("disabled", false);';
$str .= ' }';
$str .= ' });';
$str .= ' });';
$str .= '</script>';
return $str;
}
}
/*END 2012-12-7 15:42:05*/