sanitize file name

Solutions on MaxInterview for sanitize file name by the best coders in the world

showing results for - "sanitize file name"
Nico
19 Jun 2016
1function filter_filename($filename, $beautify=true) {
2    // sanitize filename
3    $filename = preg_replace(
4        '~
5        [<>:"/\\|?*]|            # file system reserved https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words
6        [\x00-\x1F]|             # control characters http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx
7        [\x7F\xA0\xAD]|          # non-printing characters DEL, NO-BREAK SPACE, SOFT HYPHEN
8        [#\[\]@!$&\'()+,;=]|     # URI reserved https://tools.ietf.org/html/rfc3986#section-2.2
9        [{}^\~`]                 # URL unsafe characters https://www.ietf.org/rfc/rfc1738.txt
10        ~x',
11        '-', $filename);
12    // avoids ".", ".." or ".hiddenFiles"
13    $filename = ltrim($filename, '.-');
14    // optional beautification
15    if ($beautify) $filename = beautify_filename($filename);
16    // maximize filename length to 255 bytes http://serverfault.com/a/9548/44086
17    $ext = pathinfo($filename, PATHINFO_EXTENSION);
18    $filename = mb_strcut(pathinfo($filename, PATHINFO_FILENAME), 0, 255 - ($ext ? strlen($ext) + 1 : 0), mb_detect_encoding($filename)) . ($ext ? '.' . $ext : '');
19    return $filename;
20}
Alessio
30 Sep 2016
1function sanitize_file_name( $filename ) {
2    $filename_raw  = $filename;
3    $special_chars = array( '?', '[', ']', '/', '\\', '=', '<', '>', ':', ';', ',', "'", '"', '&', '$', '#', '*', '(', ')', '|', '~', '`', '!', '{', '}', '%', '+', chr( 0 ) );
4    /**
5     * Filters the list of characters to remove from a filename.
6     *
7     * @since 2.8.0
8     *
9     * @param array  $special_chars Characters to remove.
10     * @param string $filename_raw  Filename as it was passed into sanitize_file_name().
11     */
12    $special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );
13    $filename      = preg_replace( "#\x{00a0}#siu", ' ', $filename );
14    $filename      = str_replace( $special_chars, '', $filename );
15    $filename      = str_replace( array( '%20', '+' ), '-', $filename );
16    $filename      = preg_replace( '/[\r\n\t -]+/', '-', $filename );
17    $filename      = trim( $filename, '.-_' );
18 
19    if ( false === strpos( $filename, '.' ) ) {
20        $mime_types = wp_get_mime_types();
21        $filetype   = wp_check_filetype( 'test.' . $filename, $mime_types );
22        if ( $filetype['ext'] === $filename ) {
23            $filename = 'unnamed-file.' . $filetype['ext'];
24        }
25    }
26 
27    // Split the filename into a base and extension[s]
28    $parts = explode( '.', $filename );
29 
30    // Return if only one extension
31    if ( count( $parts ) <= 2 ) {
32        /**
33         * Filters a sanitized filename string.
34         *
35         * @since 2.8.0
36         *
37         * @param string $filename     Sanitized filename.
38         * @param string $filename_raw The filename prior to sanitization.
39         */
40        return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
41    }
42 
43    // Process multiple extensions
44    $filename  = array_shift( $parts );
45    $extension = array_pop( $parts );
46    $mimes     = get_allowed_mime_types();
47 
48    /*
49     * Loop over any intermediate extensions. Postfix them with a trailing underscore
50     * if they are a 2 - 5 character long alpha string not in the extension whitelist.
51     */
52    foreach ( (array) $parts as $part ) {
53        $filename .= '.' . $part;
54 
55        if ( preg_match( '/^[a-zA-Z]{2,5}\d?$/', $part ) ) {
56            $allowed = false;
57            foreach ( $mimes as $ext_preg => $mime_match ) {
58                $ext_preg = '!^(' . $ext_preg . ')$!i';
59                if ( preg_match( $ext_preg, $part ) ) {
60                    $allowed = true;
61                    break;
62                }
63            }
64            if ( ! $allowed ) {
65                $filename .= '_';
66            }
67        }
68    }
69    $filename .= '.' . $extension;
70    /** This filter is documented in wp-includes/formatting.php */
71    return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
72}
73