EvilZone
Programming and Scripting => Web Oriented Coding => : ande October 04, 2010, 04:54:01 PM
-
Here is a simple and quick way to write content to a file:
This will create or overwrite any existing file.
<?php
$FileHandle = fopen("MyFile.txt", 'w') or die("Cant open file!");
fwrite($FileHandle , "This is a nice file!");
fclose($FileHandle);
?>
This will create or append any existing file:
<?php
$FileHandle = fopen("MyFile.txt", 'a+') or die("Cant open file!");
fwrite($FileHandle , "This is a nice file!");
fclose($FileHandle);
?>
-
Old stuff, but it's cool, keep on :)
-
The reason why the second one appends and the first one doesn't, is because of the
$FileHandle = fopen("MyFile.txt", 'a+') or die("Cant open file!");
line.
Notice the a+? That means: append & read.
w3schools has a list of all opening types (by the lack of better words, lol) available here (http://w3schools.com/php/php_file.asp)
-
The reason why the second one appends and the first one doesn't, is because of the $FileHandle = fopen("MyFile.txt", 'a+') or die("Cant open file!");
line.
Notice the a+? That means: append & read.
w3schools has a list of all opening types (by the lack of better words, lol) available here (http://w3schools.com/php/php_file.asp)
r Read only. Starts at the beginning of the file
r+ Read/Write. Starts at the beginning of the file
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
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
One less click!
-
Always nice to have these resources on a place you're much.
Keep up the good work, maybe make some topics including most of the common functions and your experiences using them (like : "I wont really use this one this one is laggy, better use ..."" . ")
I would like a topic on php optimization, (or i will google ^-^).
-
<?php file_put_contents($file,$data); ?>
-
This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.
Plus, the fopen() call allows you to change the opening permissions more easily than the file_put_contents().
Nevertheless, file_put_contents is nice if you want to write something quickly :)