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

  

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

1
2
3
4
5
6
7
$path = "/testweb/home.php";

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
删除上传文件中文名中的特殊符号及空格
作用:
文件: ~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媒体库中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
$file = '/path/to/file.png';
$filename = basename($file);

$upload_file = wp_upload_bits($filename, null, file_get_contents($file));
if (!$upload_file['error']) {
    $wp_filetype = wp_check_filetype($filename, null );
    $attachment = array(
        'post_mime_type' => $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 );
    }
}

账号密码登录