Create and write 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.

Please ensure you have 'chmod' or 'chown' the file to enable writting.

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 python django git Raspberry apache mysql php drupal cake javascript css AWS data