How to read and write file in PHP



My previous post shows you how to read a file and retrieve its content in PHP.

This one, you will see how to read file and also write to a file with easy:

Here is the code:

<?php 

//A function to read file content
function phpReadFile($filename){
	//Create file if not exist
	if(!is_file($filename)){
		file_put_contents($filename, "");
	}
	$myfile = fopen($filename, "r") or die("Unable to open file!");
	$filecontent = "No content.";
	if(filesize($filename) > 0)
		$filecontent = fread($myfile, filesize($filename));
	fclose($myfile);
	return $filecontent;
}

//Let's test it, try to read "MyFile.txt" file in root directory

echo nl2br(phpReadFile("MyFile.txt"));


//A function to write a text file. $wtw is "What to Write" :D.
function phpWriteFile($filename, $wtw){
	$myfile = fopen($filename, "w") or die("Unable to open file!");
	fwrite($myfile, $wtw);
	fclose($myfile);
	echo "<br>" . $wtw . " has been written.";
}

//Let's test it, write "My name is Habibie"

phpWriteFile("myname.txt", "My name is Habibie.");
?>
loading...

Leave a Reply

Your email address will not be published.