Php права на чтение

fileperms

Возвращает права доступа на указанный файл в числовом виде. Младшие биты этого значения такие же, как и биты прав доступа для использования в функции chmod() , однако, на большинстве платформ, возвращаемое значение будет также включать информацию о типе файла, который передан в качестве параметра filename . Примеры ниже демонстрируют как проверить возвращаемое значение на наличие определённых прав и типа файла на POSIX-системах, включая Linux и macOS.

Для локальных файлов, возвращаемое значение является частью структуры st_mode , которая возвращается функцией С-библиотеки stat() . Какие в точности биты установлены может варьироваться от платформы к платформе. Рекомендуется поискать документацию к вашей платформе, если требуется обработка битов возвращаемого значения, не относящихся к правам доступа.

Возвращает false в случае возникновения ошибки.

Ошибки

В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .

Примеры

Пример #1 Отображение прав доступа в виде восьмеричного числа

echo substr ( sprintf ( ‘%o’ , fileperms ( ‘/tmp’ )), — 4 );
echo substr ( sprintf ( ‘%o’ , fileperms ( ‘/etc/passwd’ )), — 4 );
?>

Результат выполнения данного примера:

Пример #2 Отображение полных прав доступа

switch ( $perms & 0xF000 ) case 0xC000 : // сокет
$info = ‘s’ ;
break;
case 0xA000 : // символическая ссылка
$info = ‘l’ ;
break;
case 0x8000 : // обычный
$info = ‘r’ ;
break;
case 0x6000 : // файл блочного устройства
$info = ‘b’ ;
break;
case 0x4000 : // каталог
$info = ‘d’ ;
break;
case 0x2000 : // файл символьного устройства
$info = ‘c’ ;
break;
case 0x1000 : // FIFO канал
$info = ‘p’ ;
break;
default: // неизвестный
$info = ‘u’ ;
>

Результат выполнения данного примера:

Примечания

Замечание: Результаты этой функции кешируются. Более подробную информацию смотрите в разделе clearstatcache() .

Начиная с PHP 5.0.0, эта функция также может быть использована с некоторыми обёртками url. Список обёрток, поддерживаемых семейством функций stat() , смотрите в разделе Поддерживаемые протоколы и обёртки.

Смотрите также

  • chmod() — Изменяет режим доступа к файлу
  • is_readable() — Определяет существование файла и доступен ли он для чтения
  • stat() — Возвращает информацию о файле

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
?>

Источник

Работа с правами доступа к файлам через PHP

Работа с правами доступа к файлам через PHP

В прошлой статье я достаточно подробно рассказал о правах доступа к файлам. Разумеется, это только теория, которую необходимо знать, чтобы правильно использовать функции для работы с правами доступа к файлам через PHP. Эту тему мы разберём в данной статье.

Я уже говорил, что у файла всегда есть владелец, и у каждого файла имеется информация о его владельце. Каждый пользователь имеет свой UID (уникальный идентификатор), и именно этот идентификатор хранится в каждом файле. Чтобы узнать его, используется функция fileowner():

После этого будет получен UID владельца файла «myfile.txt«. Чтобы сменить владельца файла, надо воспользоваться функцией chown():

В данном примере мы передали права владельца «myfile.txt» пользователю myuser. Также вместо имени пользователя можно указывать его UID.

Следующая пара PHP-функций — это filegroup() и chgrp(), которые работают аналогично функциям fileowner() и chown(), но отвечают за группу пользователей:

echo filegroup(«myfile.txt»);
chgrp(«mygroup», «myfile.txt»);
?>

И, наконец, последние, но самые важные функции для работы с правами доступа к файлам через PHP — это fileperms() и chmod():

Как Вы уже догадались, функция fileperms() возвращает права доступа к файлу. А функция chmod() устанавливает новые права доступа к файлу. Также заметьте, что права задаются с обязательным указанием ведущего нуля!

