首页 > 代码库 > php文件类

php文件类

1.需求

了解php对文件的一些操作

2.例子

写了一个类,可以操作文件,包含增,删,查

<?php
class myfile{

    public function write_file($string,$path,$mode=‘w+b‘)
    {

        if(!$fp =@fopen($path,$mode))
        {
            echo "无法写入文件";
            exit();
        }
        if(flock($fp,LOCK_EX))
        {
            for($written =0,$length = strlen($string);$written<$length;$written+=$result)
            {
                if(($result =fwrite($fp,substr($string,$written)))===false)
                {
                    break;
                }
            }
            flock($fp, LOCK_UN);
        }
        else
        {
            echo "无法获得文件锁";
            exit();
        }

        fclose($fp);
        return true;
    }

    public function read_file($path)
    {
        if(!$fp =@fopen($path,‘r+b‘))
        {
            echo "无法打开文件";
            exit();
        }
        if(flock($fp,LOCK_SH))
        {
            if(!$content = fread($fp,filesize($path)))
            {
                echo "无法读取文件";
                exit();
            }
        }
        else
        {
            echo "无法获得文件锁";
            exit();
        }

        fclose($fp);

        return $content;
    }

    public function delete_file($path)
    {
        if(!file_exists($path))
        {
            echo "文件不存在";
            return false;
        }
        @unlink($path);
        return true;
    }

}
$config=array(
  ‘string‘=>‘abcdeaisdiiee‘,
    ‘path‘=>md5(microtime()).‘.php‘
);
$obj = new myfile();
$obj->write_file(‘sufi‘,‘due‘.‘.php‘,‘a+b‘);

 

参考文档:http://www.php.net/manual/zh/function.fwrite.php

php文件类