Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Sanitize WordPress filenames on upload
* WordPress allows UTF8 characters such as copyright symbol in filenames but these break in Safari
* @see for original function
* @see for progress on fixing this bug
* #wordpress
function sanitize_filename_on_upload($filename) {
$ext = end(explode('.',$filename));
$sanitized = preg_replace('/[^a-zA-Z0-9-_.]/','', substr($filename, 0, -(strlen($ext)+1)));
$sanitized = str_replace('.','-', $sanitized);
return strtolower($sanitized.'.'.$ext);
add_filter('sanitize_file_name', 'sanitize_filename_on_upload', 10);
Copy link

geagoir commented Nov 3, 2018

A note of security: Don't ever trust $_FILES["image"]["type"]. It takes whatever is sent from the browser, so don't trust this for the image type. I recommend using finfo_open ( to verify the MIME type of a file. It will parse the MAGIC in the file and return it's type...this can be trusted (you can also use the "file" program on Unix, but I would refrain from ever making a System call with your PHP code...that's just asking for problems). ( from php manual )

Copy link

eversionsystems commented Dec 7, 2018

I was getting the following error, Only variables should be passed by reference in <file_name>.php
This can be resolved bu splitting the end function code into two lines.

$ext = explode('.', $filename);
$ext = end($ext);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment