I’m looking for a way to sanitize the filename of user uploaded attachments.
I thought that wordpress already did it but I faced preblems after an user uploaded an attachment containing a ‘°’ . That way the attachment is not downloadable.
I found out this wp function:
sanitize_file_name($filename)
is there a way to use it inside the
add_attachment
action?
thanks
2 Answers
Following on from question comments.
You can run a filter on sanitize_file_name_chars
and add the degree symbol to the array of invalid chars, but it won’t halt the upload it will simply strip the file extension.
However you can add another filter stop the upload, in a hacky kind of way by additionally hooking on the sanitize_file_name
filter which occurs shortly after the one above, there you see if a file extension is present, if not you know there was a hit in the invalid chars array and you can die()
inside the filter, which will cause the upload process to return a HTTP error(which is better then just silently dieing i guess).
add_filter( 'sanitize_file_name_chars', 'restrict_filename_chars' );
function restrict_filename_chars( $special_chars ) {
$special_chars = array_merge( array( '°' ), $special_chars );
return $special_chars;
}
add_filter( 'sanitize_file_name', 'die_on_no_ext' );
function die_on_no_ext( $filename ) {
global $parts;
if( $parts < 2 )
die(-1);
return $filename;
}
It’s not an ideal solution mind you, and we’ll see what happens with the ticket(i might just be missing something, i’m no expert on file validation).
NOTE: The filter only ensures the actual file name does not contain the degree symbol, not the “post name” (ie. the title of the attachment), you’ll need another filter to deal with sanitizing the attachments title, as this is handled by different functions and filters.