validate_file_to_edit()
云策文档标注
概述
validate_file_to_edit() 函数用于验证用户请求编辑的文件是否被允许编辑,确保文件操作的安全性。如果文件不被允许,函数会终止执行并显示错误消息。
关键要点
- 函数接受两个参数:$file(必需,用户尝试编辑的文件)和 $allowed_files(可选,允许编辑的文件数组,默认为空数组)。
- 通过调用 validate_file() 函数进行验证,返回验证码;验证码为 0 表示成功,返回文件名;否则根据验证码调用 wp_die() 终止执行。
- 验证失败时,会显示“Sorry, that file cannot be edited.”等错误消息,防止未授权文件访问。
代码示例
function validate_file_to_edit( $file, $allowed_files = array() ) {
$code = validate_file( $file, $allowed_files );
if ( ! $code ) {
return $file;
}
switch ( $code ) {
case 1:
wp_die( __( 'Sorry, that file cannot be edited.' ) );
// case 2 :
// wp_die( __('Sorry, cannot call files with their real path.' ));
case 3:
wp_die( __( 'Sorry, that file cannot be edited.' ) );
}
}注意事项
- 函数在验证失败时会直接终止 WordPress 执行,使用 wp_die() 显示错误页面,开发者需确保在调用前进行适当的错误处理或权限检查。
- 参数 $allowed_files 数组用于定义允许编辑的文件列表,$file 必须精确匹配数组中的条目,否则验证会失败。
- 此函数自 WordPress 1.5.0 版本引入,是核心文件编辑安全机制的一部分,常用于主题或插件编辑器等场景。
原文内容
Makes sure that the file that was requested to be edited is allowed to be edited.
Description
Function will die if you are not allowed to edit the file.
Parameters
$filestringrequired-
File the user is attempting to edit.
$allowed_filesstring[]optional-
Array of allowed files to edit.
$filemust match an entry exactly.Default:
array()
Source
function validate_file_to_edit( $file, $allowed_files = array() ) {
$code = validate_file( $file, $allowed_files );
if ( ! $code ) {
return $file;
}
switch ( $code ) {
case 1:
wp_die( __( 'Sorry, that file cannot be edited.' ) );
// case 2 :
// wp_die( __('Sorry, cannot call files with their real path.' ));
case 3:
wp_die( __( 'Sorry, that file cannot be edited.' ) );
}
}
Changelog
| Version | Description |
|---|---|
| 1.5.0 | Introduced. |