Функция chmod в php

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.

Источник

chmod

Attempts to change the mode of the specified file to that given in permissions .

Parameters

Note that permissions is not automatically assumed to be an octal value, so to ensure the expected operation, you need to prefix permissions with a zero (0). Strings such as «g+w» will not work properly.

chmod ( «/somedir/somefile» , 755 ); // decimal; probably incorrect
chmod ( «/somedir/somefile» , «u+rwx,go+rx» ); // string; incorrect
chmod ( «/somedir/somefile» , 0755 ); // octal; correct value of mode
?>

The permissions parameter consists of three octal number components specifying access restrictions for the owner, the user group in which the owner is in, and to everybody else in this order. One component can be computed by adding up the needed permissions for that target user base. Number 1 means that you grant execute rights, number 2 means that you make the file writeable, number 4 means that you make the file readable. Add up these numbers to specify needed rights. You can also read more about modes on Unix systems with ‘man 1 chmod‘ and ‘man 2 chmod‘.

// Read and write for owner, nothing for everybody else
chmod ( «/somedir/somefile» , 0600 );

// Read and write for owner, read for everybody else
chmod ( «/somedir/somefile» , 0644 );

// Everything for owner, read and execute for others
chmod ( «/somedir/somefile» , 0755 );

// Everything for owner, read and execute for owner’s group
chmod ( «/somedir/somefile» , 0750 );
?>

Return Values

Returns true on success or false on failure.

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Note:

The current user is the user under which PHP runs. It is probably not the same user you use for normal shell or FTP access. The mode can be changed only by user who owns the file on most systems.

Note: This function will not work on remote files as the file to be examined must be accessible via the server’s filesystem.

See Also

  • chown() — Changes file owner
  • chgrp() — Changes file group
  • fileperms() — Gets file permissions
  • stat() — Gives information about a file

Источник

chmod

Осуществляет попытку изменения режима доступа указанного файла на режим, переданный в параметре mode .

Список параметров

Обратите внимание, что значение параметра mode не переводится автоматически в восьмеричную систему счисления, поэтому, чтобы удостовериться в том, что режим был установлен верно, предваряйте нулем (0) значение передаваемое в параметре mode . Строки, такие как «g+w», не будут работать должным образом.

chmod ( «/somedir/somefile» , 755 ); // десятичное, скорее всего, указано неверно
chmod ( «/somedir/somefile» , «u+rwx,go+rx» ); // строка, неверный способ
chmod ( «/somedir/somefile» , 0755 ); // восьмеричное, верный способ
?>

Значение параметра mode состоит из трех восьмеричных чисел, определяющих уровень доступа для владельца файла, для группы, в которую входит владелец, и для других пользователей, соответственно. Число, определяющее уровень пользователя, может быть вычислено путем суммирования значений, определяющих права: 1 — доступ на выполнение, 2 — доступ на запись, 4 — доступ на чтение. Сложите эти числа для указания нужного права доступа. Более подробно о системе прав в системах Unix вы можете узнать с помощью команд ‘man 1 chmod‘ и ‘man 2 chmod‘.

// Доступ на запись и чтение для владельца, нет доступа для других
chmod ( «/somedir/somefile» , 0600 );

// Доступ на запись и чтение для владельца, доступ на чтение для других
chmod ( «/somedir/somefile» , 0644 );

// Полный доступ для владельца, доступ на чтение и выполнение для других
chmod ( «/somedir/somefile» , 0755 );

// Полный доступ для владельца, доступ на чтение и выполнение для группы владельца
chmod ( «/somedir/somefile» , 0750 );
?>

Возвращаемые значения

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

Примечания

Замечание:

Текущим пользователем является пользователь, от имени которого выполняется PHP. Возможно, что это будет не тот пользователь, под именем которого вы получаете доступ к командной оболочке или учетной записи FTP. На большинстве систем режим доступа к файлу может быть изменен только его владельцем.

Замечание: Эта функция неприменима для работы с удаленными файлами, поскольку файл должен быть доступен через файловую систему сервера.

Замечание:

При включенном безопасный режим PHP проверяет имеет ли файл или директория, с которой вы работаете, такой же UID (id владельца), как и выполняемый скрипт. Кроме того, вы не можете устанавливать SUID, SGID и «липкие» (sticky) биты.

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

  • chown() — Изменяет владельца файла
  • chgrp() — Изменяет группу владельцев файла
  • fileperms() — Возвращает информацию о правах на файл
  • stat() — Возвращает информацию о файле

Источник

Читайте также:  Css maximum я index
Оцените статью