天天看点

PHP关于文件与文件夹(1) 写入文件 文件权限 三、锁定文件

一、文件权限

 总之中的一个切都是为了保证文件夹的安全,保证文件夹的安全比保证文件的安全更重要。

二、写入文件

 file_put_contents($file,$data);  //假设没有的话会创建。有的话覆盖原文件;

 file_put_contents($file,$data,file_append); //没的话会创建,有的话追加在后面;

 file_put_contents($file,$data.php_eol,file_append);//有换行

【样例】:

<!doctype html public "-//w3c//dtd xhtml1.0 transitional//en"

 "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"xml:lang="en" lang="en">

<head>

 <meta http-equiv="content-type"content="text/html; charset=utf-8" />

 <title>add aquotation</title>

</head>

<body>

<?php // script 11.1 -add_quote.php

// 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'<p>your quotation has beenstored.</p>';

  } else { // could notopen the file.

   print'<p style="color: red;">yourquotation could not be stored due to a systemerror.</p>';

  }

 } else { // failed to enter aquotation.

  print '<pstyle="color: red;">please enter aquotation!</p>';

 }

} // end of submitted if.

// leave php and display the form:

?>

<form action="add_quote.php"method="post">

 <textarea name="quote" rows="5"cols="30">enter your quotationhere.</textarea><br/>

 <input type="submit" name="submit"value="add this quote!" />

</form>

</body>

</html>

三、锁定文件

 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()函数測试下是否可读这个文件

<html xmlns="http://www.w3.org/1999/xhtml"

xml:lang="en"lang="en">

 <title>view aquotation</title>

<h1>randomquetation</h1>

<?php

$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 '<p>' .trim($data[$rand]) .'</p>'; //file能够使内容信息放置在一个数组中,每一个元素都包括了一行