php 文件操作

获取文件信息:

//打开文件
$file_path = "test.txt";

//获取文件信息

if($fp=fopen($file_path,"r")){
	$file_info = fstat($fp);
	echo "<pre>";
	print_r($file_info);
	echo "</pre>";
	
	echo "<br/>文件大小是{$file_info['size']}";
	echo "<br/>文件上次修改时间".date("Y-m-d H:i:s",$file_info['mtime']);
	echo "<br/>文件上次访问时间".date("Y-m-d H:i:s",$file_info['atime']);
	echo "<br/>文件上次change时间".date("Y-m-d H:i:s",$file_info['ctime']);
	
}else{
	echo "打开文件失败!";
}

//关闭文件
fclose($fp);

<?php//第二种方式获取文件信息
echo "<br/>".filesize($file_path);
echo "<br/>".date("Y-m-d H:i:s",fileatime($file_path));
echo "<br/>".filectime($file_path);
echo "<br/>".filemtime($file_path);
?>

读取文件信息:

<?php
//读取文件
$file_path = "test.txt";
//先判断文件是否存在
if(file_exists($file_path)){
	$fp = fopen($file_path,"a+");
	//读取内容并且输出
	$content = fread($fp,filesize($file_path));
	echo "文件内容是:<br/>";
	$content = str_replace("\r\n", "<br/>", $content);
	echo $content;
}else{
	echo "文件不存在";
}
//关闭文件
fclose($fp);
?>

读取文件信息的简单方式:

<?php
// //读取文件
$file_path = "test.txt";
$contents = file_get_contents($file_path);
$contents = str_replace("\r\n", "<br/>", $contents);
echo $contents;
?>

循环读取文件信息:

<?php
// //读取文件
$file_path = "test.txt";

if(file_exists($file_path)){
	$fp = fopen($file_path,"rw");
	
	//设置每次读取1024字节
	$buffer = 1024;
	$str="";
	while(!feof($fp)){
		$str .= fread($fp,$buffer);
	}
	
	$str = str_replace("\r\n", "<br/>", $str);
	
	echo $str;
	
	fclose($fp);
}else{
	echo "文件不存在。";
}
?>

读取ini文件信息:

<?php
$file_path="test.ini";
$arr = parse_ini_file($file_path);
print_r($arr);

$psw = $arr['password'];
$user = $arr['user'];
$host = $arr['host'];

echo "<br/>".$psw;
echo "<br/>".$user;
echo "<br/>".$host;
?>

写文件:

<?php
$file_path = "test.txt";

if(file_exists($file_path)){
	$fp = fopen($file_path,"w+");
	$con = "您好\r\n";
	
	for($i = 0; $i <10;$i++){
		fwrite($fp, $con);
	}
	
	
	echo "添加成功!";
}else{
	echo "文件不存在!";
}

fclose($fp);
?>

写文件简单方式:

<?php
$file_path = "test.txt";
file_put_contents($file_path, "hello,world",FILE_APPEND);
?>

拷贝文件:

<?php
//拷贝文件
if(!copy("./test.png", "c://test.png")){
	echo "failed copy image file";
}else{
	echo "copy success";
}
?>

创建文件:

<span style="font-size:18px;"><?php
//创建文件并且写入信息

$file_path="c:/php创建的文件夹/newFile.txt";

$fp =fopen($file_path,"w+");

fwrite($fp, "hello,world");

fclose($fp);
?></span>

删除文件:

<?php
$file_path="c:/php创建的文件夹/newFile.txt";

if(is_file($file_path)){
	if(!unlink($file_path)){
		echo "删除失败";
	}else{
		echo "删除成功";
	}
}else{
	echo "文件不存在";
}
?>





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值