PHP - How to write a file

In this tutorial, you will learn how to write some date into a text file. So make two files test.php and test.txt in a folder and save this folder to your Wamp, Xamp, Lamp server root directory.

Now Open the test.php file, put the following code.
  1. $testFile = "test.txt";
  2. $check = fopen($testFile, 'w') or die("can't open file");
  3. $data = "Hi, Congratulations\n";
  4. fwrite($check, $data);
  5. fclose($check);
Now I'll describe the code line by line.
On the Line 1, we are saving a path of a text file in a variable named $testFile.

On the Line 2, check to see file exists or not. Second argument in the "fopen" function, "w" means we are providing a write access to the file.

On the Line 3, we are saving a string into a variable $data.

On the Line 4, we are calling fwrite() function, that have two arguments. The behavior of this function is that first this function check file exist or not. If find the file, it will paste the $data variable string into the text file.

Line 5 means, we have stop writing, and now close connection to the file.

Now open your test.txt file, where you will find this string Hi, Congratulations.

If any suggestion about topic, comment on the post.


No comments:

Post a Comment