日期:2014-05-16  浏览次数:20460 次

php学习基础-文件系统(二) 文件读写操作、文件资源处理

一、文件的打开与关闭

/*
 *读取文件中的内容
 *	file_get_contents(); //php5以上
 *	file()
 *	readfile();
 *
 *	不足:全部读取, 不能读取部分,也不能指定的区域
 *
 *	fopen()
 *	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
 *
 */
//读取出所有行
	
$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>';



二、小偷程序,抓取网站上的页面,从页面链接中获取资源图片

$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);

三、更改网站配置项,修改文件内容,先读取,在使用正则匹配写入

if(isset($_POST["sub"])){
		setConfig($_POST);
}


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="mod"><br>
</form>

四、读取文件中得sql,执行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>';
 

五、向文件中写入内容

   /*写入文件
    *	file_put_contents(“URL”, “内容字符串”);  //php5以上
    *		如果文件不存在,则创建,并写入内容
    *		如果文件存在,则删除文件中的内容,重新写放
    *
    *		不足: 不能以追加的方式写,也不能加锁
    *
    *	fopen()
    *					fwrite() 别名 fputs
    */
    $file=fopen("./test.txt", "a"); //如果打开文件成功返回资源,如果失败返回false

    for($i=0; $i<100; $i++)
		fwrite($file, "www.lampbrother{$i}.net\n");

    fclose($file);   //关闭文件资源


六、循环读取文件每次按照固定长度读取