Correct file permissions for WordPress

All files should be owned by your user account, and should be writable
by you. Any file that needs write access from WordPress should be
writable by the web server, if your hosting set up requires it, that
may mean those files need to be group-owned by the user account used
by the web server process.

How do I give PHP write access to a directory?

I’m trying to use PHP to create a file, but it isn’t working. I am assuming this is because it doesn’t have write access (it’s always been the problem before). I tried to test if this was the problem by making the folder chmod 0777, but that just ended up making every script in that directory return a 500 error message until I changed it back.
How do I give PHP write access to my file system so it can a create a file?