ZetCode

PHP filetype 函数

最后修改于 2025 年 4 月 3 日

PHP 的 filetype 函数用于确定文件或目录的类型。它返回一个字符串,指示指定文件的类型。

基本定义

filetype 函数返回给定文件的类型。可能的返回值包括 'file'(文件)、'dir'(目录)、'link'(链接)以及其他系统特定的类型。

语法:filetype(string $filename): string|false。该函数在失败时返回 false。它要求文件存在且可访问。

基本 filetype 示例

这展示了 filetype 检查文件类型的最简单用法。

basic_filetype.php
<?php

declare(strict_types=1);

$filename = "example.txt";
$type = filetype($filename);

echo $type; // Outputs: file (if example.txt exists)

这会检查 "example.txt" 的类型。对于常规文件,该函数返回 'file'。在检查文件类型之前,请确保文件存在。

检查目录类型

filetype 可以区分文件和目录。

directory_type.php
<?php

declare(strict_types=1);

$dirname = "docs";
$type = filetype($dirname);

echo $type; // Outputs: dir (if docs is a directory)

这里我们检查 "docs" 是否是一个目录。对于目录,该函数返回 'dir'。与文件一样,适用相同的路径规则。

检查符号链接

在支持符号链接的系统上,该函数可以识别它们。

symlink_type.php
<?php

declare(strict_types=1);

$linkname = "shortcut.lnk";
$type = filetype($linkname);

echo $type; // Outputs: link (if it's a symlink)

这会检查 "shortcut.lnk" 是否为符号链接。对于符号链接,该函数返回 'link'。请注意,行为可能因操作系统而异。

处理不存在的文件

filetype 会为丢失的文件返回 false 并生成警告。

nonexistent_file.php
<?php

declare(strict_types=1);

$filename = "missing.txt";
$type = filetype($filename);

if ($type === false) {
    echo "File not found or inaccessible";
}

这演示了正确的错误处理。当文件可能不存在时,请务必检查返回值。可以考虑先使用 file_exists

检查特殊文件类型

在 Unix 系统上,filetype 可以识别特殊文件类型。

special_types.php
<?php

declare(strict_types=1);

$fifo = "/path/to/named.pipe";
$type = filetype($fifo);

echo $type; // Outputs: fifo (if it's a named pipe)

这会检查 FIFO(命名管道)文件类型。在 Unix 系统上,其他可能的值包括字符设备 ('char') 和块设备 ('block')。

最佳实践

来源

PHP filetype 文档

本教程通过实际示例介绍了 PHP filetype 函数,展示了它在不同文件类型和场景下的用法。

作者

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

列出 所有 PHP 文件系统函数