In this session today we will learn how to manipulate the file using php that is we will learn to create, read, append and write the content in the file .
- So to learn how to manipulate the file using php follow the steps given below :
- First of all download and install xampp server in your machine .
- Now go to Xampp -> htdocs folder and in this htdocs folder create a new folder say sample .
- In this sample folder create a new file called as index.php .
- After creating this file you will have the following view :
- Now open index.php file with any text editor for example Notepad++ and write the following code to create a file .
- Here is the screen shot for the code :
- Now save your file .
- Open up the browser and enter the following url localhost/sample/index.php and you will have the following output .
- Here you will not see anything in the output .
- When you run it in the browser it will create a file demo.txt in the sample folder under htdocs folder automatically which we had mentioned in the code .
- Now check the sample folder in your htdocs folder and you will have the demo.txt file created .
- If the file exits already then it will override the same .
- Now to read the data from the file add the following code in index.php file .
- Here is the screen shot for the code .
- Now save index.php file and run it in the browser you will have the following output :
- Now when you open the demo.txt file in notepad you will have the following view :
- Now lets learn to append the data in demo.txt file .
- Add the following code in index.php file to implement append functionality .
- When you run it in the browser window it will not display the appended content , for that we have to add the code to read an appended data in a file.
- Here is the screen shot for the added code :
- Now save and run the index.php file you will have the following output .
- Thus you can see the appended content in the browser window.
- Hence we have learn how to manipulate the file using php .
<?php $filename="demo.txt"; //Create a file demo.txt $fh=fopen($filename,'w') or die("Can not open file"); $content="In such a manner you can create a file"; fwrite($fh,$content); fclose($fh); ?>
//Read the data in the file $fh=fopen($filename,'r'); $content=fread($fh,filesize($filename)); fclose($fh); echo '<p>Before append'.$content.'</p>';
//Append the data to the file $fh=fopen($filename,'a'); $content="This is how to append data to file"; fwrite($fh,$content); fclose($fh);
//Read file with appended data $fh=fopen($filename,'r'); $acontent=fread($fh,filesize($filename)); //The acontent is the content tobe appended fclose($fh); echo '<p>After appended:'.$acontent.'</p>';
Hi Author,
Very Nice Post on PHP tricks, I am Newbie in PHP, find your post damn helpful. Surely bookmark this post for future use. My kind request to you that please keep on write this kind of article in future also.
Thanks