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); } //////////////////////////////////////////////////////////////////////////////////////////////////