The folder, directory
where you want to write a new 'fiename.txt'
has to be set to correct CHMOD Permission.
That is, the user that runs your.php that fwrite should have write permission
to create new file.
when you connect from Browser, running this php page
you are not root, you are a guest from internet
even if you run in your same computer.
apache server does not know you are special user
so, folder where you want to fopen, fwrite fclose
should be CHMOD 777 = all can fwrite
your server use Windows or Linux?
your server is Apache?