Skip to content

ThirteeNov

My personal blog about coding and internet

Menu
  • About me
  • About Zofia Kreasi
  • Cart
  • Checkout
  • Making an airplane game from scratch in Unity
  • My account
  • Privacy Policy
  • Privacy Policy – zkLeaderboard
  • Sample Page
  • Shop
  • Tutorials on Learning JavaScript
  • ZKAccounts – Privacy Policy
Menu

How to read and write file in PHP

Posted on October 3, 2020October 3, 2020 by Habibie

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.");
?>
Post Views: 437
ciihuy2020

Welcome!

  • My YouTube Channel
  • My GitHub Page
  • About me

Categories

  • 3DVista
  • Android
  • Apache
  • C#
  • Cordova
  • Electron & Node JS
  • HTML5, CSS & JavaScript
  • iOS
  • Let's Make Unity Games
  • Misc
  • Photoshop
  • PHP
  • Python
  • Uncategorized
  • Unity
  • WordPress

Recent Posts

  • Hover Reveal script for Unity to show and hide object on mouse hover
  • How to Prevent UI Clicks in Unity from “Bleeding Through” to 3D Objects Behind Them
  • Make objects like wires and cables easily in Unity using Ciihuy Curved Mesh
  • [SOLVED] Can’t Add Custom Domain to Blogger After Losing CNAME Verification
  • iOS App Icon Generator by CiihuyCom
© 2026 ThirteeNov | Powered by Superbs Personal Blog theme