← Back to Chapters

PHP Chmod & Fileperms Functions

? PHP Chmod & Fileperms Functions

? Quick Overview

In PHP, file and directory permissions can be modified and inspected using chmod() and fileperms(). These functions are critical for controlling access, improving security, and managing server-side file operations.

? Key Concepts

  • chmod() changes file or directory permissions.
  • fileperms() retrieves existing permissions.
  • Permissions are handled using octal values like 0644 or 0755.

? Syntax & Theory

  • fileperms(string $filename) returns permission data as an integer.
  • chmod(string $filename, int $permissions) updates permission values.
  • decoct() converts permissions into readable octal format.

? Code Example

? View Code Example
// Define the file path
$file = "example.txt";

// Get current permissions
$perms = fileperms($file);
echo "Current Permissions: " . decoct($perms) . "<br>";

// Change permissions to 0644
if (chmod($file,0644)) {
echo "Permissions updated successfully<br>";
} else {
echo "Permission update failed<br>";
}

// Verify updated permissions
$perms = fileperms($file);
echo "Updated Permissions: " . decoct($perms);

? Live Output & Explanation

The script first reads existing permissions, applies new permission values using chmod(), and confirms the change using fileperms(). Permissions are displayed in octal form for clarity.

? Interactive Concept

Think of permissions as a lock system: the owner holds full control, the group has limited access, and others receive restricted visibility depending on the octal value applied.

? Use Cases

  • Securing uploaded files.
  • Granting execution rights to scripts.
  • Restricting unauthorized file access.
  • Managing shared hosting environments.

✅ Tips & Best Practices

  • Always verify permissions after using chmod().
  • Use the least-permission principle for security.
  • Avoid overly permissive values like 0777.

? Try It Yourself

  • Create a directory and modify its permissions.
  • Display permissions for multiple files dynamically.
  • Test permission changes with different user roles.