chmod / chown
chmod(string $filename, int $permissions): bool — chown(string $filename, string|int $user): bool
Changes a file's permission bits and owner: chmod sets rwx bits with an octal mode (the leading 0 is mandatory), chown changes the owner (only the superuser may give a file away); PHP's own chmod clears that path's stat cache — clearstatcache is needed for changes made OUTSIDE the process.
C C23
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
int main(void) {
char path[] = "/tmp/chm_c_XXXXXX";
int fd = mkstemp(path);
close(fd);
chmod(path, 0644);
struct stat st;
stat(path, &st);
printf("%o\n", (unsigned)st.st_mode & 0777); // 644
chmod(path, 0755);
stat(path, &st); // C has no userland stat cache: fresh result every time
printf("%o\n", (unsigned)st.st_mode & 0777); // 755
// chown to self: the owner may set ownership to themselves
int rc = chown(path, getuid(), getgid());
printf("%d\n", rc); // 0 = success
unlink(path);
return 0;
}
644 755 0
C++ C++26
#include <cstdio>
#include <cstdlib>
#include <sys/stat.h>
#include <unistd.h>
int main() {
char path[] = "/tmp/chm_cpp_XXXXXX";
int fd = mkstemp(path);
close(fd);
chmod(path, 0644);
struct stat st;
stat(path, &st);
std::printf("%o\n", static_cast<unsigned>(st.st_mode) & 0777); // 644
chmod(path, 0755);
stat(path, &st); // no userland stat cache in C++: fresh result
std::printf("%o\n", static_cast<unsigned>(st.st_mode) & 0777); // 755
// chown to self: the owner may set ownership to themselves
int rc = chown(path, getuid(), getgid());
std::printf("%d\n", rc); // 0 = success
unlink(path);
return 0;
}
644 755 0
C# v11.0.100
using System.IO;
var path = Path.GetTempFileName();
File.SetUnixFileMode(path, // 0644
UnixFileMode.UserRead | UnixFileMode.UserWrite |
UnixFileMode.GroupRead | UnixFileMode.OtherRead);
Console.WriteLine(Convert.ToString((int)File.GetUnixFileMode(path), 8)); // 644
File.SetUnixFileMode(path, // 0755
UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute |
UnixFileMode.GroupRead | UnixFileMode.GroupExecute |
UnixFileMode.OtherRead | UnixFileMode.OtherExecute);
Console.WriteLine(Convert.ToString((int)File.GetUnixFileMode(path), 8)); // 755
// no chown API in .NET: Mono.Unix or P/Invoke on libc (see notes)
File.Delete(path);
644 755
Go v1.27.4
package main
import (
"fmt"
"os"
)
func main() {
path := fmt.Sprintf("%s/chm_go_%d", os.TempDir(), os.Getpid())
os.WriteFile(path, []byte("x"), 0644)
os.Chmod(path, 0644)
fi, _ := os.Stat(path)
fmt.Printf("%o\n", fi.Mode().Perm()) // 644
os.Chmod(path, 0755)
fi, _ = os.Stat(path)
fmt.Printf("%o\n", fi.Mode().Perm()) // 755
// os.Chown to self: the owner may set ownership to themselves
err := os.Chown(path, os.Getuid(), os.Getgid())
fmt.Println(err == nil)
os.Remove(path)
}
644 755 true
Java v27.0.1
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermissions;
public class Main {
public static void main(String[] args) throws Exception {
Path path = Files.createTempFile("chm", ".tmp");
Files.setPosixFilePermissions(path, PosixFilePermissions.fromString("rw-r--r--"));
System.out.println(PosixFilePermissions.toString(Files.getPosixFilePermissions(path))); // rw-r--r--
Files.setPosixFilePermissions(path, PosixFilePermissions.fromString("rwxr-xr-x"));
System.out.println(PosixFilePermissions.toString(Files.getPosixFilePermissions(path))); // rwxr-xr-x
// chown to the current user: PosixFileAttributeView.setOwner
var view = Files.getFileAttributeView(path, PosixFileAttributeView.class);
var me = path.getFileSystem().getUserPrincipalLookupService()
.lookupPrincipalByName(System.getProperty("user.name"));
view.setOwner(me); // owner "changing" to themselves is allowed
System.out.println(view.getOwner().equals(me));
Files.delete(path);
}
}
rw-r--r-- rwxr-xr-x true
JavaScript v26.13.1
const fs = require("fs");
const os = require("os");
const dir = fs.mkdtempSync(os.tmpdir() + "/chm_");
const path = `${dir}/demo.dat`;
fs.writeFileSync(path, "x"); // create the file first
fs.chmodSync(path, 0o644);
console.log((fs.statSync(path).mode & 0o777).toString(8)); // 644
fs.chmodSync(path, 0o755);
console.log((fs.statSync(path).mode & 0o777).toString(8)); // 755
// chown to self; POSIX-only in Node (no-op concept on Windows)
if (process.getuid) {
fs.chownSync(path, process.getuid(), process.getgid());
console.log("chown ok");
} else {
console.log("chown skipped");
}
fs.unlinkSync(path);
fs.rmSync(dir, { recursive: true, force: true });
644 755 chown ok
PHP v8.6.0
$file = tempnam(sys_get_temp_dir(), 'chm_'); // tempnam creates with mode 0600
chmod($file, 0600);
fileperms($file); // prime PHP's per-path stat cache with 0600
$pid = pcntl_fork();
if ($pid === 0) { chmod($file, 0644); exit(0); } // a CHILD process changes the mode
pcntl_waitpid($pid, $status);
// the cached result comes back STALE: PHP cannot see other processes' changes
echo sprintf('%o', fileperms($file) & 0777), "\n"; // 600 (stale!)
clearstatcache();
echo sprintf('%o', fileperms($file) & 0777), "\n"; // 644 (fresh)
chmod($file, 0755); // PHP's own chmod clears the cache automatically
echo sprintf('%o', fileperms($file) & 0777), "\n"; // 755
var_dump(chown($file, fileowner($file))); // owner "changing" to themselves: true
unlink($file);
600 644 755 bool(true)
Python v3.15.2
import os
import tempfile
fd, path = tempfile.mkstemp(prefix="chm_")
os.close(fd)
os.chmod(path, 0o644)
print(oct(os.stat(path).st_mode & 0o777)[2:]) # 644
os.chmod(path, 0o755)
print(oct(os.stat(path).st_mode & 0o777)[2:]) # 755
if hasattr(os, "getuid"):
os.chown(path, os.getuid(), os.getgid()) # owner to self is allowed
print("chown ok")
else:
print("chown skipped") # Windows: no uid concept
os.unlink(path)
644 755 chown ok
Rust v1.99.1
use std::fs;
use std::os::unix::fs::PermissionsExt; // std's unix-only permission extension
fn main() {
let path = std::env::temp_dir().join(format!("chm_rs_{}", std::process::id()));
fs::write(&path, b"x").unwrap();
fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
println!("{:o}", fs::metadata(&path).unwrap().permissions().mode() & 0o777); // 644
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
println!("{:o}", fs::metadata(&path).unwrap().permissions().mode() & 0o777); // 755
// std has no chown: libc::chown or the nix crate (see notes)
fs::remove_file(&path).unwrap();
}
644 755
TypeScript v26.13.1
import * as fs from "fs";
import * as os from "os";
const dir = fs.mkdtempSync(`${os.tmpdir()}/chm_`);
const path = `${dir}/demo.dat`;
fs.writeFileSync(path, "x"); // create the file first
fs.chmodSync(path, 0o644);
console.log((fs.statSync(path).mode & 0o777).toString(8)); // 644
fs.chmodSync(path, 0o755);
console.log((fs.statSync(path).mode & 0o777).toString(8)); // 755
// chown to self; POSIX-only in Node (no-op concept on Windows)
if (process.getuid) {
fs.chownSync(path, process.getuid(), process.getgid());
console.log("chown ok");
} else {
console.log("chown skipped");
}
fs.unlinkSync(path);
fs.rmSync(dir, { recursive: true, force: true });
644 755 chown ok
Language differences
PHP: permissions is not automatically read as octal — write 0755, not 755 (decimal 755 = octal 1363, yielding nonsense bits); stat-cache teaching point: only changes made outside the process go stale (the example forks a child via pcntl_fork to show 600 stale -> 644 after clearstatcache), while PHP's own chmod/touch family clears the cache as a side effect; chown only lets the superuser give a file to someone else — setting it back to yourself always succeeds (asserted in the example); on Windows chmod can only flip the read-only bit and chown fails silently on regular files.
C/C++: chmod(2)/chown(2) share prototypes and have no userland stat cache — every stat is fresh (the exact contrast to PHP's cached teaching point); an owner chowning to themselves needs no privilege.
C#: File.SetUnixFileMode/GetUnixFileMode (.NET 7+, Unix only) — UnixFileMode is a User-prefixed flags enum without file-type bits; the .NET base library has no chown API (use Mono.Unix or P/Invoke into libc).
Go: os.Chmod + os.FileMode.Perm() to read back; os.Chown takes numeric uid/gid (os.Getuid()), not user names.
Java: NIO Files.setPosixFilePermissions (POSIX filesystems only; throws UnsupportedOperationException on Windows); chown goes through PosixFileAttributeView.setOwner(UserPrincipal).
JavaScript: fs.chmodSync/statSync().mode & 0o777; fs.chownSync is a no-op on Windows — guard on process.getuid as the example does.
Python: os.chmod/os.stat().st_mode; os.chown is POSIX-only — the code guards with hasattr(os, "getuid").
Rust: std has no chown — use libc::chown or the nix crate; permissions go through std::os::unix::fs::PermissionsExt (from_mode/mode()).
TypeScript: same as JS.
Shared pitfall: the missing octal 0 prefix is the classic beginner accident in every language.