← Back to PHP Course | Chapter 9: File Handling | Lesson 5 of 8

PHP File Permissions

Checking Permissions

Every file and directory on a Unix-like server has permission bits controlling who can read, write, or execute it, typically shown as three digits like 755, one each for the owner, group, and everyone else.

Example: Checking Permissions

php
<?php
file_put_contents("data.txt", "content");
echo substr(sprintf('%o', fileperms("data.txt")), -4);
?>

Changing Permissions

chmod($path, 0755) changes a file or directory's permissions from PHP, though the web server's own user account needs sufficient permission on the parent directory to make that change in the first place.

Example: Changing Permissions

php
<?php
file_put_contents("data.txt", "content");
chmod("data.txt", 0755);
echo substr(sprintf('%o', fileperms("data.txt")), -4);
?>

Changing File Ownership

A common and dangerous shortcut is setting permissions to 777 (full access for everyone) to make an upload directory 'just work' — this is a serious security risk since it lets any user on a shared server modify those files.

Example: Changing File Ownership

php
<?php
// Setting 0777 gives everyone full access -- a common but risky shortcut
file_put_contents("data.txt", "content");
chmod("data.txt", 0644); // safer than 0777
echo "Permissions set to a safer default";
?>

Checking Existence and Types

is_writable() and is_readable() let you check permissions from PHP before attempting a file operation, so your script can fail gracefully with a clear error instead of a raw fwrite() warning.

Example: Checking Existence and Types

php
<?php
file_put_contents("data.txt", "content");
var_dump(is_writable("data.txt"));
var_dump(is_readable("data.txt"));
?>

Safe Permissions Handling

File ownership and permissions are frequently the real cause behind 'my upload script suddenly stopped working' bugs after a server migration or deployment, since the new environment's user accounts may differ from the old one's.

Example: Safe Permissions Handling

php
<?php
file_put_contents("data.txt", "content");
if (!is_writable("data.txt")) {
    echo "Cannot write -- check ownership after deployment";
} else {
    echo "Write access confirmed";
}
?>
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.