Why PHP script does not create a directory with 777 permissions ?
In PHP, we aren’t able to create a directory with 777 permission because of default umask. The umask is called a user mask or user file creation mask. This is a kind of base permission or default permission given when a new file or folder is created. The default value of umask is generally 022. The umask sets in which permissions must be removed from the system default when you create a file or a directory.
First of all, let’s understand how umask actually works during file or directory creation and permission setup. We will use mkdir() function in below examples.
- Example 1:
For example, a mask 0022 means that you don't want group and others modify the file. default 0666 rw-.rw-.rw- umask 0022 ---.-w-.-w- Final 0644 rw-.r--.r-- That means any file from now will have 0644 permissions.
It is important to understand that umask revokes, deletes permissions from system default, so it can’t grant permissions the system default hasn’t. In the above example, with the 666 system default, there is no way you can use umask to create a file with execute permission.
- Example 2: Suppose the permission of new directory created to be 665 OR mkdir(“geeks”, 655); The folder “geeks” will have permission: drw–wx-wx
The original permission according to 655 is drw-r-xr-x. But the result is drw--wx-wx. Permission to be applied: 655 Default umask : 022 Final : 633 This is obtained by performing subtraction.
So, When we try to create a directory with permission 777, instead of getting drwxrwxrwx we get drwxr-xr-x which corresponds to 755 ( subtracting 022 from 777). This is the reason why we aren’t able to create a directory with permission 777.
It’s not over yet, as I never said it is impossible to create a directory with permission 777. So let’s learn how to create a directory with 777 permission, follow the below steps:
- Step 1: This line changes the umask to zero while storing the previous one into $oldmask.
$oldmask = umask(0)
- Step 2: This line makes the directory using the desired permissions and (now irrelevant) umask.
- Step 3: This line restores the umask to what it was originally.
This is how you can create a directory with 777 permission. The permission 777 in symbolic representation for directory is drwxrwxrwx. This permission allows the owner user, group, and others to read, write, and execute, so it has no restriction. This permission means that anyone who is a user on the same server can read, write, and execute the file. In the case of a folder, anyone who is a user will be able to copy files to it. This obviously sounds dangerous if you are using a shared server for your website.
Please Login to comment...