Ok, here it goes, in no-offence-I-assume-you-are-all-dorks-mode 🙂
777 is bad because it offers Read Write and eXecute rights to anyone on the box. (1=execute, 2=Write, 4=read, 1+2+4=7 for the users in the same group, and 7 for everyone else)
What you'd want is 600, which is read/write for you and you alone. (don't need X on PHP files, and every right you don't need is a right too many)
Unfortunately the webserver itself runs as a user (and that user is not you), so 600 would mean that the webserver can't read your files.
If the webserver user is in the same group as you, you could use 640; RW for you, R for the webserver. If the webserver user is not in your group, you'd need 604; RW for you, nothing extra for users in your group, Rfor everyone.
But, on a shared host there is usally one webserver for all clients, so the webserver is one user that is shared by all the clients.
That user needs R on all the PHP files.
That means it can read your PHP, but also also all the files of all other clients; your PHP script (which is executed by the webserver user) can read all the scripts of all other clients.
The only "safe" solution to this is to either run a seperate webserver for every client, or to put all the data that you don't want others to see into environment variables inside your webserver.
Unfortunately many hosts will not let you do either of the two. (because it's more work for them)
Writing has exactly the same problem, the webserver needs W permissions on the files you want to write to, which automatically gives W permissions on those files to the rest of the clients. It's just a matter of time untill a hacker finds out which of your files has W permission.
How can you safeguard against this?
You can't. Not without help from your ISP.
The best you can do is set 640 or 660 (or 604/606 depending on the IQ of your ISP) and hope people don't find your files/there are no hackers on the server.