umask
umask() устанавливает PHP umask в значение mask & 0777 и возвращает старую umask. Если PHP используется в качестве серверного модуля, umask будет восстанавливаться после окончания каждого запроса.
Список параметров
Возвращаемые значения
Если параметр mask равен null , функция umask() просто возвращает текущую umask, в противном случае возвращается старая umask.
Список изменений
Примеры
Пример #1 Пример использования umask()
$old = umask ( 0 );
chmod ( «/path/some_dir/some_file.txt» , 0755 );
umask ( $old );
?php
// Проверка
if ( $old != umask ()) die( ‘При восстановлении umask произошла ошибка’ );
>
?>
Примечания
Замечание:
Избегайте использования этой функции в многопоточных веб-серверах. Лучше изменить права файла с помощью функции chmod() после его создания. Использование umask() может привести к неожиданному поведению одновременно работающих скриптов и самого веб-сервера, т.к. они все будут использовать одну и ту же umask.
User Contributed Notes 14 notes
I think that the best way to understand umask is to say that umask is used to revoke permissions, not to set permissions.
umask sets which permissions must be removed from the system default when you create a file or a directory.
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 that any file from now on 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 example above, with the 666 system default, there is no way you can use umask to create a file with execute permission. If you want to grant more permissions, use chmod.
Be aware that system default permissions are not related to PHP (they depends upon server configuration). PHP has a default umask that is applied after system default base permissions. And there are different system default base permissions for files and directories.
Usually, system default permissions for files are 666 and for directories 0777. And usually, default PHP umask is 0022
«It is better to change the file permissions with chmod() after creating the file.»
The usual lacking of security knowledge within the PHP team rears its head once again. You *always* want to have the file created with the proper permission. Let me illustrate why:
(a) you create new file with read permissions
(b) an attacking script opens the file
(c) you chmod the file to remove read permissions
(d) you write sensitive data to the file
Now, you might think that the changes of an attacking script getting to open the file before you chmod them are low. And you’re right. But low changes are never low enough — you want zero chance.
When creating a file that needs increased permissions, you always need to create the file with the proper permissions, and also create it with O_EXCL set. If you don’t do an exclusive create, you end up with this scenario:
(a) attacker creates the file, makes it writable to everyone
(b) you open the file with restricted permissions, but since it already exists, the file is merely opened and the permissions left alone
(c) you write sensitive data into the insecure file
Detecting the latter scenario is possible, but it requires a bit of work. You have to check that the file’s owner and group match the script’s (that is, posix_geteuid(), not myuid()) and check the permissions — if any of those are incorrect, then the file is insecure — you can attempt to unlink() it and try again while logging a warning, of course.
The only time when it is reasonable or safe to chmod() a file after creating it is when you want to grant extra permissions instead of removing them. For example, it is completely safe to set the umask to 0077 and then chmoding the files you create afterward.
Doing truly secure programming in PHP is difficult as is, and advice like this in the documentation just makes things worse. Remember, kids, anything that applies to security in the C or UNIX worlds is 100% applicable to PHP. The best thing you can possibly do for yourself as a PHP programmer is to learn and understand secure C and UNIX programming techniques.
fileperms
Returns the file’s permissions as a numeric mode. Lower bits of this mode are the same as the permissions expected by chmod() , however on most platforms the return value will also include information on the type of file given as filename . The examples below demonstrate how to test the return value for specific permissions and file types on POSIX systems, including Linux and macOS.
For local files, the specific return value is that of the st_mode member of the structure returned by the C library’s stat() function. Exactly which bits are set can vary from platform to platform, and looking up your specific platform’s documentation is recommended if parsing the non-permission bits of the return value is required.
Returns false on failure.
Errors/Exceptions
Upon failure, an E_WARNING is emitted.
Examples
Example #1 Display permissions as an octal value
echo substr ( sprintf ( ‘%o’ , fileperms ( ‘/tmp’ )), — 4 );
echo substr ( sprintf ( ‘%o’ , fileperms ( ‘/etc/passwd’ )), — 4 );
?>?php
The above example will output:
Example #2 Display full permissions
switch ( $perms & 0xF000 ) case 0xC000 : // socket
$info = ‘s’ ;
break;
case 0xA000 : // symbolic link
$info = ‘l’ ;
break;
case 0x8000 : // regular
$info = ‘r’ ;
break;
case 0x6000 : // block special
$info = ‘b’ ;
break;
case 0x4000 : // directory
$info = ‘d’ ;
break;
case 0x2000 : // character special
$info = ‘c’ ;
break;
case 0x1000 : // FIFO pipe
$info = ‘p’ ;
break;
default: // unknown
$info = ‘u’ ;
>
The above example will output:
Notes
Note: The results of this function are cached. See clearstatcache() for more details.
As of PHP 5.0.0, this function can also be used with some URL wrappers. Refer to Supported Protocols and Wrappers to determine which wrappers support stat() family of functionality.
See Also
- chmod() — Changes file mode
- is_readable() — Tells whether a file exists and is readable
- stat() — Gives information about a file
User Contributed Notes 9 notes
Don’t use substr, use bit operator
decoct ( fileperms ( $file ) & 0777 ); // return «755» for example
?>
If you want to compare permission
0755 === ( fileperms ( $file ) & 0777 );
?>
This may not be immediately apparent to some, but you can use octdec( $octal_value ) to match the permissions retrieved by file perms
//assumes file has 2770 permissions
$perm = fileperms ( __FILE__ );
$bit = «102770» ;
printf ( «%s\n» , octdec ( $bit ) );
printf ( «%s\n» , $perm );
An easy way to calculate fileperms to chmod is this:
Displays 666 or 777 (depends on chmod set).
Displays 0666 or 0777 and refers immediately to the number set with chmod();
Windows has a very different file permission model to Unix and integrates them only minimally.
Here’s how Windows calculates the bitmask.
u+w/g+w/o+w is set based on whether the file has the read only flag.
u+x/g+x/o+x is set based on whether $filename is an inherently executable file (e.g. bat) or a directory.
Windows isn’t integrating its ACLs at all.
Here is a small function I made : http://pastebin.com/iKky8Vtu
I was bored and I thought it could be useful.
mixed mkperms( string $perms [, bool return_as_string = false [, string $filename ] ] )
Returns permissions given a string in literal format and a filename.
If the file name is omitted, the permissions that the function will return are based on 000-permissions.
If return_as_string is set to true, the result will be output as a 644 format string. Otherwise it will return a string converted to base-10 for chmod.
echo mkperms ( ‘u+r’ , true ), «\n» ; // 400
echo mkperms ( ‘u+rwx,g+rw,o+x’ , true ), «\n» ; // 761
touch ( ‘myfile.txt’ ); // Create a file with any permissions
chmod ( ‘myfile.txt’ , mkperms ( ‘u=rwx,g=x,o=rw’ )); // myfile.txt is now at -rwx—xrw-
// Make a file and give it full permissions
touch ( ‘somefile.txt’ );
chmod ( ‘somefile.txt’ , 0777 );
echo mkperms ( ‘g-w,o-rw’ , true , ‘somefile.txt’ ); // 751
echo mkperms ( ‘u=rwx,g-r,o=-‘ , true , ‘somefile.txt’ ); // 730
// This way you can apply permissions to files
chmod ( ‘somefile.txt’ , mkperms ( ‘u=rwx,g-r,o=-‘ , false , ‘somefile.txt’ )); // somefile.txt is now at -rwx-wx—
?>
PS : sorry I had to put it on pastebin, or else it just made the note way too long.
A small function for the last 3 digits (777/755 ect.)
function getFilePermission ( $file ) $length = strlen ( decoct ( fileperms ( $file )))- 3 ;
return substr ( decoct ( fileperms ( $file )), $length );
>
?>
Since the output of decoct( fileperms(‘.’) ) is of the form: 40644
It seems the previous example is wrong, instead you should understand:
To get permissions formatted as «644»:
echo substr ( decoct ( fileperms ( ‘.’ ) ), 2 );
?>
To get permissions formatted as «0644»:
echo substr ( decoct ( fileperms ( ‘.’ ) ), 1 );
?>
On Linux (not tested on Windows), if you want a chmod-like permissions, you can use this function:
function file_perms ( $file , $octal = false )
if(! file_exists ( $file )) return false ;
return substr ( decoct ( $perms ), $cut );
>
?>
Using it:
$ touch foo.bar
$ chmod 0754 foo.bar
echo file_perms ( ‘foo.bar’ ); // prints: 754
echo file_perms ( ‘foo.bar’ , true ); // prints 0754
?>