PHP File Permissions and Ownership
In this tutorial, we will learn about file permissions and ownership in PHP with the help of examples. Managing file permissions and ownership is essential for securing file operations in PHP.
Incorrect permissions or ownership settings can lead to unauthorized access to sensitive files and create serious security vulnerabilities. PHP provides several built-in functions and techniques to check, control and modify file permissions and ownership, ensuring your applications remain safe and reliable.
What are File Permissions in PHP?
File permissions determine who can access a file and what actions they can perform on it. In Linux/Unix-based operating systems, file permissions are divided into three categories for the users:
- File owner – The user who owns the file.
- Group – Users who belong the file’s group.
- Others – All other users on the system.
Each category has three types of file permissions:
- Read (r) → This permission allows the user to view or read the contents of a file.
- Write (w) → This permission allows the user to modify or edit the contents of a file.
- Execute (x) → This permission allows the user to run the file as a program or script.
For example:
-rw-r--r-- 1 user group 1234 Jan 10 10:00 myfile.txt
Here:
- Owner → read & write (rw-)
- Group → read-only (r–)
- Others → read-only (r–)
Understanding File Permissions in Numbers (Octal Notation)
In PHP, file permissions are often represented as octal numbers:
- 4 → Read
- 2 → Write
- 1 → Execute
These values are added together to set permissions:
- 7 = Read + Write + Execute (4+2+1)
- 6 = Read + Write (4+2)
- 5 = Read + Execute (4+1)
- 4 = Read only
File Permission Representation in Octal and Symbolic Notation
Octal Value | Symbolic Notation | Meaning |
---|---|---|
600 | -rw——- | Owner can read/write. Group and others have no permissions. |
644 | -rw-r–r– | Owner can read/write. Group and others can only read. |
666 | -rw-rw-rw- | Everyone (owner, group, others) can read and write. |
700 | -rwx—— | Owner can read/write/execute. Group and others have no permissions. |
755 | -rwxr-xr-x | Owner can read/write/execute. Group and others can read and execute. |
777 | -rwxrwxrwx | Everyone (owner, group, others) has full permissions (read/write/exec). |
To manipulate these permissions, you need to understand both PHP functions and how these octal numbers correspond to different permission settings.
PHP Functions for File Permissions
PHP provides several functions to check and modify file permissions:
- fileperms()
- chmod()
- is_readable()
- is_writable()
- is_executable()
Let’s understand each function one by one with the help of important examples.
PHP fileperms() Function
The fileperms() function in PHP is a built-in function used to get the current permissions of a file.
Basic Syntax
fileperms(string $filename): int|false
Parameters
The fileperms() function accepts one parameter:
- $filename → This parameter represents the name of the file whose permissions you want to check.
Return Value
- The fileperms() function returns an integer representing the permissions of the file on success.
- This function returns false if the file does not exist or cannot be accessed.
To make the output human-readable, you can use the decoct() function to convert this integer into an octal number.
Example 1: Get File Permissions
<?php
$file = "myfile.txt";
// Get file permissions with fileperms() function.
$permissions = fileperms($file);
// Display permissions in octal format using decoct() function.
echo "File permissions: " . substr(decoct($permissions), -4);
?>
Output: File permissions: 0666
In this example,
- The fileperms($file) function returns an integer for the permissions of the specified file.
- The decoct($permissions) function converts this integer number to octal.
- substr(…, -4) ensures we get the last four digits, which is the standard Unix permission format.
Example 2: Human-readable File Permissions
<?php
$file = "myfile.txt";
// Get file permissions.
$permissions = fileperms($file);
// Convert the decimal number to octal format.
$octalPerms = substr(decoct($permissions), -4);
// Split octal digits into owner, group, others.
$owner = (int)$octalPerms[0];
$group = (int)$octalPerms[1];
$others = (int)$octalPerms[2];
// Create a function to convert a single digit to rwx format.
function getPermissionString($digit) {
$str = '';
$str .= ($digit & 4) ? 'r' : '-';
$str .= ($digit & 2) ? 'w' : '-';
$str .= ($digit & 1) ? 'x' : '-';
return $str;
}
echo "File Permissions: " . getPermissionString($owner)
. getPermissionString($group)
. getPermissionString($others);
?>
Output: File Permissions: ---rw-rw-
In this example, the getPermissionString() function converts each digit to rwx format.
How to Change File Permissions in PHP?
PHP provides a built-in chmod() function, which changes the permissions of a file. This function allows you to set the read, write, and execute permissions for the owner, group, and others.
Basic Syntax
bool chmod(string $filename, int $mode)
Parameters
The chmod() function takes two parameters:
- $filename → This parameter represents the name of the file whose permissions you want to change.
- $mode → This parameter indicates the new permissions, which must be specified in octal format, e.g., 0644, 0755.
Return Value
- Returns true on success.
- Returns false on failure.
Example 1: Change File Permissions
<?php
$file = "myfile.txt";
// Change file permissions to 755.
if (chmod($file, 0755)) {
echo "Permissions changed successfully!";
} else {
echo "Failed to change permissions.";
}
?>
Output: Permissions changed successfully!
In this example, the octal value 0755 sets:
- Owner → read, write, execute
- Group → read, execute
- Others → read, execute
Example 2: Change File Permissions for File Upload
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
// Set uploaded file permissions to the octal value 644.
chmod($target_file, 0644);
echo "File uploaded and permissions set!";
} else {
echo "File upload failed!";
}
?>
Output: File uploaded and permissions set!
Explanation:
- In this example, we have set the upload directory, which defines where you want to store the uploaded file. The trailing slash (/) allows you to concatenate the filename later. Note that the uploads/ directory must exist and be writable.
- Then, we built the destination file path. $_FILES[“file”][“name”] is the name of original file provided by the client (the <input name=”file”> in your HTML form).
- The basename() function strips directory components from the filename. Then, we append it to the uploads directory.
- After that, we moved the uploaded temporary file to the target location. When a file is uploaded by the users, PHP places it in a temporary location given by $_FILES[“file”][“tmp_name”].
- The move_uploaded_file() function moves that temporary file to the $target_file path only if the source is a valid uploaded file via HTTP POST. It returns true on success, and false on failure.
- If the move succeeded, the chmod() function sets the permissions of the newly moved file to octal 0644.
- 0 = octal literal indicator
- 6 (owner) = read + write
- 4 (group) = read
- 4 (others) = read
How to Check if a File is Readable in PHP?
PHP provides a built-in is_readable() function that checks whether a file or directory is readable, meaning the PHP script has permission to access its contents.
Basic Syntax
bool is_readable(string $filename)
The is_readable() function accepts one parameter $filename, which specifies the path to the file or directory. This function returns true if the file is readable, otherwise returns false.
Example: Permission to Read Contents
<?php
$file = "myfile.txt";
if (is_readable($file)) {
echo "The file '$file' is readable.";
} else {
echo "The file '$file' is NOT readable.";
}
?>
Output: The file 'myfile.txt' is readable.
How to Check if a File is Writable in PHP?
The is_writable() function is a built-in function that checks whether a file or directory is writable, meaning the PHP script has permission to modify or write to it.
Basic Syntax
bool is_writable(string $filename)
The is_writable() function accepts one parameter named $filename, which specifies the path to the file or directory. This function returns true if the file or directory is writable, otherwise returns false.
Example: Permission to Write Contents
<?php
$file = "myfile.txt";
if (is_writable($file)) {
echo "The file '$file' is writable.";
} else {
echo "The file '$file' is NOT writable.";
}
?>
Output: The file 'myfile.txt' is writable.
Check Whether a File is Executable in PHP
To check if a file is executable, you can use the is_executable() function. This function checks whether the specified file has execute permissions, meaning it can be run as a program or script.
Basic Syntax
bool is_executable(string $filename)
The is_executable() function takes one parameter named $filename that specifies the path to the file. This function returns true if the file is executable, otherwise returns false.
Example: File Execution Permission
<?php
$file = "myfile.txt";
if (is_executable($file)) {
echo "The file '$file' is executable.";
} else {
echo "The file '$file' is not executable.";
}
?>
Output: The file 'myfile.txt' is not executable.
Example: Check All at Once
<?php
$file = "myfile.txt";
echo "Checking file permissions for '$file':";
echo is_readable($file) ? "Readable \n" : "Not Readable \n";
echo is_writable($file) ? "Writable \n" : "Not Writable \n";
echo is_executable($file) ? "Executable \n" : "Not Executable \n";
?>
Output: Checking file permissions for 'myfile.txt': Readable Writable Not Executable
File Ownership in PHP
File ownership is important in a multi-user environment. PHP offers a built-in chown() function to change the ownership of the file. This function requires the path to the file and name of the new owner. Here’s a syntax:
bool chown(string $filename, string $username)
This function returns true if the ownership of a file is changed, otherwise returns false.
Example: Change File Ownership
<?php
$file = "myfile.txt";
// Attempt to change the file owner to 'www-data'.
if (chown($file, "www-data")) {
echo "File ownership changed successfully!";
} else {
echo "Failed to change file ownership.";
}
?>
Output: Failed to change file ownership.
In this example code, we try to change the ownership of myfile.txt to the user www-data (common web server user in Linux). If successful, it prints a success message. Otherwise, it shows a failure message.
Note: The chown() function only works on POSIX (Unix/Linux) systems, not on Windows. If PHP does not have permission to change ownership, the function will fail.
Best Practices for File Permissions in PHP
When considering file permissions in PHP, several best practices help maintain security:
- Avoid 777 permissions because this allows anyone to read, write, and execute your files, creating a huge security risk.
- Use 644 for files because owner can read/write, and others can only read.
- Use 755 for directories. Owner can read/write/execute, and others can only read/execute.
- Restrict uploading of the files. Always try to validate and sanitize uploaded files before adjusting permissions.
- Regularly audit file and directory permissions to check file system to ensure sensitive files (like config.php) are not exposed.
Conclusion
In this article, you learned everything about PHP file permissions from basics to advanced levels. I hope that you will have understood all topics covered and practiced examples.