PHP-Read Write File
<Beginner PHP><Array><Loop><Function><Pre-Def variable><Session><Read Write File><CRUD>
Working with Files & Writing to a file
Functions for creating, reading, uploading and editing files.
fopen()
creates or opens a file
modes
r: open file for read only
w: open file for write only,
- erases content of file or
- creates new file if not exist
a:open file for write only
x: create new file for write only
rt: open file for read/write
wt: open file for read/write
- erase content of file
- create new file
a:open file for read/write.
- create new file if not exist
xt: create new file if not exist
Creating a file
$myfile=fopen("file.txt","w");
fwrite:
writes to a file. Parameters:
- file to write to
- string to be written
<?php
$myfile=fopen("names.txt","w");
$txt="Mickey\n";
fwrite($myfile,$txt);
$txt="David\n";
fwrite($myfile,$txt);
fclose($myfile);
/*Mickey
David*/
?>
Note: \n means new line
fclose()
closes an open file
returns TRUE on success, FALSE on failure
it is good practice to close the file after finishing the work.
Appending to a file
to append content to a file, we need to open the file in append mode
$myfile="test.txt";
$fh=fopen($myfile,'a');
fwrite($fh,"some text");
fclose($fh);
'a' : the file pointer is placed at the end of file. It ensures new data is added at the end.
<?php
if(isset($_POST['text'])){ // if form text box not empty
$name=$_POST['text']; //string to be written
$handle=fopen('names.txt','a'); // file to write as append
fwrite($handle, $name."\n"); // file,string
fclose($handle); //close file
}
?>
<form method="post">
Name:<input type="submit" name="submit"/>
</form>
Note: the form has no action attribute
Reading a file
the file() function reads the entire file into an array
Each elt within the array corresponds to a line in the file
$read=file('names.txt');
for each($read as $line){
echo $line.",";
}
//output Mickey, David,
Note : please note the comma after `David'
$read=file('names.txt');
$count=count($read);
$i=1
for each($read as $line){
echo $line;
if($i<$count){
echo ',';
}
$i++;
}
//output Mickey,David
Comments
Post a Comment