[Snippet] File Write/Read

xhtmlphp

Member
Reputation
0
File write; if file does not exist it will attempt to create it, also it will write to the end of the file
Code:
$data = 'Some text';
$filename = 'file.html';
$open = fopen($filename, "a+");
fwrite($open, $data);
fclose($open);

File write; if file does not exist it will attempt to create it, also it will write to the beginning of the file. Meaning that it will clear all the text within the document and replace it.
Code:
$data = 'Some text';
$filename = 'file.txt';
$open = fopen($filename, "w+");
fwrite($open, $data);
fclose($open);


File read; the contents of the file will be saved under the '$contents' variable.
Code:
$filename = 'file.txt';
$open = fopen($filename, "rb");
$contents = fread($open, filesize($filename));
fclose($open);
 

correcting you

btw you can just use ... file_exists()

PHP:
$data = 'Some text';
$filename = 'file.html';
$open = fopen($filename, "x+"); // a just appends. x+ creates .
fwrite($open, $data);
fclose($open);
rename("images","pictures");


this is TOTALLY wrong.

PHP:
$filename = 'file.txt';
$open = fopen($filename, "a+");
$contents = rename($filename, newfilename.txt);
fclose($open);
 

I've always looked at this and it has never been wrong...
 
Proof said:
Where did you get "rb" from?

I'm not criticizing you, just helping.

Ages ago I read a snippet using 'rb' and have used it ever since for reading a file; I didn't just copy/paste it every time though
 


it's probably depreciated... just use the

PHP:
rename($name, $newname);
 
He reported it to be removed and I wasn't sure which post.
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…