Tuesday 2 June 2015

PHP Write to File

<?php
function write_to_file($fn, $str)
{
 if ($str == '') return 'Nothing to write...';
 if ($fn == '') return 'No file to write to...';
 if (($fp = @fopen($fn, 'w')) === false) return 'Error obtaining file handle';
 if (@fwrite($fp, $str, strlen($str)) === false)
 {
  fclose($fp);
  return 'Error writing to file';
 }
 fclose($fp);
 return 'Data written to file successfully';
}
?>
 
A simple function that writes whatever you pass to it in a file.
 

Usage

Possibly you need to check your permissions in order for PHP to write to the file. This function will overwrite what's in the file if you call it again. Check PHP's site for fopen modes: http://www.php.net/manual/en/function.fopen.php

How to:

$str = 'This is a string...';
echo write_to_file('/home/tester/myfile.txt', $str);
  

0 comments:

Post a Comment