Home >>Advance PHP Tutorial >PHP File create write
<?php $fo=fopen("filename","mode"); ?>
Modes | Description |
---|---|
w | Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist |
w+ | Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist |
r | Read only. Starts at the beginning of the file |
r+ | Read/Write. Starts at the beginning of the file |
a | Append. Opens and writes to the end of the file or creates a new file if it doesn't exist |
a+ | Read/Append. Preserves file content by writing to the end of the file |
x | Write only. Creates a new file. Returns FALSE and an error if file already exists |
x+ | Read/Write. Creates a new file. Returns FALSE and an error if file already exists |
<?php //write string to file $data="A fish out of water"; file_put_contents("output.txt",$data) or die('ERROR:Can not write file'); echo "data written inside this file"; ?>
<?php //write string to file $data="A fish out of water"; file_put_contents("output.txt",$data,FILE_APEND)or die('ERROR:Can not write file'); echo "data written inside this file"; ?>
<?php //open and lock file //write string to file //unlock and close file $data="A fish out of water"; $fo=fopen("output.txt","w"); flock($fo,LOCK_EX) or die('ERROR:cannot lock file'); fwrite($fo,$data); flock($fo,LOCK_UN) or die('ERROR:cannot unlock file'); fclose($fo); echo "Data written to file"; ?>
<?php //open and lock file //write string to file //unlock and close file $data="A fish out of water"; $fo=fopen("output.txt","w"); flock($fo,LOCK_EX) or die('ERROR:cannot lock file'); fputs($fo,$data); flock($fo,LOCK_UN) or die('ERROR:cannot unlock file'); fclose($fo); echo "Data written to file"; ?>