• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

php 搞代码 4年前 (2022-01-23) 17次浏览 已收录 0个评论

一、文件权限

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

二、写入文件

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”&gt;

<meta http-equiv=”content-type”content=”text/html; charset=utf-8″ />
Add AQuotation

<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.

6本文来源gao@dai!ma.com搞$代^码!网7

搞gaodaima代码

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML1.0 Transitional//EN"
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<meta http-equiv=”content-type”content=”text/html; charset=utf-8″ />
View AQuotation

<body>

RandomQuetation

<?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 ‘

‘ .trim($data[$rand]) .’

‘; //file可以使内容信息放置在一个数组中,每个元素都包含了一行

?>


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:PHP关于文件与目录(1) 写入文件 文件权限 三、锁定文件

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址