PHP學習記錄(文件函數庫)

文件函數庫

文件、目錄函數庫爲PHP核心函數庫,能夠經過其提供的API完成對於文件及目錄的經常使用操做。php

文件信息相關的APIhtml

/*
 * 文件信息相關API
 * filetype(), filesize(), filectime(),filemtime(), fileatime()
 */

$dirname = "./";
$filename = "./11.txt";

// string filetype(string filename):返回文件的類型
echo '文件類型爲:', filetype($dirname), "\n";        //dir
echo '文件類型爲:', filetype($filename), "\n";       //file

//int filesize(string filename):返回文件大小的字節數
echo '文件大小:', filesize($filename), "\n";

//int filectime(string filename):返回文件的建立時間的時間戳
echo '文件的建立時間:', date('Y-m-d H:i:s', filectime($filename)), "\n";

//int filemtime(string filename):返回文件的最後修改時間的時間戳
echo '文件的修改時間:', date('Y-m-d H:i:s', filemtime($filename)), "\n";

//int fileatime(string filename):返回文件的最後訪問時間的時間戳
echo '文件的最後訪問時間:', date('Y-m-d H:i:s', fileatime($filename)), "\n";

//檢測文件是否可讀、可寫、可執行:is_readable(), is_writeable(), is_executabel()
//var_dump(is_readable($filename));       //bool(true)
//var_dump(is_writable($filename));       //bool(true)
//var_dump(is_executable($filename));     //bool(false)
//var_dump(is_file($filename));           //bool(true)
var_dump(
    is_readable($filename),
    is_writable($filename),
    is_executable($filename),
    is_file($filename)
);  //功能同上四句

文件路徑相關APIjson

/*
 * mixed pathinfo(string $path, [, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ])
 * 描述:返回文件路徑的信息。後面接常量表示具體的值
 *
 * PATHINFO_DIRNAME:文件夾名
 * PATHINFO_BASENAME:文件全稱
 * PATHINFO_EXTENSION:文件擴展名
 * PATHINFO_FILENAME:文件名稱
 */
print_r(pathinfo($filename));  //Array([dirname] => .  [basename] => 11.txt [extension] => txt [filename] => 11)
echo pathinfo($filename, PATHINFO_EXTENSION), "\n";  //取出擴展名

$filename = __FILE__;
echo pathinfo($filename, PATHINFO_DIRNAME), "\n";  //路徑部分
echo pathinfo($filename, PATHINFO_EXTENSION), "\n";  //文件擴展名部分

//string basename(string $path[, string $suffix])
//描述:給出一個包含有指向一個文件的全路徑的字符串,返回基本的文件名,若是文件名是以suffix🉑️🉑️結束的,那這一部分也會被去掉
echo basename($filename), "\n";  //文件路徑下的文件全程

//string dirname(string $path):給出一個包含有指向文件的全路徑的字符串,返回去掉文件名後的目錄名
echo dirname($filename), "\n";     //文件路徑

//bool file_exists(string $filename):檢查文件或目錄是否存在
var_dump(file_exists($filename));

文件相關的API數組

//文件建立、刪除、剪切、重命名、拷貝

/*
 * bool touch(string $filename[, int $time=time()[, int $atime]])
 * 描述:若是文件存在,則嘗試將由filename給出的文件的訪問和修改時間設定爲給出的time,
 *      若是文件不存在,則會被建立
 * 參數:
 * filename:要設定的文件名
 * time:要設定的時間,沒有提供則會使用當前系統的時間
 * atime:若是給出了這個參數,則給定文件的訪問時間會被設置爲atime,不然設置爲time
 *
 */
$filename = './22.txt';
var_dump(touch($filename));

/*
 * bool unlink(string $filename[, resource $context])
 * 描述:刪除指定路徑下的文件
 *
 */
if (file_exists($filename)){  //若是文件存在則刪除
//    var_dump(unlink($filename));
}

/*
 * bool rename(string $oldname, string $newname[, resource $context])
 * 描述:重命名一個文件或者目錄
 *
 */
if (file_exists($filename)){  //若是文件存在則重命名
    $newName = './44.txt';
    var_dump(rename($filename, $newName));
}

$oldname = '../practice';
if (file_exists($oldname)){  //若是目錄存在則重命名
    $newname = '../practices';
    var_dump(rename($oldname, $newname));
}

//將11.txt剪切到aaa目錄下
$filename = './11.txt';
$newname = './aaa/11.txt';
if (file_exists($newname)){
    //只須要將文件重命名就能實現其路徑的切換
    var_dump(rename($newname, $filename));
}

