your script is fine it's the test.file that does not have the correct permissions. You are opening test.file to write to it. So test.file needs write permissions on it. if the file does not exist yet you will need to create it and change the permissions of the output file to 777. another thing you can do is chown the directory to use the webserver user. usually nobody.
Let me know if you don't understand