ZetCode

PHP fileowner 函数

最后修改于 2025 年 4 月 3 日

PHP fileowner 函数检索指定文件的所有者。它返回文件所有者的用户 ID,该 ID 可以解析为用户名。

基本定义

fileowner 函数返回文件所有者的用户 ID。它接受一个参数:文件的路径,以字符串形式表示。

语法:fileowner(string $filename): int|false。成功时返回用户 ID,失败时返回 false。在 Unix 系统上结果是数字。

fileowner 基本示例

这展示了 fileowner 获取文件所有者 ID 的最简单用法。

basic_fileowner.php
<?php

declare(strict_types=1);

$filename = "/var/www/html/index.php";
$ownerId = fileowner($filename);

if ($ownerId !== false) {
    echo "File owner ID: " . $ownerId;
} else {
    echo "Could not get file owner";
}

这检索文件所有者的数字用户 ID。可以使用 posix_getpwuid 在类 Unix 系统上将 ID 解析为用户名。

获取所有者用户名

此示例演示了如何将所有者 ID 转换为可读的用户名。

fileowner_username.php
<?php

declare(strict_types=1);

$filename = "/etc/passwd";
$ownerId = fileowner($filename);

if ($ownerId !== false) {
    $ownerInfo = posix_getpwuid($ownerId);
    echo "File owner: " . $ownerInfo['name'];
} else {
    echo "Could not get file owner";
}

在这里,我们使用 posix_getpwuid 将数字 ID 转换为用户名。请注意,此函数仅在具有 POSIX 扩展的类 Unix 系统上可用。

检查文件所有权

此示例检查当前用户是否拥有特定文件。

check_ownership.php
<?php

declare(strict_types=1);

$filename = "test.txt";
$ownerId = fileowner($filename);
$currentUserId = posix_geteuid();

if ($ownerId !== false) {
    if ($ownerId === $currentUserId) {
        echo "You own this file";
    } else {
        echo "You don't own this file";
    }
} else {
    echo "Could not check file ownership";
}

我们将文件所有者 ID 与当前有效用户 ID 进行比较。这对于在执行敏感文件操作之前进行权限检查很有用。

错误处理

这演示了使用 fileowner 时的正确错误处理。

error_handling.php
<?php

declare(strict_types=1);

$filename = "nonexistent.txt";
$ownerId = @fileowner($filename);

if ($ownerId === false) {
    $error = error_get_last();
    echo "Error: " . $error['message'];
} else {
    echo "File owner ID: " . $ownerId;
}

我们使用 @ 运算符来抑制警告,并显式检查返回值。error_get_last 函数检索最后发生的错误。

Windows 兼容性

这显示了 fileowner 在 Windows 系统上的行为。

windows_compat.php
<?php

declare(strict_types=1);

$filename = "C:\\Windows\\win.ini";
$ownerId = fileowner($filename);

if ($ownerId !== false) {
    echo "File owner ID: " . $ownerId;
} else {
    echo "Could not get file owner (Windows may return 0)";
}

在 Windows 上,fileowner 通常返回 0 (SYSTEM) 或可能失败。Windows 具有与类 Unix 操作系统不同的权限系统。

最佳实践

来源

PHP fileowner 文档

本教程涵盖了 PHP fileowner 函数,并提供了实际示例,展示了它在不同场景和操作系统中的用法。

作者

我叫 Jan Bodnar,是一位热情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出 所有 PHP 文件系统函数