您的位置:首页 > 编程语言 > PHP开发

PHP文件系统-文件的读写操作

2012-04-11 13:17 363 查看
一、 文件的打开与关闭(读文件中的内容, 向文件中写内容)

读取文件中的内容
file_get_contents(); //php5以上,读取出的文件内容放在一个变量中
file() //读取文件中内容,按每一行保存在数组中
readfile(); //读取文件中的内容,并输出
不足:全部读取, 不能读取部分,也不能指定的区域

fopen() --打开文件或者 URL
fread() --读取文件(可安全用于二进制文件)
fgetc() --从文件指针中读取字符
fgets() --从文件中读取一行

写入文件,file_put_contents(“URL”, “内容字符串”); //php5以上
如果文件不存在,则创建,并写入内容。如果文件存在,则删除文件中的内容,重新写放
不足: 不能以追加的方式写,也不能加锁
fopen() fwrite() 别名 fputs

本地文件:
./test.txt
c:/appserv/www/index.html
/usr/local/apahce/index.html

远程: http://www.baidu.com http://www.163.com ftp://user@pass:www.baidu.com/index.php
二、程序实例

1、把远程网站的图片链接信息保存到一个文件中

$str=file_get_contents("http://www.163.com");
preg_match_all('/\<img\s+src=.*?\s*\/?\>/i',$str, $images);
$imgs="";
foreach($images[0] as $img){
$imgs.=$img.'<br>';
}
echo file_put_contents("test.txt", $imgs);

2、修改配置文件中的内容

function setConfig($post){
//读取文件中的内容
$str=file_get_contents("config.inc.php");

$zz=array();
$rep=array();

foreach($post as $key=>$value ){
$zz[]="/define\(\"{$key}\",\s*.*?\);/i";
$rep[]="define(\"{$key}\", \"{$value}\");";
}
echo '<pre>';
print_r($zz);
print_r($rep);
echo '</pre>';
//改写文件中的内容
$str=preg_replace($zz, $rep, $str);

file_put_contents("config.inc.php", $str);
//再写回文件
}
?>

<form action="one.php" method="post">
host : <input type="text" name="DB_HOST"><br>
user: <input type="text" name="DB_USER"><br>
pass: <input type="text" name="DB_PWD"><br>
dbname <input type="text" name="DB_NAME"><br>
tabPREFIX <input type="text" name="TAB_PREFIX"><br>
<input type="submit" name="sub" value="修改"><br>
</form>

3、读出安装文件中所有的SQL语句

$lines=file("lampcms.sql"); //读取出所有行

$sqlstr="";

foreach($lines as $line){
$line=trim($line); //去掉首尾的空白字符
if($line!=""){
if(!($line{0}=="#" || $line{0}.$line{1}=="--")){
$sqlstr.=$line;
}
}
}

$sqlstr=rtrim($sqlstr,";"); //删除文件内容的最后的一个分号

$sqls=explode(";",$sqlstr); //按;号进行分割

echo '<pre>';
print_r($sqls);
echo '</pre>';
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: