I would like to save some info to a file on my server using the __destruct()
function in one of my classes.
However, every time I try to use file_put_contents(...)
inside __destruct()
, I get this error:
Warning: file_put_contents(HTMLcache.txt): failed to open stream: Permission denied in /Applications/MAMP/htdocs/time/HJ_Tag.php on line 141
file_put_contents(...)
works just fine in other parts on my code, where it is called on the exact same file. What might it be causing this error during __destruct()
, and how can I fix it?
I think you mean __destruct()
instead of __destroy()
, so I edited your post.
Can PHP save to a file during __destruct()
Yes, it can.
However, when you use relative filename with file_put_contents()
like this:
file_put_contents('hello.txt', 'hello world');
The file may actually be created somewhere you're not expecting and you may not have write permission there, which explains the error message.
In my case, it was created in C:\Users\Rei\AppData\Local\VirtualStore
.
Which is odd because I never specified that directory.
I had to search my entire harddrive to find it.
To prevent that, always use absolute filename.
For instance, add __DIR__
before the filename.
file_put_contents(__DIR__ . 'hello.txt', 'hello world');
And make sure you have write permission.