Last active
January 7, 2019 10:31
-
-
Save jnicol/fc1bd3b5fc277ab52c2a to your computer and use it in GitHub Desktop.
Sanitize WordPress filenames on upload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); |
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
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 )