PHP - Write into a file with PHP

4 posts Page 1 of 1
Contributors
User avatar
Danny
VIP - Donator
VIP - Donator
Posts: 621
Joined: Sat Oct 30, 2010 8:21 pm

PHP - Write into a file with PHP
Danny
heey guys!
Let's start!
Create a code to write a file and open it in php,
let's start with the code:
Code: Select all
$fileName = 'test.txt';
$file = fopen($fileName,'w');
if ($file === FALSE) {
    echo "Can’t open file!";
}
 
$text = "This is a simple message" . PHP_EOL;
fwrite($file, $text);
fwrite($file, "Other text" . PHP_EOL);
 
fclose($file);
Done! lmao;
see that is simple!
User avatar
Livengood
Serious Programmer
Serious Programmer
Posts: 444
Joined: Tue Feb 16, 2010 6:24 am

This is a great code for some people to get the hang of this. :) thanks for sharing.
Image
User avatar
Danny
VIP - Donator
VIP - Donator
Posts: 621
Joined: Sat Oct 30, 2010 8:21 pm

Re: PHP - Write into a file with PHP
Danny
I'm glad that someone like it ;D
User avatar
Kelly
Linux Users
Linux Users
Posts: 11
Joined: Sun Nov 20, 2011 5:49 am

Re: PHP - Write into a file with PHP
Kelly
Just so you know; you can change this:
Code: Select all
if ($file === FALSE) {
    echo "Can’t open file!";
} 
to
Code: Select all
if(!$file) echo "Can’t open file!"; 
or
Code: Select all
$file = fopen($fileName,'w') or die('Can\'t open file!' . chr(10));
Here is my re-writting version:
Code: Select all
$fileName = 'test.txt';
$file = @fopen($fileName,'a') or die('Can\'t open/create file!' . chr(10));;

$text = "This is a simple message" . PHP_EOL;
@fwrite($file, $text) or print('Failed to write to file.' . chr(10));
@fwrite($file, "Other text" . PHP_EOL) or print('Failed to write to file.' . chr(10));

@fclose($file); 
4 posts Page 1 of 1
Return to “Tutorials”