EvilZone

Programming and Scripting => Web Oriented Coding => : ande October 04, 2010, 04:54:01 PM

: Write to file
: 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);
?>

: Re: Write to file
: Zyrukas November 26, 2010, 11:09:50 PM
Old stuff, but it's cool, keep on :)
: Re: Write to file
: iLike November 29, 2010, 07:23:55 PM
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)
: Re: Write to file
: ande November 29, 2010, 09:13:06 PM
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!
: Re: Write to file
: Stackprotector November 30, 2010, 09:02:49 AM
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 ^-^).
: Re: Write to file
: Nahid December 09, 2010, 05:10:37 AM
:
<?php file_put_contents($file,$data); ?>
: Re: Write to file
: iLike December 12, 2010, 02:50:46 PM
:
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 :)