<span><span><span class="hljs-meta"><?php</span></span><span>
</span><span><span class="hljs-comment">// This part of the code is unrelated to the article content and is just an example introduction</span></span><span>
</span><span><span class="hljs-keyword">echo</span></span><span> </span><span><span class="hljs-string">"Welcome to the PHP file permissions tutorial."</span></span><span>;
</span><span><span class="hljs-meta">?></span></span><span>
<p><hr></p>
<p></span><?php<br>
/*<br>
Article Title: How to Control Default Permissions of Newly Created Files Using PHP's umask Function: An Example<br>
*/</p>
<p>// In PHP, the umask function sets the process's file permission mask, controlling default permissions for newly created files or directories.<br>
// By default, Linux assigns 0666 (rw-rw-rw-) for new files and 0777 (rwxrwxrwx) for new directories.<br>
// The umask function restricts permissions by masking certain bits.</p>
<p>// For example, umask(0022) masks the permissions corresponding to 0022, preventing write access for group and others.<br>
// The default permissions for new files become 0666 & ~0022 = 0644 (rw-r--r--)<br>
// The default permissions for new directories become 0777 & ~0022 = 0755 (rwxr-xr-x)</p>
<p>// Example illustration:</p>
<p>// Set the umask value<br>
umask(0022);</p>
<p>// Create a file<br>
$file = 'testfile.txt';<br>
file_put_contents($file, "This is a test file.");</p>
<p>// Check file permissions<br>
$perms = fileperms($file) & 0777; // Extract only permission bits<br>
printf("Permissions of file %s: %o\n", $file, $perms);</p>
<p>/*<br>
Typical output:<br>
File testfile.txt permissions: 644</p>
<p>This indicates the new file has rw-r--r-- permissions: owner can read/write, group and others read-only.<br>
*/</p>
<p>// To change the default permissions, adjust the umask value, e.g.:<br>
umask(0000); // No permissions are masked</p>
<p>// Create another file<br>
$file2 = 'testfile2.txt';<br>
file_put_contents($file2, "A test file with more permissive settings.");</p>
<p>// Check new file permissions<br>
$perms2 = fileperms($file2) & 0777;<br>
printf("Permissions of file %s: %o\n", $file2, $perms2);</p>
<p>/*<br>
Permissions are usually 666 (rw-rw-rw-), meaning all users have read and write access.<br>
*/</p>
<p>// Notes:<br>
// 1. umask only affects files or directories created by the current PHP process.<br>
// 2. Existing file permissions are not affected by umask.<br>
// 3. The web server user's permissions and OS security policies also influence the final permissions.</p>
<p>// In summary, the umask function provides a convenient way to control default permissions for new files and directories in PHP.<br>
// Correctly setting umask helps ensure file security and prevents risks from overly permissive permissions.</p>
<p data-is-last-node="" data-is-only-node="">?><br>
</span>