/*
 * bool copy(string $source, string $dest)
 * 描述:將文件重source拷貝到dest,若是用移動,請用rename
 *
 * 注意:只能移動具體文件,不能移動目錄
 */
$filename = './11.txt';
$desname = './aaa/1.txt';
if (file_exists($filename)){
    var_dump(copy($filename, $desname));
}


$imageName = 'http://pic4.nipic.com/20091217/3885730_124701000519_2.jpg';
$newName = './aaa/image1.jpg';
//拷貝遠程文件須要開啓php.ini文件中的allow_url_fopen=On選項
var_dump(copy($imageName, $newName));  //將http網絡上的資源拷貝過來

//var_dump(rename($imageName, $newName));  //http wrapper does not support renaming 不能移動http網絡上的資源

文件內容相關API網絡

//內容相關操做
/*
 * 打開文件
 * resource fopen(string $filename, string $mode)
 * 描述:打開文件或者url
 * $filename:指定的文件名
 * $mode:指定了所要求到該流的訪問類型:
 * 'r':只讀方式打開,將文件指針指向文件頭
 * 'r+':讀寫方式打開,將文件指針指向文件頭
 * 'w':寫入方式打開,將文件指針指向文件頭並將文件大小截爲零
 * 'w+':讀取方式打開,將文件指針指向文件頭並將文件大小截爲零
 * 'a':寫入方式打開,將文件指針指向文件末尾
 * 'a+':讀寫方式打開,將文件指針指向文件末尾
 * 'x':建立並以寫入方式打開
 * 'x+':建立並以讀寫方式打開
 *
 *
 * 讀取、寫入文件
 * string fread(resource $handle, int $length)
 * 描述:讀取文件,返回一個字符串。fread()從文件指針handle讀取最多length個字節。
 * 該函數在遇到如下幾種狀況中止讀取文件:
 * 讀取了length個字節;
 * 到達了文件末尾EOF;
 *
 * int ftell(resource $handle)
 * 描述:返回文件指針讀/寫的位置
 *
 * int fseek(resource $handle, int $offset)
 * 描述:在文件指針中定位
 *
 * bool rewind(resource $handle)
 * 描述:倒回文件指針的位置,將handle的文件位置指針設爲文件流的開頭
 *
 * bool ftruncate(resource $handle, int $size)
 * 描述:將文件截斷到給定的長度
 *
 * 
 * int fwrite(resource $handle, string $string[, int $length]) 注:fputs()是fwrite的別稱
 * 描述:寫入文件。把string寫入文件指針handle處
 * 若是指定了length,當寫入了length個字節或者寫完了string之後,寫入就會中止。
 * 注意:fwrite向文件寫入內容,若是以前有內容,會產生覆蓋
 *
 *
 * 關閉文件
 * bool fclose(resource $handle)
 * 描述:關閉一個已經打開的文件指針
 *
 */
 $filename = '../aaa/1.txt';

//操做$handle對象的時候,要時刻注意文件指針的位置

//將文件內容設置爲'this is a test'
$handle = fopen($filename, 'w');
fwrite($handle, 'this is a test');
fclose($handle);

/*
 * 'r':只讀方式打開,將文件指針指向文件頭
 * 'r+':讀寫方式打開,將文件指針指向文件頭
 */
$handle1 = fopen($filename, 'r');
echo fread($handle1, filesize($filename)), "\n";
fclose($handle1);

//注:fwrite()向文件寫入內容,若是以前的位置有內容,會產生覆蓋
$handle2 = fopen($filename, 'r+');
if (fwrite($handle2, 'aaa')){
//    fseek($handle2, 0);  //將文件指針指向第一個位置
    rewind($handle2);  //功能同上,將文件指針指向第一個位置
    echo fread($handle2, filesize($filename)), "\n";
}
fclose($handle2);


/*
 * 'w':寫入方式打開,將文件指針指向文件頭並將文件大小截爲零。若是文件不存在則嘗試建立之
 * 'w+':讀寫方式打開,將文件指針指向文件頭並將文件大小截爲零。若是文件不存在則嘗試建立之
 */
$handle3 = fopen($filename, 'w');
fwrite($handle3, 'aaa123');
fclose($handle3);

$handle4 = fopen($filename, 'w+');
if (fwrite($handle4, 'abc')){
    fseek($handle4, 0);
    echo fread($handle4, filesize($filename)), "\n";
}
fclose($handle4);

