What are the best practices for setting file permissions and ownership when creating files in PHP?

When creating files in PHP, it is important to set appropriate file permissions and ownership to ensure security and access control. A common best practice is to set file permissions to restrict access to only necessary users and groups, and to set ownership to the appropriate user and group.

// Set file permissions and ownership when creating a file in PHP
$filename = 'example.txt';
$myfile = fopen($filename, 'w');
if ($myfile) {
    chmod($filename, 0644); // Set file permissions to 644
    chown($filename, 'www-data'); // Set ownership to the appropriate user (e.g. www-data)
    fclose($myfile);
    echo 'File created successfully with proper permissions and ownership.';
} else {
    echo 'Failed to create file.';
}