php文件写入加1,PHP关于文件与目录(1) 写入文件 文件权限 三、锁定文件
一、文件權限
總之一切都是為了保證目錄的安全,保證目錄的安全比保證文件的安全更重要。
二、寫入文件
file_put_contents($file,$data); //如果沒有的話會創建,有的話覆蓋原文件;
file_put_contents($file,$data,FILE_APPEND); //沒的話會創建,有的話追加在后面;
file_put_contents($file,$data.PHP_EOL,FILE_APPEND);//有換行
【例子】:
// Identify the file to use:
$file ='../quotes.txt'; //這個文件最好放在父目錄中,安全。
// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Handle theform.
if ( !empty($_POST['quote'])&& ($_POST['quote'] != 'Enter yourquotation here.') ) { // Need some thing to write.
if(is_writable($file)) { // Confirm that the file iswritable.
file_put_contents($file,$_POST['quote'] . PHP_EOL, FILE_APPEND); // Write thedata.
//Print amessage:
print'
Your quotation has beenstored.
';
} else { // Could notopen the file.
print'
Yourquotation could not be stored due to a systemerror.
';
}
} else { // Failed to enter aquotation.
print 'Please enter aquotation!
';
}
} // End of submitted IF.
// Leave PHP and display the form:
?>
三、鎖定文件
file_put_contents($file,$data,FILE_APPEND|LOCK_EX); //兩個變量的使用順序無關緊要
LOCK_SH 用于讀取的共享鎖
LOCK_EX 用于寫入的獨享鎖
LOCK_UN 釋放一個鎖
LOCK_NB 非阻塞鎖
四、讀取文件
第一種方法:$data=file_get_contents($file); //按照一個字符串來讀取
第二種方法:$data=file($file); //讀取每一行的數據,較為常用
【例】: //補充:謹慎點可以在file函數前使用is_readable()函數測試下是否可讀這個文件
https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>
RandomQuetation
$data =file('../quotes.txt');
// Count the number of items in the array:
$n = count($data);
// Pick a random item: 產生一個隨機數
$rand = rand(0, ($n -1));
// Print the quotation:
print '
' .trim($data[$rand]) .'
'; //file可以使內容信息放置在一個數組中,每個元素都包含了一行
?>
總結
以上是生活随笔為你收集整理的php文件写入加1,PHP关于文件与目录(1) 写入文件 文件权限 三、锁定文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: windows下php swoole扩展
- 下一篇: php如何和c进行数据交换,PHP与 后