本文日常整理收录一些小功能,持续更新...
前端ajax上传文件
html
HTML
<tr>
<th class="six">导入Excel表格</th>
<td class="indent"><input type="file" name="excel_file" id="excel_file"/></td>
</tr>
js
/**
* 上传文件
*/
$("#daoru").click(function(){
//用jQuery可以这样:
var fileInput=$("#excel_file")[0];
var file = fileInput.files[0]; //获得File对象(也就是你那个filemeta),这里文件是单选的,如果是多选的需要遍历fileInput.files属性来获取每一个文件
var formData = new FormData();
formData.append("excel_file", file); //FormData对象的append方法第一个参数相当于input的name属性,第二个参数就是value,可以是File对象
$.ajax({
type: "POST", //必须POST
dataType: 'json',
url: "test.php", //接收请求的URL
processData: false, //必须设置
contentType: false, //必须设置
data: formData, //直接把formData对象作为data属性的值发送
success:function(data) {
}
})
})
php
$fileData = $_FILES['excel_file'];
$fileTmpAddr = $fileData['tmp_name'];
$flag = move_uploaded_file( $fileTmpAddr, $fileDesAddr );
下载文件
/**
* 下载文件方法
* @param string $file_name 文件名
* @param string $path 文件路径
* @author 命中水、
* @date(2016.12.26)
*/
function download_flie($file_name, $path) {
header("Content-type:text/html;charset=utf-8");
$file_name = iconv("utf-8","gb2312",$file_name);
$file_path = $path.$file_name;
if(!file_exists($file_path))
{
echo "没有该文件文件";
return ;
}
$fp = fopen($file_path,"r");
$file_size = filesize($file_path);
//下载文件需要用到的头
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length:".$file_size);
Header("Content-Disposition: attachment; filename=".$file_name);
$buffer = 1024;
$file_count = 0;
while( !feof( $fp ) && $file_count < $file_size)
{
$file_con = fread($fp,$buffer);
$file_count += $buffer;
echo $file_con;
}
fclose($fp);
}
遍历指定目录文件
/**
* 遍历指定目录 列出所有文件
* @param path $folderName 目录路径
* @return array 所有文件
*/
public function searchAllFile ( $folderName )
{
$result = array();
$handle = opendir($folderName);
if ( $handle ) {
while ( ( $file = readdir ( $handle ) ) !== false ) {
if ( $file != '.' && $file != '..') {
$sonPath = $folderName . DIRECTORY_SEPARATOR . $file;
if ( is_dir ( $sonPath ) ){
$result['dir'][$sonPath] = $this->searchAllFile ( $sonPath );
} else {
$result['file'][] = $sonPath;
}
}
}
closedir($handle);
}
return $result;
}
plupload上传
前台
html
<div id="container">
<a href="javascript:;" >
<img id="pickfiles" class="photo" src='<?php if ($dishes_data['photo_url'] != '#'): ?>
<?=base_url($dishes_data['photo_url']);?>
<?php endif ?>' />
</a>
</div>
js
var uploader = new plupload.Uploader({
runtimes : 'html5,flash,silverlight,html4',
browse_button : 'pickfiles', // you can pass in id...
container: document.getElementById('container'), // ... or DOM Element itself
url : '<?php echo module_url('dishes/main/upload_photo')?>',
flash_swf_url : '<?php echo base_url("js/plupload/Moxie.swf");?>',
silverlight_xap_url : '<?php echo base_url("js/plupload/Moxie.xap");?>',
filters : {
max_file_size : '10mb',
mime_types: [
{title : "Image files", extensions : "jpg,png,jpeg"},
]
},
init: {
PostInit: function() {
},
FilesAdded: function(up, files) {
plupload.each(files, function(file) {
uploader.start();
return false;
});
},
FileUploaded: function(uploader,file,responseObject) {
var data = JSON.parse(responseObject.response);
$("#pickfiles").attr('src', data.file_url);
$("#photo_url").val(data.url);
},
Error: function(up, err) {
alert(err.message);
}
}
});
uploader.init();
后台
/**
* 上传图片
* @param array $allow_exts 支持的图片类型
* @param paths $file_path 图片存储目录
* @return array
*/
function upload_img($allow_exts, $file_path)
{
if(empty($allow_exts) || !is_array($allow_exts)) {
return ['status' => 202, 'msg' => '不是正确的文件类型'];
}
// 上传文件信息
$upload_file = $_FILES['file'];
// 上传文件类型
$original_ext = explode('/', $upload_file['type'])[1];
$original_name = $upload_file['name'];
// 检查文件类型
if (!in_array($original_ext, $allow_exts)) {
return ['status' => 'error', 'msg' => '文件类型不支持'];
}
$file_name = random_str(8) . uniqid('', true) . '.' . $original_ext;
// 检测字符编码
if (mb_detect_encoding($file_path, array('ASCII','GB2312','GBK','UTF-8')) == 'UTF-8') {
$file_path = iconv("UTF-8", "GB2312//IGNORE", $file_path);
}
if (!file_exists($file_path)) {
mkdir($file_path, 0777, true);
}
// 获取文件名编码
$name_code = mb_detect_encoding($file_name, array('ASCII','GB2312','GBK','UTF-8'));
/**
* 对文件名编码进行相应的转换
* 分别获取utf8和gbk文件名
*/
if ($name_code != 'UTF-8') {
$utf8_name = iconv($name_code, 'UTF-8//IGNORE', $file_name);
$gbk_name = iconv('UTF-8', 'GB2312//IGNORE', $utf8_name);
} else {
$gbk_name = iconv('UTF-8', 'GB2312//IGNORE', $file_name);
$utf8_name = $file_name;
}
// 本地文件名
$local_file_path = rtrim($file_path, '/') . '/' . $gbk_name;
// 保留文件名
$utf8_file_path = rtrim($file_path, '/') . '/' . $utf8_name;
// 移动临时文件
if (move_uploaded_file($upload_file['tmp_name'], $local_file_path)) {
return [
'status' => 200,
'msg' => '上传成功!',
'path' => $utf8_file_path,
'url' => base_url($utf8_file_path),
'unique_name' => $utf8_name,
'original_name' => $original_name
];
} else {
return ['status' => 'error', 'msg' => '上传失败!'];
}
}
删除文件
/**
* 根据绝对路径删除目录中文件
* @param string $file_path 文件相对路径
* @return bool
* @author 命中水、
* @date(2016-10-9 pm)
*/
function delete_file( $file_path ) {
$file_path = get_absolute_path($file_path);
if( unlink( $file_path ) ) return TRUE;
return FALSE;
}
/**
* 取得文件绝对路径
* @param string $file_path 文件路径
* 例:/uploads/business_code/20161104032818.jpg
* @return string 文件绝对路径
* 例:E:\WWW\xxx\web\uploads\business_code\20161104032818.jpg
* @author 命中水、
* @date(2016-11-4 am)
*/
function get_absolute_path( $file_path ) {
$file_path = str_replace('/', '\\', $file_path);
$file_path = getcwd() . $file_path; //转换绝对路径
$absolute_path = iconv("UTF-8", "GBK",$file_path); //调整编码
return $absolute_path;
}
自写表单验证
if (!function_exists('form_validate')) {
/**
* 自写方法验证表单数据
* @param array $vali_rule 验证规则
* @param string or array $method 接收数据方式 或者 待验证的数据
* @return boolean/array true 或者 验证失败说明
*/
function form_validate($vali_rule, $method = 'post')
{
if (!is_array($vali_rule)) {
return false;
}
$CI =& get_instance();
if (is_array($method)) {
$data = $method;
} else {
$data = $CI->input->$method();
}
if ($data) {
foreach ($data as $key => $value) {
if (isset($vali_rule[$key]) && !empty($vali_rule[$key])) {
$rule_list = explode('|', $vali_rule[$key]['rule']);
$msg_list = explode('|', $vali_rule[$key]['msg']);
foreach ($rule_list as $k => $rule) {
if (!in_array('required', $rule_list) && empty($value)) {
continue;
}
if (validate_rule($rule, $value) === false) {
return [
'status' => 'error',
'msg' => $msg_list[$k],
// 'data' => $vali_rule[$key]
];
};
}
}
}
}
return true;
}
}
if (!function_exists('validate_rule')) {
/**
* 具体的验证规则
* @param string $rule 验证规则名称
* @param string $value 验证值
* @return boolean
*/
function validate_rule($rule, $value)
{
$flag = true;
switch ($rule) {
case 'required':
if (empty($value)) {
$flag = false;
}
break;
case 'phone':
if (!preg_match("/^1[345678]\d{9}$/", trim($value))) {
$flag = false;
}
break;
case 'email':
if (!filter_var(trim($value), FILTER_VALIDATE_EMAIL)) {
$flag = false;
}
break;
case 'int':
if (!filter_var(trim($value), FILTER_VALIDATE_INT)) {
$flag = false;
}
break;
default:
# code...
break;
}
return $flag;
}
}
根据ip获取城市
$url = "http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
$ip = json_decode(file_get_contents($url));
if((string)$ip->code=='1'){
return false;
}
return $ip->data->city;