返回 使用前后端分离...... 登陆

使用前后端分离的web在线管理器。全程使用ajax的请求

2019-03-01 20:22:39 319

chakan.png


copy.png


createFile.pngunload.png

unload.png

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>简易版的web管理器</title>
		<link href="//netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
		<style>
			body , ul , li{margin:0;padding:0;}
			/* ul  头部操作 */
			ul {background:#f1f1f1;height:48px;width:1600px;margin:0 auto;border-radius: 8px 8px 0 0;margin-bottom:8px;}
			ul > li{list-style: none;float: left;display: flex;align-items: center;justify-content: center;height:100%;margin:0 12px;cursor: pointer;}
			
			h2{color:#0056B3}
			table{width:1600px;border:none;margin:0 auto;min-width:1400px;text-align: center;border-collapse: collapse;}
			table a img{height:25px;}
			th {background-color:#6da3da;height:40px;font-weight: 500;color:#fff;background-image:linear-gradient(to bottom , #666 , #aaa);}
			th:first-child{border-radius: 8px 0 0 0;}
			th:last-child{border-radius:0 8px  0 0;}
			td {border:1px solid #999;height:30px;}
			tr td:first-child{border-left: none;}
			tr td:last-child{border-right: none;}
			tr:last-child td {border-bottom:none;}
			.fa {cursor: pointer;width:24px;}
			.zo{color:#a06c6c;}
			.red{color:#e11;}
			.blue{color:#B3D0f0;}
			.lv{color:#87bf87;}
			.yl{color:#d8d8b3;}
			/* 隐藏 */
			.hiddBox{display: none;}
			/* 遮影 */
			.shading{width:100vw;height:100vh;background:rgba(0,0,0,.4);position: fixed;z-index: 8;top:0;left:0;display: none;}
			/* 弹窗 */
			.pop{width:600px;background-color:#f9f9f9;z-index: 99;position: fixed;left:calc(50vw - 300px);top:28%;border-radius: 10px;box-shadow:0 0 10px 2px #999;padding:0 20px;padding-bottom:28px;display: none;}
			.pop p {margin:0;}
				/* 关闭按钮 */
				.pop i {position: absolute;
    right: 14px;
    top: 2px;}
				/* 标题 */
				.pop-title{text-align: center;font-size:22px;margin:12px 0;}
				/* 文件名 */
				.pop-file{color:#e11;font-weight: 600;margin-right:4px;}
				/* 文本域 */
				.pop textarea{
					margin-top:14px;
					width: 100%;
				outline: none;
				resize: none;
    height: 260px;
    font-size: 14px;
    font-family: 楷体 , 宋体;
    border-radius: 8px;}
				/* 按钮 */
				.pop-btn{
					margin: 10px auto;
    border: 1px solid #999;
    color: #fff;
    background: #87bf87;
    outline: none;
    display: flex;
    height: 40px;
    padding: 0 20px;
    font-size: 14px;
    border-radius: 8px;
    margin-bottom: 0;
    cursor: pointer;
				}
				/*输入框*/
			.pop input{
				margin-top: 20px;
				border-radius: 5px;
				outline: none;
				border: 1px solid #999;
				height: 30px;
				width: 100%;
				margin-bottom: 10px;
			}
			/* 上传文件 */
			.pop-file{
				height:23px!important;
				background-color:#fff!important;;
			}
			
			/*弹窗提示消息*/
			.pop-msg{
				position: absolute;
				bottom:10%;left:10%;
				color: #3c763d;
				background-color: #dff0d8;
				border-color: #d6e9c6;
				border-radius:8px;
				padding:10px 20px;
				text-align: center;
				display: block;
				opacity: 0;
				z-index: 999;
				transition: all 1.2s;
			}
			.pop-msgR{
				left:70%;
				opacity: 1;
			}

			/*提示消息*/
			.title{
				position: fixed;top:50%;left:50%;
				color: #3c763d;
				background-color: #dff0d8;
				border-color: #d6e9c6;
				border-radius: 8px;
				padding:10px 20px;
				text-align: center;
				display: none;
				transform: translate(-50%,-50%);
				z-index: 999;
			}
		</style>
	</head>
	<body>
<!-- 表格 -->
<h2 style="text-align: center;margin:15px 0;">在线WEB文件管理器</h2>
<ul class="ul">
	<li data-act="main" title="主目录" ><i  class="fa fa-home fa-3x"></i>&nbsp;&nbsp;&nbsp;</li>
	<li data-act="createFile" title="新建文件" ><i  class="fa fa-file fa-2x"></i></li>
	<li data-act="createDir" title="新建目录" ><i  class="fa fa-file-o fa-2x"></i></li>
	<li data-act="unload" title="上传文件" ><i  class="fa fa-upload fa-2x"></i></li>
	<li data-act="back" title="上一目录" ><i  class="fa fa-arrow-left fa-2x"></i></li>
</ul>
<table border="0" cellspacing="0" cellpadding="0" >
	<thead>
		<tr>
			<th>编号</th>
			<th>名称</th>
			<th>类型</th>
			<th>大小</th>
			<th>可读</th>
			<th>可写</th>
			<th>可执行</th>
			<th>创建时间</th>
			<th>修改时间</th>
			<th>访问时间</th>
			<th>操作</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>1</td>
			<td>新建文本</td>
			<td>文件</td>
			<td>1.1kb</td>
			<td>可</td>
			<td>可</td>
			<td>不可</td>
			<td>2019-09-11</td>
			<td>2019-05-11</td>
			<td>2019-09-11</td>
			<td><a href="#" ><img class="small" src="images/show.png" alt="" title="查看"></a>
            <a href="#" ><img class="small" src="images/edit.png" alt="" title="修改"></a>
            <a href="#" ><img class="small" src="images/rename.png" alt="" title="重命名"></a>
            <a href="#" ><img class="small" src="images/copy.png" alt="" title="复制"></a>
            <a href="#" ><img class="small" src="images/cut.png" alt="" title="剪切"></a>
            <a href="#" ><img class="small" src="images/download.png" alt="" title="下载"></a>
            <a href="#" ><img class="small" src="images/delete.png" alt="" title="删除"></a>
        </td>
		</tr>
	</tbody>
</table>
<!-- 遮影 -->
<div class="shading"></div>
	<!-- 弹窗 -->
<div class="pop ">
	<!-- 关闭按钮 -->
	<i class="fa fa-window-close fa-2x"></i>
	<!-- 操作名称 -->
	<h3 class="pop-title">查看</h3>
	<!-- 正在操作的文本 -->
	<p ><span class="pop-file">11.txt</span>的文本内容如下:</p>
	<textarea rows="100" cols="8" >
	</textarea>
</div>

<!-- 提示 -->
<div class="title">操作成功!!!</div>
		<script src="./list/jquery.min.js" type="text/javascript"></script>
		<script src="js/main.js" type="text/javascript" charset="utf-8"></script>
	</body>
</html>
$(function(){
	var path = 'file';
	var self = null;
	var newName = null;
	var isMain = true;
	//请求获取目录
	ajax('http://www.myphp.com/07/zuoye/get.php',{path:path},renderingTable);
    
	//绑定弹窗中的关闭按钮
	$('.pop i').on('click',function(){
		console.log(this);
	});

//绑定头部的ul
$('ul > li').on('click',function(){
	var cuozuo = $(this).attr('data-act');
	switch(cuozuo){
		case 'main':  //等于主目录时
		 path = 'file';
		 if(isMain){return console.log("当前在主目录,的返回");}
		 //请求获取目录
		 ajax('http://www.myphp.com/07/zuoye/get.php',{path:path},renderingTable);
		 break;
		case 'createFile': 
		  //渲染弹窗
		  popContent('',cuozuo);
		 break;
		case 'createDir':
		  //渲染弹窗
		  popContent('',cuozuo);
		  break;
		case 'unload':
		  //渲染弹窗
		  popContent('',cuozuo);
		  break;
	}
});



/**
 * 渲染弹窗
 * @parma url 该文件
 * @parma act 操作
 * @parma text 文本
 */
function popContent(url,act,text){
	var str = ``;
	switch(act){
		case 'show':  //查看文件
			str += `
			  <i class="fa fa-window-close fa-2x"></i>
			  <h3 class="pop-title">查看</h3>
			  <p><span class="pop-file">${url}</span>的文本内容如下:</p>
			  <textarea class="pop-srk" rows="100" cols="8" disabled>	
				  ${text}
			  </textarea>
			`;
			break;
		case 'xgQr':  //修改
			str += `
			  <i class="fa fa-window-close fa-2x"></i>
			  <h3 class="pop-title">修改</h3>
			  <p><span class="pop-file">${url}</span>的文本内容如下,请输入内容并按下确定按钮:</p>
			  <textarea class="pop-srk" rows="100" cols="8">	
				  ${text}
			  </textarea>
			  <button class="pop-btn" data-act=${act} data-url=${url}  >确认修改</button>
			`;
			break;
		case 'renameQr': //重命名
			str += `
			<i class="fa fa-window-close fa-2x"></i>
			  <h3 class="pop-title">重命名</h3>
			  <p><span class="pop-file">${url}</span>的重命名,请输入新的名字并按下确定按钮:</p>
			  <input class="pop-srk" type="text" value="" />
			  <div class="pop-msg"></div>
			  <button class="pop-btn" data-act=${act} data-url=${url}  >确认修改</button>
			`;
			break;
		case 'copy': //复制
			str += `
			<i class="fa fa-window-close fa-2x"></i>
			  <h3 class="pop-title">复制</h3>
			  <p><span class="pop-file">${url}</span>的复制,请输入路劲即可:</p>
			  <input class="pop-srk" type="text" value="" />
			  <div class="pop-msg"></div>
			  <button class="pop-btn" data-act=${act} data-url=${url}  >确认复制</button>
			`;
			break;
		case 'cut': //剪切
			str += `
			<i class="fa fa-window-close fa-2x"></i>
			  <h3 class="pop-title">剪切</h3>
			  <p><span class="pop-file">${url}</span>的剪切,请输入路劲即可:</p>
			  <input class="pop-srk" type="text" value="" />
			  <div class="pop-msg"></div>
			  <button class="pop-btn" data-act=${act} data-url=${url}  >确认剪切</button>
			`;	
			break;
		case 'createFile':  //创建文件
		    str += `
		      <i class="fa fa-window-close fa-2x"></i>
		      <h3 class="pop-title">创建文件</h3>
		      <p>请输入你要创建的文件名:</p>
		      <input class="pop-srk" type="text" value="" />
		      <div class="pop-msg"></div>
		      <button class="pop-btn" data-act=${act} data-url=${url}  >确认创建</button>
		    `;	
			break;
		case 'createDir': //创建文件夹
		    str += `
		      <i class="fa fa-window-close fa-2x"></i>
		      <h3 class="pop-title">创建文件夹</h3>
		      <p>请输入你要创建的文件夹名:</p>
		      <input class="pop-srk" type="text" value="" />
		      <div class="pop-msg"></div>
		      <button class="pop-btn" data-act=${act} data-url=${url}  >确认创建</button>
		    `;
		    break;
		case 'unload'://上传文件	
		  str += `
		    <i class="fa fa-window-close fa-2x"></i>
		    <h3 class="pop-title">上传文件</h3>
		    <p>请选择你要上传的文件</p>
		    <input  class="pop-file pop-srk" id="file" type="file" name="file" value="" />
		    <div class="pop-msg"></div>
		    <button class="pop-btn" data-act=${act} data-url=${url}  >确认上传</button>
		  `;
		  break;
	}
	//设置jq
	$('.pop').html(str);
	closePop(true);
	//绑定关闭按钮
	$('.pop i').on('click',function(){
		closePop(false);
	});

	//绑定按钮
	$('.pop-btn').on('click',function(){
		newName =  $('.pop .pop-srk')[0] > 1 ? $('.pop .pop-srk').val().trim() : '22222';
		var act = $(this).attr('data-act');
		if($('.pop .pop-srk').val().trim() == 0){
			/*
			//用时间戳当判断
			window.time = window.time ? window.time : 0;
			var nowTime = new Date().getTime();
			if(nowTime - window.time <= 2000){
				console.log('动画执行中,返回!!!');
			}
			window.time = nowTime;
			*/

            //阻止用户连续点击,用提示类的属性来判断
			if($('.pop-msg').css('opacity') != '0'){
				return console.log("动画执行中,111返回!!!");
			}

            $('.pop-msg').text('名字不能为空!').addClass('pop-msgR');
            setTimeout(function(){
                $('.pop-msg').removeClass('pop-msgR');
			},2000);
			return ;
		}
		
		//如果是复制
		if(act == 'copy'){
			var nowLujin = newName;
			var list = $('.pop-file').text().trim().split('/');
			newName = list[0].toString() + '/' + newName +'/'+ list[1];
		//如果是剪切	
		}else if(act == 'cut'){
			var nowLujin = newName;
			var list = $('.pop-file').text().trim().split('/');
			newName = list[0].toString() + '/' + newName ;
		//如果是创建文件或创建文件夹
		}else if(act == 'createFile' || act == 'createDir'){ 
			$(this).attr('data-url',path+'/'+$('.pop input').val().trim())
		//上传文件	
		}else if(act == 'unload'){
			//创建表单
			var formData = new FormData();
			//添加数据
            formData.append('file',document.getElementsByName('file')[0].files[0]);
            formData.append('act',act);
			
			//此处是用ajax上传文件给后台
            $.ajax({
	              url: 'http://www.myphp.com/07/zuoye/caozuo.php',	
                  type:'post',
				  data: formData,
				  processData : false , //设置数据不需要进行处理  ,  重要
				  contentType : false , //设置发送的数据不进行处理  , 重要  后台才能接受到文件和数据等。
				  success : function(res){
					  changeData(JSON.parse(res));
				  }
            });
			closePop(false);
			return;
		}
		
		
			
		//请求后台数据
		ajax('http://www.myphp.com/07/zuoye/caozuo.php',{file:$(this).attr('data-url'),act:act,text:$('.pop textarea').val(),newName:newName,dir:$('.pop input').val()},changeData,'post');
		closePop(false);
	});
}

/**
 * 弹窗动画
 */
function closePop(bool){
	if(bool){
		$(".pop").slideDown(400);
		$(".shading").slideDown(100);
	}else{
		$(".pop").slideUp(350);
		$(".shading").slideUp(200);
	}
}

/**
 * 请求数据
 */
function ajax(url,data,fun,method = 'GET'){
	$.ajax({
	      method:method,
	      url:url,
	      data: data,
	     success(res){
			 try{
			 	dataAll = JSON.parse(res);
				fun(dataAll);
			 }catch(e){
				alert("数据返回错误!!!");
			 }
	     },
	     error(e){
			 console.log(e);
			  alert("请求失败,2秒后刷新页面!!!");
			  setTimeout("location.href = location.href",2000);
	     }
	});
}

/**
 * i对应的操作请求成功
 */
function changeData(res){
	console.log(res);
	//判断是否为提示消息
	if(res.act == 'title'){
		//是否有返回新名字  重名操作
		if(res.cuozuo && res.cuozuo == 'renameQr'){
			$(self).parent().attr('data-url',path+"/"+res.newName).parent().find('td:nth-child(2)').text(res.newName);
		//复制操作	
		}else if(res.cuozuo && (res.cuozuo == 'copy' || res.cuozuo == 'cut')){
			//请求获取目录
			ajax('http://www.myphp.com/07/zuoye/get.php',{path:path},renderingTable);
		//删除操作	
		}else if(res.cuozuo && res.cuozuo == 'del'){
			//请求获取目录
			ajax('http://www.myphp.com/07/zuoye/get.php',{path:path},renderingTable);
		//创建操作	
		}else if(res.cuozuo && (res.cuozuo == 'createFile' || res.cuozuo == 'createDir')){
			//请求获取目录
			ajax('http://www.myphp.com/07/zuoye/get.php',{path:path},renderingTable);
		}
		
		
		
        setTimeout(function () {
            $('.title').text(res.msg).slideDown(200).delay(1500).slideUp(200);
        },500);
	}else{
		popContent(res.url,res.act,res.data);
	}
}



/**
 * 渲染数据
 */
function renderingTable(res){
	var list = res.data;
	let str;
	for(var i=0;i<list.length;i++){
		str += `
			<tr>
				<td>${(i+1)}</td>
				<td>${list[i].name}</td>
				<td>${list[i].type == 'file' ? '<i class="fa fa-file-text-o fa-lg" title="文件" ></i>' : '<i class="fa fa-file-o fa-lg" title="文件夹"></i>'}</td>
				<td>${list[i].size}</td>
				<td>${list[i].isKd ? '<i class="fa   fa-hand-peace-o fa-lg"></i>' : '<i class="fa  fa-hand-stop-o fa-lg" ></i>'}</td>,
				<td>${list[i].isKx ? '<i class="fa   fa-hand-peace-o fa-lg"></i>' : '<i class="fa  fa-hand-stop-o fa-lg"></i>'}</td>,
				<td>${list[i].isRun ? '<i class="fa   fa-hand-peace-o fa-lg"></i>' : '<i class="fa  fa-hand-stop-o fa-lg"></i>'}</td>,
				<td>${list[i].ctime}</td>
				<td>${list[i].atime}</td>
				<td>${list[i].mtime}</td>
				<td data-url="${list[i].url}">
					<i class="fa  lv fa-shower fa-lg" title="查看" data-act='show'></i>
			`;
		if(list[i].type == 'file'){
			str += `		<i class="fa  zo fa-pencil fa-lg" title="修改" data-act='xg'></i>
					<i class="fa  yl fa-envelope fa-lg" title="重命名" data-act='rename'></i>
					<i class="fa blue  fa-copy fa-lg" title="复制" data-act='copy'></i>
					<i class="fa  red fa-cut fa-lg" title="剪切" data-act='cut'></i>
					<i class="fa  lv fa-arrow-circle-down fa-lg" title="下载" data-act='dow'></i>
					<i class="fa  red fa-delicious fa-lg" title="删除" data-act='del'></i>
			`;
		}else{
			str += `		<i class="fa  yl fa-envelope fa-lg" title="重命名" data-act='rename'></i>
					<i class="fa blue  fa-copy fa-lg" title="复制" data-act='copy'></i>
					<i class="fa  red fa-cut fa-lg" title="剪切" data-act='cut'></i>
					<i class="fa  red fa-delicious fa-lg" title="删除" data-act='del'></i>
			`;
		}
				str += `	</td>
			</tr>`;
	}
	$('tbody').html(str);
	//数据渲染完成
	//根据每个操作对应的显示弹窗
	$('table td:last-child i').on('click',function(){
		var act = $(this).attr('data-act');
		//查看或修改
		if(act == 'show' || act == 'xg'){
			//请求后台数据
			ajax('http://www.myphp.com/07/zuoye/caozuo.php',{file:$(this).parent().attr('data-url'),act:act},changeData,'post');
		//重命名	
		}else if(  act == 'rename'){
			//显示弹窗
			popContent($(this).parent().attr('data-url'),"renameQr");
			self = this;
		//复制	 || 剪切
		}else if(act == 'copy' || act == 'cut'){
			//显示弹窗
			popContent($(this).parent().attr('data-url'),act);
		}

        //下载
		if(act == 'dow'){
			//访问下载链接
			location.href = location.href+"caozuo.php?act=dow&file="+$(this).parent().attr('data-url');
		}
		
		//删除
		if(act == 'del'){
			if(window.confirm("您确定要删除嘛?删除之后无法恢复哟!!!")){
			  //location.href = location.href+"caozuo.php?act=del&file="+$(this).parent().attr('data-url')+"&wangzhi="+location.href;
			  //请求后台数据
			  ajax('http://www.myphp.com/07/zuoye/caozuo.php',{file:$(this).parent().attr('data-url'),act:act},changeData,'post');
			}
		}
		
		//渲染弹窗
		//popContent($(this).parent().attr('data-url'),$(this).attr('data-act'));
	});

}

});
<?php
	include "function.php";

	@$act = $_REQUEST['act'];
	@$fileName = $_REQUEST['file'];
	@$wangzhi = $_REQUEST['wangzhi'];
	$data = [
		'status' => 0,
		'data' => [],
		'act' => $act,
		'url' => $fileName,
		'msg' => '请求成功'
	];

	switch(@$act){
		case 'show': //查看
			//调用查看函数
			$data['data'] = read_file($fileName);
			$data['msg'] = '请求文件内容成功返回';
			break;
		case 'xg': //修改  ,先返回数据给用户.用户按下确认时在来处理
			$data['data'] = read_file($fileName);
			$data['act'] = 'xgQr';
			break;
		case 'xgQr': //修改确认
			$text = $_POST['text'];
			$mes = write_file($fileName,$text,false);
			$data['msg'] = $mes;
			$data['act'] = 'title'; //提示用户
			break;
		case 'renameQr': //确认修改重命名
		    $data['act'] = 'title';
			$dir = pathinfo($fileName,PATHINFO_DIRNAME);
			@$newName = $_POST['dir'];
			 $mes = rename_file($fileName,$dir.'/'.$newName);
			 $data['msg'] = $mes;
			 $data['cuozuo'] = $act;
			 $data['newName'] = $newName;
		    break;
		case 'copy': //确认复制
		    $data['act'] = 'title';
			@$newName = $_POST['newName'];
			 $mes = copy_file($fileName,$newName);
			 $data['msg'] = $mes;
			 $data['cuozuo'] = $act;
		    break;
		case 'cut': //确认复制
		    $data['act'] = 'title';
			@$newName = $_POST['newName'];
			 $mes = cut_file($fileName,$newName);
			 $data['msg'] = $mes;
			 $data['cuozuo'] = $act;
		    break;	
		case 'dow': //下载
			$data['act'] = 'title';
			$mes = dow_file($fileName);
			$data['msg'] = $fileName;
			break;
		case 'del': //删除
		  $data['act'] = 'title';
		  $mes = del_file($fileName);
		  $data['msg'] = $mes;
		  $data['cuozuo'] = 'del';
		  break;
		case 'createFile': //创建文件
		  $mes = create_file($fileName);
		  $data['msg'] = $mes;
		  $data['act'] = 'title';
		  $data['cuozuo'] = $act;
		  break;
		case 'createDir': //创建文件夹
		  $mes = createFolder($fileName);
		  $data['msg'] = $mes;
		  $data['act'] = 'title';
		  $data['cuozuo'] = $act;
		  break;  
		case 'unload': //上传文件
		  $mes  = upload_file($_FILES["file"]);
		  $data['act'] = 'title';
		  $data['msg'] = $mes;
		  break;
	}
	
	echo JSON_encode($data);	
?>
<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/2/19
 * Time: 17:39
 */

/**
 * 创建文件或目录
 * @param $fileName  需要创建的文件名
 * @return string    提示信息
 */
function create_file($fileName){
    //判断文件是否存在
    if(file_exists($fileName)){
        return "该文件已存在";
    }

    //判断目录是否存在,如果不存在就创建目录
    if(!file_exists(dirname($fileName))){  // dirname函数 获取文件目录
        mkdir(dirname($fileName),0777,true);
    }

    //touch 用来设置文件时间,如果文件不存在则会创建
    if(touch($fileName)){
        return "文件创建成功";
    }

    return "文件创建失败";
}

/**
 * 删除文件的函数
 * @param $fileName   文件名称
 * @return string  提示信息
 */
function del_file($fileName){
    //判断文件是否存在且 判断该文件是否有权限进行读写
    if(!file_exists($fileName) || !is_writable($fileName)){
        return "此文件不可操作";
    }
    //删除文件
    if(unlink($fileName)){
        return "文件删除成功";
    }
    return "文件删除失败";
}

/**
 * 文件复制
 * @param $fileName  fileName
 * @param $lujin   Road
 * @return string   prompt Msg
 */
function copy_file($fileName,$lujin){
  if(!file_exists($fileName) || !is_writable($fileName)){
      return "此文件不可操作";
  }

  //检测拷贝到的目录下是否存在有相同的文件
    if(file_exists($lujin)){
        return "该目录下已存在此文件";
    }

  if(copy($fileName,$lujin)){
      return "OK ! COPY!! ";
  };
  return "Error!!!";
}


/**
 * @param $fileName   文件名
 * @param $newName   需要新的重命名文件
 * @return string  提示的信息
 */
function rename_file($fileName,$newName){
    //判断参数是否为正常的文件
    if(!is_file($fileName)){
        return "该类型文件不可重命名!";
    }

    //获取路劲
    $path = dirname($fileName);
    //拼接路劲
    $destName = $path.DIRECTORY_SEPARATOR.$newName;
    //判断是否为正常路劲
    if(is_file($destName)){
        return '修改失败!';
    }
    //进行重命名操作并判断是否成功
    if(rename($fileName,$newName)){
        return "文件重命名成功";
    }
    return "文件重命名失败";
}

/**
 * 剪切的函数
 * @param $fileName  剪切的文件
 * @param $newName  需要剪切的路劲
 * @return string  提示信息
 */
function cut_file($fileName,$newName){
    //判断文件是否存在
    if(!is_file($fileName)){
        return "此文件不可操作!";
    }

    //判断是否存在该文件夹,不存在则创建
    if(!is_dir($newName)){
        mkdir($newName,0777);
    }


    //拼接路劲
    $destName = $newName.DIRECTORY_SEPARATOR.basename($fileName);

    //判断是否为正常的文件夹
    if(file_exists($destName)){
        return "该文件夹下已存在此文件!";
    }

    if(rename($fileName,$destName)){
        return "剪贴成功";
    }
     return "剪贴失败!";
}

/**
 * 文件信息查询操作
 * @param $fileName   文件名
 * @return array|string 文件信息相关数组| false
 */
function get_file_info($fileName){
    //判断文件是否文真是的文件
    if(!is_file($fileName) && !is_readable($fileName)){
        return "没有该文件,或此文件不可读";
    }
   return [
       'type' => filetype($fileName),
       'ctime' => date('Y-m-d H:i:s',filectime($fileName)),
       'mtime' => date('Y-m-d H:i:s',filemtime($fileName)),
       'atime' => date('Y-m-d H:i:s',fileatime($fileName)),
       'size' => trans_byte(filesize($fileName))
       ];
}

/**
 * @param $byte   字节大小
 * @param int $precision   精确到两位数字
 * @return string  文件大小信息
 */
function trans_byte($byte,$precision=2){
    $kb = 1024;
    $mb = 1024*$kb;
    $gb = 1024*$mb;
    $tb = 1024*$gb;

    if($byte < $kb){
        return $byte.'B';
    }elseif($byte < $mb){
        return round($byte/$kb,$precision).'KB';
    }elseif($byte < $gb){
        return round($byte/$mb,$precision).'MB';
    }elseif($byte < $tb){
        return round($byte/$gb,$precision).'GB';
    }else{
        return round($byte/$tb)."TB";
    }
}

/**
 * 读取文件信息  字符串
 * @param $fileName  文件名
 * @return bool|string  返回的时字符串|文件不存在
 */
function read_file($fileName){
    if(file_exists($fileName) && is_readable($fileName)){
        return file_get_contents($fileName);
    }
    return "该文件不存在或不可读取!";
}

/**
 * 文件读取方式,返回的数组
 * @param $fileName
 * @param bool $bool  是否需要跳过空行
 * @return string   array|false
 */
function read_file_array($fileName,$bool = true){
    if(file_exists($fileName) && is_readable($fileName)){
        if($bool){
            //在数组每个元素的末尾不要添加换行符,跳过空行
            return file($fileName,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
        }else{
            //不跳过空行
            return file($fileName);
        }
    }
  return false;
}

/**
 * 文件写入操作
 * @param $fileName  操作的文件名
 * @param $data  需要写入的数据
 * @param bool $clear  是否清空内容
 * @return string  提示信息
 */
function write_file($fileName, $data,$clear = true){
    //判断文件是否存在 且  可读写
    if(file_exists($fileName) && is_writable($fileName)){
        //是否保留原来的内容
       if($clear){
         $data.= file_get_contents($fileName);
       }
       file_put_contents($fileName,$data);
       return "文件写入成功";
    }
    return "文件不存在或不可读取";
}

/**
 * 文件下载
 * @param $fileName  文件名
 * @return string  提示信息
 */
function dow_file($fileName){
    if(file_exists($fileName)){
        //告诉游览器需要下载的文件大小
        header('Accpet-Length:'.filesize($fileName));
        //告诉游览器文件作为附件处理 ,告诉游览器最终下载完的文件名称
        header('Content-Disposition:attachment;filename='.basename($fileName));
      //  ob_clean(); //清楚(擦除)输出缓冲区
        readfile($fileName); //下载文件
        exit;  //结束  没有该语句,则会连源码也会作为附件一起下载给用户
    }
    return "文件不存在";
}

/**
 * @param $fileInfo  文件信息
 * @param string $uploadPath 文件到的目录
 * @param bool $imageFlag   是否检查图片
 * @param array $allowExt  规定的文件类型
 * @param int $maxSize  最大大小设置
 */
function upload_file($fileInfo,$uploadPath = './upload',$imageFlag = true , $allowExt = ['jpg', 'png', 'jpeg', 'gif', 'txt','xls'], $maxSize = 2097152){
  //判断文件是否有错误,error  等于0  表示没有错误
    if($fileInfo['error'] == 0){
      //截取上传文件的后缀
        $ext = strtolower(pathinfo($fileInfo['name'],PATHINFO_EXTENSION));
        //判断上传的文件是否符合类型
        if(!in_array($ext,$allowExt)){
            return "文件类型不符";
        }
        //判断上传的大小是否符合
        if($maxSize - $fileInfo['size'] < 0){
            return "文件大小超出";
        }
        //判断是否有upload目录
        if(!is_dir($uploadPath)){
            mkdir($uploadPath,0777,true);
        }
       &amp				

最新手记推荐

• 用composer安装thinkphp框架的步骤 • 省市区接口说明 • 用thinkphp,后台新增栏目 • 管理员添加编辑删除 • 管理员添加编辑删除

全部回复(0)我要回复

暂无评论~
  • 取消 回复 发送
  • PHP中文网