How to change file permissions in PHP?

In PHP, you can use the chmod() function to change the permissions of a file. The chmod() function requires two parameters: the file path and the new permissions.

Here's an example that changes the permissions of a file to read and write for the owner, read-only for the group, and no permissions for others:

$file = '/path/to/file.txt'; $permissions = 0640; // Owner: Read + Write, Group: Read, Others: No permissions if (file_exists($file)) { chmod($file, $permissions); echo 'File permissions changed successfully.'; } else { echo 'File not found.'; }

In the above example, the 0640 value represents the octal representation of the permissions. The leading 0 indicates that it is an octal value. The first digit represents the owner's permissions, the second digit represents the group's permissions, and the third digit represents others' permissions. Each digit is a sum of the corresponding permissions.

Here are some common permission numbers:

  • Read: 4
  • Write: 2
  • Execute: 1

So, to set a file as readable and writable for the owner, readable for the group, and not readable, writable, or executable for others, you would use 0640.

Remember to check if the file exists before trying to change its permissions.