PHP Reading And Writing Files

PHP Code Snippets Reading And Writing Files
Share:

About

In this code snippet, we’ll learn how to read and write files with PHP.

Let’s see the example below.

Code:

<?php

//Entry point////////////////////////////////////////////////////////////////////////////////////

$filePath = "HelloWorld.txt";

WriteFiles($filePath, "Hello World!");

$data = ReadFiles($filePath); //You can also use file_get_contents($filePath).
echo $data;

/////////////////////////////////////////////////////////////////////////////////////////////////


//Functions//////////////////////////////////////////////////////////////////////////////////////

function ReadFiles($filePath){
	//Create/open file. 
	$file = fopen($filePath, "r") or die("An error occured while trying to open the file."); //More info. about second parameter: https://www.php.net/manual/en/function.fopen.php
	//Read data from file.
	$data = fread($file, filesize($filePath));
	//Close file.
	fclose($file);

	return $data;
}

function WriteFiles($filePath, $data){
	//Create/open file. 
	$file = fopen($filePath, "w") or die("An error occured while trying to open the file."); //More info. about second parameter: https://www.php.net/manual/en/function.fopen.php
	//Write data to file.
	fwrite($file, $data);
	//Close file.
	fclose($file);
}

//////////////////////////////////////////////////////////////////////////////////////////////////

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger