函数文档

path_is_absolute()

💡 云策文档标注

概述

path_is_absolute() 函数用于测试给定的文件系统路径是否为绝对路径。它支持多种路径格式,包括 Unix 风格(如 /foo/bar)和 Windows 风格(如 c:windows),并处理流包装器。

关键要点

  • 函数接受一个字符串参数 $path,返回布尔值:true 表示绝对路径,false 表示非绝对路径。
  • 检查逻辑包括:流包装器路径、realpath() 匹配、路径长度和起始字符、Windows 驱动器路径、以及以 / 或 开头的路径。
  • 在 Windows 平台上,使用 wp_normalize_path() 处理后的路径可能导致返回 false,需注意此行为差异。

代码示例

function path_is_absolute( $path ) {
	if ( wp_is_stream( $path ) && ( is_dir( $path ) || is_file( $path ) ) ) {
		return true;
	}
	if ( realpath( $path ) === $path ) {
		return true;
	}
	if ( strlen( $path ) === 0 || '.' === $path[0] ) {
		return false;
	}
	if ( preg_match( '#^[a-zA-Z]:\#', $path ) ) {
		return true;
	}
	return ( '/' === $path[0] || '\' === $path[0] );
}

注意事项

在 Windows 平台上,path_is_absolute() 对经过 wp_normalize_path() 标准化的路径可能返回 false,这可能导致跨平台兼容性问题,建议测试时考虑此差异。


📄 原文内容

Tests if a given filesystem path is absolute.

Description

For example, ‘/foo/bar’, or ‘c:windows’.

Parameters

$pathstringrequired
File path.

Return

bool True if path is absolute, false is not absolute.

Source

function path_is_absolute( $path ) {
	/*
	 * Check to see if the path is a stream and check to see if its an actual
	 * path or file as realpath() does not support stream wrappers.
	 */
	if ( wp_is_stream( $path ) && ( is_dir( $path ) || is_file( $path ) ) ) {
		return true;
	}

	/*
	 * This is definitive if true but fails if $path does not exist or contains
	 * a symbolic link.
	 */
	if ( realpath( $path ) === $path ) {
		return true;
	}

	if ( strlen( $path ) === 0 || '.' === $path[0] ) {
		return false;
	}

	// Windows allows absolute paths like this.
	if ( preg_match( '#^[a-zA-Z]:\\#', $path ) ) {
		return true;
	}

	// A path starting with / or  is absolute; anything else is relative.
	return ( '/' === $path[0] || '\' === $path[0] );
}

Changelog

Version Description
2.5.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    This note was added while current WordPress version is 5.7

    Please be aware that path_is_absolute() returns false on a Windows platform when used on a normalized (abs) path (trac #48289).

    var_dump( path_is_absolute( __FILE__ ) );
    var_dump( path_is_absolute( wp_normalize_path( __FILE__ ) ) );

    *nix Result:

    bool(true)
    bool(true)

    Windows Result:

    bool(true)
    bool(false)