What is the chmod() function in PHP?

The chmod() function in PHP is a built-in function of PHP. We use this function in situations where certain permissions of a file need to be updated.

Syntax

chmod ( string $filename, int $mode )

Parameters

filename: The file whose permissions are supposed to be updated by the user.

mode: Octal value representing the new value of the mode.

Modes

Let’s understand the value of mode a little further.

  1. The first value is always zero, which defines the octal values.

  2. The second value specifies permission for the owner.

  3. The third value specifies permission for the owner’s user group.

  4. The fourth value specifies permissions for everybody else.

The second, third, and fourth values can contain the sum of the following 3 values, depending on which permissions are granted.

  • 1 = execute permissions
  • 2 = write permissions
  • 4 = read permissions

Return value

If the function executes successfully, it returns True. Otherwise, it returns False.

Code

If someone wants to provide read and write permission to the owner, the value of the mode will be 0600 where the second value represents the owner and 6 means that 4(read permissions) + 2(write permission are provided.

// read and write permission for owner
chmod("file.txt", 0600);
Output : true
// read and write permission for owner
// read permission for everyone else
chmod("file.txt", 0604);
Output : true
// read, write and execute permission for owner. 
// read and write permission for owner's user group
// read permission for everyone else
chmod("file.txt", 0764);
Output : true
Copyright ©2024 Educative, Inc. All rights reserved