<?php
$filepath = "wfile.txt";
echo dirname($filepath)."<br />";
//權限檢測
is_writeable(dirname($filepath)) or die("can not write $filepath<br />");
is_readable($filepath) or die("can not read $filepath<br />");
//打開文件
$fhandle= fopen($filepath, "w+b");
//寫數據
$i=0;
if(flock($fhandle, LOCK_EX|LOCK_NB)) //加寫鎖
{
fwrite($fhandle, "content1");
fwrite($fhandle, "content2\r\n");
fwrite($fhandle, "content3");
usleep(1000000);
echo $i."<br />";
$i++;
if($i==20)
break;
}
else
{
echo "can not lock ".$filepath." for write<br />";
}
//else
//讀數據
if(flock($fhandle, LOCK_SH)) //加讀鎖
{
fseek($fhandle, 0);
while(!feof($fhandle))
{
$str = fgets($fhandle);
echo $str."<br />";
}
}
else
{
echo "can not lock ".$filepath." for read<br />";
}
//輸出:content1content2|content3
//讀到數組中,每行一元素
$arr = file($filepath);
var_dump($arr);
php文件操作示例源碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.