Skip to content

Instantly share code, notes, and snippets.

@jnicol
Last active January 7, 2019 10:31
Show Gist options
  • Save jnicol/fc1bd3b5fc277ab52c2a to your computer and use it in GitHub Desktop.
Save jnicol/fc1bd3b5fc277ab52c2a to your computer and use it in GitHub Desktop.
Sanitize WordPress filenames on upload
/**
* WordPress allows UTF8 characters such as copyright symbol in filenames but these break in Safari
*
* @see https://wordpress.org/support/topic/uploaded-image-with-accents-in-name-image-dont-show-in-safari-6 for original function
* @see https://core.trac.wordpress.org/ticket/22363 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);
@geagoir
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 (http://www.php.net/manual/en/function.finfo-open.php) 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 )

@eversionsystems
Copy link

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