PHP File Permissions
In this page:
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
file_put_contents("data.txt", "content");
echo substr(sprintf('%o', fileperms("data.txt")), -4);
?>
Login to try C/C++/Java/PHP code in the editor
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
file_put_contents("data.txt", "content");
chmod("data.txt", 0755);
echo substr(sprintf('%o', fileperms("data.txt")), -4);
?>
Login to try C/C++/Java/PHP code in the editor
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
// 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";
?>
Login to try C/C++/Java/PHP code in the editor
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
file_put_contents("data.txt", "content");
var_dump(is_writable("data.txt"));
var_dump(is_readable("data.txt"));
?>
Login to try C/C++/Java/PHP code in the editor
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
file_put_contents("data.txt", "content");
if (!is_writable("data.txt")) {
echo "Cannot write -- check ownership after deployment";
} else {
echo "Write access confirmed";
}
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: