Few things. Make a backup first. Then write to a temporary file. Then check this file (reread it to make sure that it is syntactically correct and means that you think it does). Only then, a MOVE ( mv or rename() ) file on top of the original. That way, you can never get stuck in a position when another process is trying to read while you are still writing, or a write failure causes a syntax error, etc.
Edit:
There are several things you can do to escalate permissions.
One could write a script (shell) to check the file and perform the move. Then you can install this file. So you are writing a temporary file using PHP, checking it against PHP (in the end, you can never check too much). Then call the script to move the temporary file to the desired position (with elevated privileges).
Another would be to add an account with write permission only to these files (either via sudo, or normally). Then use PHP for su newuser -c "mv tmpfile finalfile" . You would have to disable authentication, but this is better than running PHP as consistent ...
Another option is to use the SSH extension for ssh in the field (using the private key), upload the file and copy it to the final destination.
But somehow you do it, if PHP is hacked, they have access to these files, since PHP has a way ...
source share