may be a ownership problem. try do chmod -R 775 /var/www/folder and/or chown -R domain:www-data /var/www/folder - where domain is the user of that particular virtualhost or www-data
Also to update a file instead rewrite you can use append option - adding + will help to create the file first time if it is not exists.
$file = fopen("test.php","a+");
echo fwrite($file,"do not vote me down ab");
fclose($file);
And If you want to change the ownership of the file you can use Php chown function-
chown('test.php','apache');
Too change permission of file or folder recusively use this code -
exec ("find /path/to/folder -type d -exec chmod 0750 {} +");
exec ("find /path/to/folder -type f -exec chmod 0644 {} +");