Это самые основные и самые важные функции PHP для работы с правами доступа. Я бы даже сказал, что реально используются только последние две, поэтому с ними потренируйтесь в работе. И ещё раз напоминаю, что права доступа имеются только в Unix-системах, а в Windows их вообще нет, поэтому и данные функции там так же будут работать некорректно.

Создано 27.06.2011 21:34:13

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 8 ):

    А можно это как-то сделать чтобы это не видели пользователи? То есть, если они смотрят исходный код страницы и чтобы они в нем не увидели этого PHP-кода?

    Они его и не увидят. Этот код выполняется на сервере ещё до того, как пользователи увидят конечную HTML-страницу.

    Здравствуйте! Извините за возможно глупый вопрос, но когда добавляешь файлы через Админ-панель в папку с правами, например 744, нужно сначала поменять права на 777, добавить файл и обратно поменять права.

    По fileowner и filegroup выдаёт нули, а по fileperms выдаёт 33206. Такие дела.

    Дочитал и понял, в Windows не работает, можешь не замарачиваться

    Эта статья рассчитана на работу с хостингом (на Linux) через фтп-клиент к примеру. В Windows не много по-другому все устроено.

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    PHP File Permissions

    Summary: in this tutorial, you will learn how to deal with PHP file permissions, including checking and changing file permissions.

    File permissions specify what a user can do with a file, e.g., reading, writing, or executing it. Notice that PHP automatically grants appropriate permissions behind the scenes.

    For example, if you create a new file for writing, PHP automatically grants the read and write permissions.

    PHP provides some useful functions for checking and changing the file permissions.

    Checking file permissions

    PHP has three handy functions that check file permissions:

    • is_readable() function returns true if the file exists and is readable; otherwise, it returns false .
    • is_writable() function returns true if the file exists and is writable; otherwise, it returns false .
    • is_executable() function returns true if the file exists and executable; otherwise, it returns false .

    Let’s take a look at the following example:

     $filename = 'readme.txt'; $functions = [ 'is_readable', 'is_writable', 'is_executable' ]; foreach ($functions as $f) < echo $f($filename) ? 'The file ' . $filename . $f : ''; >Code language: HTML, XML (xml)

    Besides those functions, PHP also provides the fileperms() function that returns an integer, which represents the permissions set on a particular file. For example:

     $permissions = fileperms('readme.txt'); echo substr(sprintf('%o', $permissions), -4); //0666Code language: HTML, XML (xml)

    Changing file permissions

    To change the file permission or mode, you use the chmod() function:

    chmod ( string $filename , int $permissions ) : boolCode language: PHP (php)

    The chmod() function has two parameters:

    • $filename is the file that you want to change the permissions.
    • $permissions parameter consists of three octal number components that specify access restrictions for the owner, the user group in which the owner is in, and everyone else in this sequence.

    The chmod() function returns true on success or false on failure.

    The permissions argument is represented by an octal number that contains three digits:

    • The first digit specifies what the owner of the file can read, write, or execute the file.
    • The second digit specifies what the user group in which the owner is in can read, write, or execute the file.
    • The third digit specifies what everyone else can read, write, or execute the file.

    The following table illustrates the value of each digit that represents the access permission for particular users ( owner, user group, or everyone else) :

    Value Permission
    0 cannot read, write or execute
    1 can only execute
    2 can only write
    3 can write and execute
    4 can only read
    5 can read and execute
    6 can read and write
    7 can read, write and execute

    The following example sets permission that the only owner can read and write a file, everyone else only can read the file:

     $filename = './readme.txt'; chmod($filename, 0644);Code language: HTML, XML (xml)

    Notice that we put 0 before 644 to instruct PHP to treat it as an octal number.

    Summary

    • Use the is_readable() , is_writable() , is_executable() to check if a file exists and readable, writable, and executable.
    • Use the chmod() function to set permissions for a file.

    Источник

    Читайте также:  Лабораторные работы java наследование
    Оцените статью