php文件对于非现有文件不可写

I have the following code to write to a file.

$ics_file   = "/var/www/Untis/ICS/$ID.ics"; 
if (is_writable($ics_file)) {
  if (!$handle = fopen($ics_file, 'c')) {
     echo "Cannot open file ($ics_file)

";
     exit;
  }
  if (fwrite($handle, $ics_contents) === FALSE) {
    echo "Cannot write to file ($ics_file)

";
    exit;
  }
  fclose($handle);
} else {
  echo "The file <b>$ics_file</b> is not writable

";
}

This code only works if a manually create the file and then chmod it to 777 from the terminal. However I have already made the directory in which it's writing, 777 and I changed the group to www-data.

pi@raspberrypi /var/www/Untis $ ls -all
total 44
drwxrwxrwx 2 pi   www-data 4096 Sep 27 20:49 ICS

However I'm still unable to write in there. The error I'm getting is:

The file /var/www/Untis/ICS/CTE152B.ics is not writable.

I'm currently clueless why its not working for new files, if I chmod the dir to 777 php should be able to write in there right?