. */ declare(strict_types=1); namespace App\Helpers; /** * This class provides functions to sanitize filenames. */ class FilenameSanatizer { /** * Converts a given filename to a version, which is guaranteed to be safe to use on all filesystems. * This function is adapted from https://stackoverflow.com/a/42058764/21879970 * @param string $filename * @return string */ public static function sanitizeFilename(string $filename): string { $filename = preg_replace( '~ [<>:"/\\\|?*]| # file system reserved https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words [\x00-\x1F]| # control characters http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx [\x7F\xA0\xAD]| # non-printing characters DEL, NO-BREAK SPACE, SOFT HYPHEN [#\[\]@!$&\'()+,;=]| # URI reserved https://www.rfc-editor.org/rfc/rfc3986#section-2.2 [{}^\~`] # URL unsafe characters https://www.ietf.org/rfc/rfc1738.txt ~x', '-', $filename); // avoids ".", ".." or ".hiddenFiles" $filename = ltrim($filename, '.-'); //Limit filename length to 255 bytes $ext = pathinfo($filename, PATHINFO_EXTENSION); return mb_strcut(pathinfo($filename, PATHINFO_FILENAME), 0, 255 - ($ext ? strlen($ext) + 1 : 0), mb_detect_encoding($filename)) . ($ext ? '.' . $ext : ''); } }