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

php中文网
发布: 2016-06-23 13:46:15
原创
965人浏览过

一、文件权限

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

二、写入文件

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

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

立即学习PHP免费学习笔记(深入)”;

 file_put_contents($file,$data.PHP_EOL,FILE_APPEND);//有换行

【例子】:

br />  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


 
 Add AQuotation


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

br />  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


 
 View AQuotation


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速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号