PHP file handling allows you to make operations with the file like the create file, open file, write the file. in this article, you will know about Write file in PHP. You must need full file access permission(chmod to 777) to write it. When writing to a file, the first thing you need to do is to open up the file. We do that with this code:
<?php $file = "myfile.txt"; $file_operation = fopen($file, 'w'); ?>After opening the file, we can use the fwrite command to add data to our file. We would do this as shown below:
<?php $file = "myfile.txt"; //Select the file $file_operation = fopen($file, 'w'); //Open the file using fopen $data = "My Name is Ravi\n"; //What you want to write and \n is line break like enter fwrite($file_operation, $data); //Write the data into file $data2 = "I Love Programming\n"; //Add new data fwrite($file_operation, $data); //Write the data into file print "Success!"; // Print some message fclose($file_operation); //close the file ?>
Output of myfile.txt is: My Name is Ravi I Love Programming
Rewrite Data
If we were to run this very same thing again only using different data, it would erase all of our current data, and replace it with the new data. Here is an example:<?php $file = "myfile.txt"; //Select the file $file_operation = fopen($file, 'w'); //Open the file using fopen $data = "Hello Technokida, Tutorial of Write file in PHP\n"; fwrite($file_operation, $data); print "Success!"; fclose($file_operation); ?>The file we created, myfile.txt, now contains this data: Hello Technokida, Tutorial of Write file in PHP
Add more data to file
In above examples, we set only WRITE permission for the file, so in that case, when you are going to add data it will erase old data and start writing it from first. If you want to APPEND new data then you have to change file permission, Here is an example:<?php $file = "myfile.txt"; $file_operation = fopen($file, 'a'); $data = "Welcome to Technokida\n"; fwrite($file_operation, $data); $data = "Ravi Vadhel\n"; fwrite($file_operation, $data); $data = "File Handling in PHP\n"; fwrite($file_operation, $data); print "Success!"; fclose($file_operation); ?>
This should add these three string to the end of the file, so our file output is: Hello Technokida, Tutorial of Write file in PHP Welcome to Technokkida Ravi Vadhel File Handling in PHP You can write your views in the comment box, Read our other PHP tutorial articles.
sneezes and itchy eyes that often accompany allergies. Using a few of these measures might just help allergy sufferers to find some relief.satta king play bazaarv
ReplyDelete