Creating and Writting files in PHP

Posted under » PHP on 16 April 2009

Create new file for writing

<¿php 
$fh = fopen("newfile.txt", "w"); // fh is file handle

if($fh==false) die("unable to create file");
?> 

The code above creates a new file myfile for writing only in the current directory.

The mode "w" creates a new file for writing, places the pointer in the beginning of the file. If the file already existed, it deletes everything in the file.

When you create a file, the function fopen returns a file pointer. If the attempt to create a file fails for any reason, the function returns false.

<¿php 
$fh = fopen("newfile.txt", "w+");
if($fh==false) die("unable to create file");
?> 

The mode "w+" creates a new file for reading and writing, places the pointer in the beginning of the file. If the file already existed, it deletes everything from the file.

Similarly, you can use mode 'a' and 'a+' for creating new files. However with these modes, if the file already exists, it will not truncate the file (i.e. it will not delete any content in the file) and places the pointer at the end of the file for writing.

finally, use fwrite to write to file.

$isi = "

Here is the contents.

"; if (fwrite($fh, $isi) === FALSE) { $kontent = "

Cannot write to file newfile.txt

"; exit; } $kontent = "

newfile.txt page updated

"; fclose($fh); echo $kontent;

Alternatively, you can use this.

<¿php
$fp = fopen('newfile2.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);
// the content of 'data.txt' is now 123 and not 23 because you have not close it yet.
?>

See also Implode, file_get_contents and substact string.

web security linux ubuntu GIT svn Raspberry apache mysql php drupal cake symfony javascript Ajax css