关于WordPress附件比较有用的内置方法及防注入的清洗方法

作者: 站长 上传时间: 浏览: N/A 下载: N/A 格式: N/A 评分: N/A

两个方法
wp_check_filetype
php的basename(path,suffix)也有用

$path = "/testweb/home.php";

//显示带有文件扩展名的文件名
echo basename($path);

//显示不带有文件扩展名的文件名
echo basename($path,".php");

重点讲下面的(外网摘抄)


/**
删除上传文件中文名中的特殊符号及空格
作用:
文件: ~My WordPress Upload~.jpg
默认WordPress: My-WordPress-Upload.jpg
自定义解决方案: my-wordpress-upload.jpg

文件: ÐÕçument full of $$$.pdf
默认WordPress: ÐÕçument-full-of-.pdf
自定义解决方案: document-full-of.pdf

文件: Really%20Ugly%20Filename-_-That_-_Is_Too Common.....png
默认WordPress: Really-Ugly-Filename-_-That_-_Is_Too-Common....png
自定义解决方案: really-ugly-filename-that-is -too-common.png
*/
function wpartisan_sanitize_file_name( $filename ) {
$sanitized_filename = remove_accents( $filename ); // Convert to ASCII
// Standard replacements
$invalid = array(
' ' => '-',
'%20' => '-',
'_' => '-',
);
$sanitized_filename = str_replace( array_keys( $invalid ), array_values( $invalid ), $sanitized_filename );
$sanitized_filename = preg_replace('/[^A-Za-z0-9-\. ]/', '', $sanitized_filename); // Remove all non-alphanumeric except .
$sanitized_filename = preg_replace('/\.(?=.*\.)/', '', $sanitized_filename); // Remove all but last .
$sanitized_filename = preg_replace('/-+/', '-', $sanitized_filename); // Replace any more than one - in a row
$sanitized_filename = str_replace('-.', '.', $sanitized_filename); // Remove last - if at the end
$sanitized_filename = strtolower( $sanitized_filename ); // Lowercase

return $sanitized_filename;
}
add_filter( 'sanitize_file_name', 'wpartisan_sanitize_file_name', 10, 1 );

另一个优秀的代码,通过自定义方法将指定路径的文件加入到WordPress媒体库中


$wp_filetype['type'],
'post_parent' => $parent_post_id,
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $parent_post_id );
if (!is_wp_error($attachment_id)) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
}
}

Leave a Comment