/*
 * 'a':寫入方式打開,將文件指針指向文件末尾。若是文件存在則嘗試建立之
 * 'a+':讀寫方式打開,將文件指針指向文件末尾。若是文件存在則嘗試建立之
 */
//PHP_EOL:至關於'\n'換行符號
$handle5 = fopen($filename, 'a');
fwrite($handle5, 'handle5');
fclose($handle5);

$handle6 = fopen($filename, 'a+');
if (fwrite($handle6, 'handle6')){
    fseek($handle6, 0);
    echo fread($handle6, filesize($filename)), "\n";  //abchandleahand 疑問:爲何少了'le6'

    ftruncate($handle6, 5);  //將文件截取到給定的長度

    rewind($handle6);
    echo fread($handle6, filesize($filename)), "\n";
}
fclose($handle6);




/*
 * string fgetc(resource $handle)
 * 描述:從文件句柄中獲取一個字符,若是碰到EOF則返回false
 *
 * string fgets(resource $handle[, int $length])
 * 描述:從文件指針中讀取一行
 * length:限制取回該長度的數據
 *
 * string fgetss(resource $handle[, int $length[, string $allow_tags]])
 * 描述:從文件指針中讀取一行並過濾掉html標記。和fgets()相同,只除了fgetss()嘗試從讀取的文本中去掉任何html和php標記
 * length:限制取回該長度的數據
 *
 * bool feof(resource $handle):測試文件指針是否到了文件結束的位置
 *
 * string strip_tags(string $str[, string $allow_tags])
 * 描述:從字符串中取出html和php標記
 *
 * 注意:
 * fgetcsv()
 * fputcsv()
 *
 */

$filename = '../aaa/1.txt';

//寫入一段文件
$handle1 = fopen($filename, 'w');
$txt = <<<EOF
<h1>一級標題</h1>
<h2>二級標題</h2>
<h3>三級標題</h3>
EOF;
fwrite($handle1, $txt);
fclose($handle1);


$handle2 = fopen($filename,'r+');
echo fread($handle2, filesize($filename)), "\n";

rewind($handle2);
echo '第一個字符是:', fgetc($handle2), "\n";  //第一個字符是:<


rewind($handle2);
echo '第一行字符串是:', fgets($handle2), "\n";  //第一行字符串是:<h1>一級標題</h1>

rewind($handle2);
while (!feof($handle2)){  //利用feof()函數判斷是否爲文件結尾,遍歷輸出每一行
    echo fgets($handle2);
}
echo "\n";

rewind($handle2);
echo fgetss($handle2), "\n";  //一級標題

rewind($handle2);
echo strip_tags(fgets($handle2)), "\n";  //功能同上
fclose($handle2);

簡化的讀取、寫入文件app

/*
 * 簡化的讀取、寫入文件
 *
 * string file_get_contents(string $filename[, bool $use_include_path=false[, ...]])
 * 描述:將整個文件讀入一個字符串
 *
 * int file_put_contents(string $filename, mixed $data[, int....])
 * 描述:將一個字符串寫入文件。會將以前的內容清空
 * data:要寫入的數據,類型能夠是string, array或者是stream資源,data能夠是數組,但不能是多緯數組
 *       通常只是寫入string類型
 * 注意:若是$filename下的文件不存在,會自動建立文件
 *
 *
 * 序列化和反序列化:
 *
 * string serialize(mixed $value)
 * 描述:產生一個可存儲的值的表示,稱爲序列化
 *
 * mixed unserialize(string $str)
 * 描述:從已存儲的表示中建立php的值,稱爲反序列化
 *
 *
 * php變量和json的相互轉化:
 *
 * string json_encode(mixed $value...)
 * 描述:對變量進行json編碼,返回json字符串
 *
 * mixed json_decode(string $json...)
 * 描述:對json格式的字符串進行解碼,轉換成php變量
 *
 *
 */
echo '簡化函數:', "\n";
$filename = '../aaa/1.txt';
echo file_get_contents($filename), "\n";

$string = '你好嗎,我是昭哥';
file_put_contents($filename, $string);
echo file_get_contents($filename), "\n";

$arr = [
    'id' => 1001,
    'name' => '王昭',
    'sex' => '男',
    'phone' => '1829210000',
];
$string = serialize($arr);
echo $string, "\n";  //a:5:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;}  ->將$arr序列化爲字符串
print_r(unserialize($string));  //Array([0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5) ->將序列化後的字符串反序列化爲數組

$json = json_encode($arr);
echo $json, "\n";

print_r(json_decode($json));
相關文章
相關標籤/搜索