PHP writing a file

this code will create a directory and write a file inside of it. If file already exists will append to it, if not will create it.

 

IMPORTANT: if you are executing as a CGI program, the directory you are writing to must have filemode of that is writable by the running cgi process. In our case that unfortuantely means 777 (yes---because the CGI program is run not as your longin as owner but, generally as some other user, like "nobody"). This will mean that you will NEED to create the directory $mypath first and set the mode to 777 for this directory. Notice then that the file created "test.txt" will be owned by "nobody" not your login. HOWEVER, you can create a directory that is owned by the process owner of the cgi but, that still needs to be writeable. THIS IS REALLY BAD TO DO---- NEVER DO THIS.

 

<?php
$mypath="/home/faculty/grewe/public_html/PHP/files";
mkdir($mypath,0777,TRUE);
$filename = $mypath.'/test.txt';
$handle = fopen($filename,"x+");
$d = date('Y-m-d');
$t = time();
$somecontent = "Add this to the file ".$d." ".$t."\n";
fwrite($handle,$somecontent);
echo "Success";
fclose($handle);
?>

 

try it now:

 

results directory here

 

© Lynne Grewe