函数文档

get_temp_dir()

💡 云策文档标注

概述

get_temp_dir() 函数用于确定一个可写的临时文件目录,优先使用系统或 PHP 配置,最后回退到默认路径。开发者可通过 WP_TEMP_DIR 常量覆盖此行为。

关键要点

  • 函数返回一个可写的临时目录字符串,使用 trailingslashit() 确保路径以斜杠结尾。
  • 目录选择优先级:首先检查 WP_TEMP_DIR 常量定义,然后依次尝试 sys_get_temp_dir()、upload_tmp_dir、WP_CONTENT_DIR,最后默认使用 /tmp/。
  • sys_get_temp_dir() 会尊重 TMPDIR 环境变量,确保跨平台兼容性。
  • 如果所有候选目录都不可写,可以通过在 wp-config.php 中定义 WP_TEMP_DIR 常量来强制指定临时目录。

代码示例

function get_temp_dir() {
    static $temp = '';
    if ( defined( 'WP_TEMP_DIR' ) ) {
        return trailingslashit( WP_TEMP_DIR );
    }

    if ( $temp ) {
        return trailingslashit( $temp );
    }

    if ( function_exists( 'sys_get_temp_dir' ) ) {
        $temp = sys_get_temp_dir();
        if ( @is_dir( $temp ) && wp_is_writable( $temp ) ) {
            return trailingslashit( $temp );
        }
    }

    $temp = ini_get( 'upload_tmp_dir' );
    if ( @is_dir( $temp ) && wp_is_writable( $temp ) ) {
        return trailingslashit( $temp );
    }

    $temp = WP_CONTENT_DIR . '/';
    if ( is_dir( $temp ) && wp_is_writable( $temp ) ) {
        return $temp;
    }

    return '/tmp/';
}

注意事项

  • 函数使用静态变量 $temp 缓存结果以提高性能,避免重复检查目录。
  • 在检查目录可写性时,使用了 @ 操作符抑制可能的错误,确保函数在权限问题下仍能优雅回退。
  • 此函数自 WordPress 2.5.0 版本引入,是核心文件处理功能的基础组件。

📄 原文内容

Determines a writable directory for temporary files.

Description

Function’s preference is the return value of sys_get_temp_dir(), followed by the upload_tmp_dir value from php.ini, followed by WP_CONTENT_DIR, before finally defaulting to /tmp/.

Note that sys_get_temp_dir() honors the TMPDIR environment variable.

In the event that this function does not find a writable location, it may be overridden by the WP_TEMP_DIR constant in your wp-config.php file.

Return

string Writable temporary directory.

Source

function get_temp_dir() {
	static $temp = '';
	if ( defined( 'WP_TEMP_DIR' ) ) {
		return trailingslashit( WP_TEMP_DIR );
	}

	if ( $temp ) {
		return trailingslashit( $temp );
	}

	if ( function_exists( 'sys_get_temp_dir' ) ) {
		$temp = sys_get_temp_dir();
		if ( @is_dir( $temp ) && wp_is_writable( $temp ) ) {
			return trailingslashit( $temp );
		}
	}

	$temp = ini_get( 'upload_tmp_dir' );
	if ( @is_dir( $temp ) && wp_is_writable( $temp ) ) {
		return trailingslashit( $temp );
	}

	$temp = WP_CONTENT_DIR . '/';
	if ( is_dir( $temp ) && wp_is_writable( $temp ) ) {
		return $temp;
	}

	return '/tmp/';
}

Changelog

Version Description
2.5.0 Introduced.