PHP Create a file write and read the contents inside files - php cms - Phptpoint.com

PHP Create a file write and read the contents inside files

PHP Summer Training/Internship with 2 Live Projects in Noida Fee is only 5500/-Click here to Book Your Seat

/ins>

Read and Write the contents of a files in PHP

Create a file if not exist and write the contents.

Output
check your file manually
(a file is created with name myfile.txt and contents is saved inside the file)
enter your file
choose your extension
Enter your contents

In the above example
First create three field using HTML script (form with method=”post”)
i)Input textbox field : this is text field where user enters the file name
ii) select box : user selects the extension of file.
iii)textarea : user enters the content(data).
and a submit button with value =”Save”.
When user click on save button logic define inside PHP script perform their execution.
first it check the existence using isset($_POST[‘save’]). $_POST[‘file’], $_POST[‘ext’], $_POST[‘data’], is used to collect the values from a HTML form.
$file variable store the concatenation of file name and extension using($f.$ext).
Now check the existence of file using file_exists( ) function. if its true message show file is already exist. otherwise else condition execute . open the file using fopen () function pass two argument($file,”w”) w is used to write on file. function fwrite( ) with two arguments($fo,$data) write data on a file.
message is shown “your file saved”.

Read the contents from an existing files

Output
Output will display in textarea see on your browswer.
enter your file
choose your extension
Enter your contents

isset( ) is used to perform read operation on display button. $_POST [ ] is used to collect value from user Input.
( $file=$f.$ext) is used to get file name with extension file_exist( ) function is used to check ,the file is exist or not.

if file exist first it open the file using fopen( ) using with variable($fo), pass two argument $file ,”r” (is used to read the file).

Variable($contents) stored the content using fread( ) function with two argument($fo,filesize($file)).
It read the all contents of a file and display the contents in textarea.
otherwise show message file doesn’t exists.

Latest Trending Technologies