PHP的文件操作类
<?php
class file {
function file() {
die("Class file can not instantiated!");
}
//创建目录
function forcemkdir($path){
if(!file_exists($path)){
file::forcemkdir(dirname($path));
mkdir($path,0777);
}
}
//检测文件是否存在
function iswriteable($file){
$writeable=0;
if(is_dir($file)){
$dir=$file;
if($fp=@fopen("$dir/test.txt",'w')){
@fclose($fp);
@unlink("$dir/test.txt");
$writeable=1;
}
}else{
if($fp=@fopen($file,'a+')){
@fclose($fp);
$writeable=1;
}
}
return $writeable;
}
//删除当前目录下的文件或目录
function cleardir($dir,$forceclear=false) {
if(!is_dir($dir)){
return;
}
$directory=dir($dir);
while($entry=$directory->read()){
$filename=$dir.'/'.$entry;
if(is_file($filename)){
@unlink($filename);
}elseif(is_dir($filename)&$forceclear&$entry!='.'&$entry!='..'){
chmod($filename,0777);
file::cleardir($filename,$forceclear);
rmdir($filename);
}
}
$directory->close();
}
//删除当前目录及目录下的文件
function removedir($dir){
if (is_dir($dir) && !is_link($dir)){
if ($dh=opendir($dir)){
while (($sf= readdir($dh))!== false){
if('.'==$sf || '..'==$sf){
continue;
}
file::removedir($dir.'/'.$sf);
}
closedir($dh);
}
return rmdir($dir);
}
return @unlink($dir);
}
//复制文件
function copydir($srcdir, $dstdir) {
if(!is_dir($dstdir)) mkdir($dstdir);
if($curdir = opendir($srcdir)) {
while($file = readdir($curdir)) {
if($file != '.' && $file != '..') {
$srcfile = $srcdir . '/' . $file;
$dstfile = $dstdir . '/' . $file;
if(is_file($srcfile)) {
copy($srcfile, $dstfile);
}
else if(is_dir($srcfile)) {
file::copydir($srcfile, $dstfile);
}
}
}
closedir($curdir);
}
}
//读取文件
function readfromfile($filename) {
if ($fp=@fopen($filename,'rb')) {
if(PHP_VERSION >='4.3.0' && function_exists('file_get_contents')){
return file_get_contents($filename);
}else{
flock($fp,LOCK_EX);
$data=fread($fp,filesize($filename));
flock($fp,LOCK_UN);
fclose($fp);
return $data;
}
}else{
return '';
}
}
//写入文件
function writetofile($filename,$data){
if($fp=@fopen($filename,'wb')){
if (PHP_VERSION >='4.3.0' && function_exists('file_put_contents')) {
return @file_put_contents($filename,$data);
}else{
flock($fp, LOCK_EX);
$bytes=fwrite($fp, $data);
flock($fp,LOCK_UN);
fclose($fp);
return $bytes;
}
}else{
return
}
}
//上传文件
function uploadfile($attachment,$target,$maxsize=1024,$is_image=1){
$result=array ('result'=>false,'msg'=>'upload mistake');
if($is_image){
$attach=$attachment;
$filesize=$attach['size']/1024;
if(0==$filesize){
$result['msg'] = '上传错误';
return $result;
}
if(substr($attach['type'],0,6)!='image/'){
$result['msg'] ='格式错误';
return $result;
}
if($filesize>$maxsize){
$result['msg'] ='文件过大';
return $result;
}
}else{
$attach['tmp_name']=$attachment;
}
$filedir=dirname($target);
file::forcemkdir($filedir);
if(@copy($attach['tmp_name'],$target) || @move_uploaded_file($attach['tmp_name'],$target)){
$result['result']=true;
$result['msg'] ='上传成功';
}
if(!$result['result'] && @is_readable($attach['tmp_name'])){
@$fp = fopen($attach['tmp_name'], 'rb');
@flock($fp, 2);
@$attachedfile = fread($fp, $attach['size']);
@fclose($fp);
@$fp = fopen($target, 'wb');
@flock($fp,2);
if(@fwrite($fp, $attachedfile)) {
@unlink($attach['tmp_name']);
$result['result']=true;
$result['msg']= '上传失败';
}
@fclose($fp);
}
return $result;
}
function hheader($string, $replace = true, $http_response_code = 0){
$string = str_replace(array("\r", "\n"), array('', ''), $string);
if(emptyempty($http_response_code) || PHP_VERSION <'4.3'){
@header($string, $replace);
}else{
@header($string, $replace, $http_response_code);
}
if(preg_match('/^\s*location:/is', $string)){
exit();
}
}
//下载文件
function downloadfile($filepath,$filename=''){
global $encoding;
if(!file_exists($filepath)){
return 1;
}
if(''==$filename){
$tem=explode('/',$filepath);
$num=count($tem)-1;
$filename=$tem[$num];
$filetype=substr($filepath,strrpos($filepath,".")+1);
}else{
$filetype=substr($filename,strrpos($filename,".")+1);
}
$filename ='"'.(strtolower($encoding) == 'utf-8' && !(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') === FALSE) ? urlencode($filename) : $filename).'"';
$filesize = filesize($filepath);
$dateline=time();
file::hheader('date: '.gmdate('d, d m y h:i:s', $dateline).' gmt');
file::hheader('last-modified: '.gmdate('d, d m y h:i:s', $dateline).' gmt');
file::hheader('content-encoding: none');
file::hheader('content-disposition: attachment; filename='.$filename);
file::hheader('content-type: '.$filetype);
file::hheader('content-length: '.$filesize);
file::hheader('accept-ranges: bytes');
if(!@emptyempty($_SERVER['HTTP_RANGE'])) {
list($range) = explode('-',(str_replace('bytes=', '', $_SERVER['HTTP_RANGE'])));
$rangesize = ($filesize - $range) > 0 ? ($filesize - $range) : 0;
file::hheader('content-length: '.$rangesize);
file::hheader('http/1.1 206 partial content');
file::hheader('content-range: bytes='.$range.'-'.($filesize-1).'/'.($filesize));
}
if($fp = @fopen($filepath, 'rb')) {
@fseek($fp, $range);
echo fread($fp, filesize($filepath));
}
fclose($fp);
flush();
ob_flush();
}
//返回文件类型
function extname($filename){
$pathinfo=pathinfo($filename);
return strtolower($pathinfo['extension']);
}
function createaccessfile($path){
if(!file_exists($path.'index.htm')){
$content=' ';
file::writetofile($path.'index.htm',$content);
}
if(!file_exists($path.'.htaccess')){
$content='Deny from all';
file::writetofile($path.'.htaccess',$content);
}
}
//返回文件大小
function getdirsize($filedir){
$handle=opendir($filedir);
while($filename=readdir($handle)){
if ('.' != $filename && '..' != $filename){
$totalsize += is_dir($filedir.'/'.$filename) ? file::getdirsize($filedir.'/'.$filename) : (int)filesize($filedir.'/'.$filename);
}
}
return $totalsize;
}
}
?>
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
更多技术文章请搜索千锋PHP,做真实的自己,用良心做教育。
互联网+时代,时刻要保持学习,携手千锋PHP,Dream It Possible。
PHP的文件操作类的更多相关文章
- [C#] 常用工具类——文件操作类
/// <para> FilesUpload:工具方法:ASP.NET上传文件的方法</para> /// <para> FileExists:返回文件是否存在&l ...
- 文件操作类CFile
CFile file; CString str1= L"写入文件成功!"; wchar_t *str2; if (!file.Open(L"Hello.txt" ...
- asp.net文件操作类
/** 文件操作类 **/ #region 引用命名空间 using System; using System.Collections.Generic; using System.Text; usin ...
- android 文件操作类简易总结
android 文件操作类(参考链接) http://www.cnblogs.com/menlsh/archive/2013/04/02/2997084.html package com.androi ...
- Ini文件操作类
/// <summary> /// Ini文件操作类 /// </summary> public class Ini { // 声明INI文件的写操作函数 WritePriva ...
- java csv 文件 操作类
一个CSV文件操作类,功能比较齐全: package tool; import java.io.BufferedReader; import java.io.BufferedWriter; impor ...
- Qt5:Qt文件操作类 QFile
在QT中,操作文件一般不使用C++提供的文件操作类 , 因为操作文件的时候,要用到C++提供的 string 类,而在QT中使用的是Qt自己实现的一个string类 QString .在Qt中使用C+ ...
- C# 文件操作类大全
C# 文件操作类大全 时间:2015-01-31 16:04:20 阅读:1724 评论:0 收藏:0 [点我收藏+] 标签: 1.创建文件夹 //usin ...
- Java文件操作类效率对比
前言 众所周知,Java中有多种针对文件的操作类,以面向字节流和字符流可分为两大类,这里以写入为例: 面向字节流的:FileOutputStream 和 BufferedOutputStream 面向 ...
- JAVA文件操作类和文件夹的操作代码示例
JAVA文件操作类和文件夹的操作代码实例,包括读取文本文件内容, 新建目录,多级目录创建,新建文件,有编码方式的文件创建, 删除文件,删除文件夹,删除指定文件夹下所有文件, 复制单个文件,复制整个文件 ...
随机推荐
- js把字符串格式的时间转换成几秒前、几分钟前、几小时前、几天前等格式
最近在做项目的时候,需要把后台返回的时间转换成几秒前.几分钟前.几小时前.几天前等的格式:后台返回的时间格式为:2015-07-30 09:36:10,需要根据当前的时间与返回的时间进行对比,最后显示 ...
- javascript中将整数添加千位符号
如果num是整数的话,将其转换成带千位符号的字符串: Number(num).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + ','); 另 ...
- Storm ui 显示异常
今天安装storm集群的时候,各个进程也都起来,却发现Storm ui界面下无法观察Storm集群的状态 有很多地方处理不当都会造成这种现象: 1.storm.yaml配置不当 2.防火墙的问题 3. ...
- 猜数字(C语言版)
编程先由计算机“想”一个1到100之间的数请人猜,如果人猜对了,则结束游戏,并在屏幕上输出人猜了多少次才猜对此数,以此来反映猜数者“猜”的水平,否则计算机给出提示,告诉人所猜的数是太大还是太小,最多可 ...
- Codeforces数据结构(水题)小结
最近在使用codeblock,所以就先刷一些水题上上手 使用codeblock遇到的问题 1.无法进行编译-------从setting中的编译器设置中配置编译器 2.建立cpp后无法调试------ ...
- 【题解】ZOJ1420 Cashier Employment
论文——冯威<浅析差分约束系统>. 论文讲得很详细,就不解释了.主要想记录一下对于差分约束的理解(感觉以前的学习真的是在囫囵吞枣啊……) 差分约束系统,同于解决线性的不等关系是否存在合法解 ...
- 什么是Redis的事务
一.什么是Redis的事务 可以一次执行多个命令,本质上是一组命令的集合.一个事务中的所有命令都会序列化,然后按顺序地串行化执行,而不会被插入其它命令. 二.Redis的事务可以做什么 一个队列中,一 ...
- 关于GDI+
原文链接地址:http://www.2cto.com/kf/201107/97283.html 一 介绍 其实本人对GDI+不能算是专家,只是在几个小项目中应用了一些而已, 算是入门了. 刚好最近有点 ...
- [Leetcode] palindrome partition ii 回文分区
Given a string s, partition s such that every substring of the partition is a palindrome. Return the ...
- 【NOIP模拟赛】 permutation 数学(打表)
biubiu~~~ 这道题卡读题卡得很死......首先他告诉我们读循环的时候要顺着圈读,然后又说这个圈在数列上要以最大数开始读,而且以这样的循环的首数排序,得到的序列与原序列一样那么他就是可行序列, ...