What are the best practices for handling file permissions and access rights when writing to files in PHP to prevent issues with file manipulation?

When writing to files in PHP, it is important to properly set file permissions and access rights to prevent unauthorized file manipulation. One common best practice is to set the file permissions to only allow the necessary users or groups to read, write, and execute the file. Additionally, it is recommended to validate user input and sanitize data before writing it to a file to prevent security vulnerabilities.

// Set file permissions to only allow the owner to read and write
$filename = 'example.txt';
$file = fopen($filename, 'w');
chmod($filename, 0600);

// Validate and sanitize user input before writing to the file
$data = $_POST['data'];
$sanitized_data = filter_var($data, FILTER_SANITIZE_STRING);
fwrite($file, $sanitized_data);
fclose($file);