I want to validate the file name of the files to be uploaded from the Media Library.

CASE study: I want to restrict the file name containing '%', '. .', '/' etc..from uploading to the media library.

I can restrict the file types but not able to restrict as per the file names.

Suggest me any wordpress filter or any procedure to accomplish the solution.


The filter is sanitize_file_name. You get the $filename as parameter.

Sample code:

add_filter( 'sanitize_file_name', 'wpse_77892_filter_filename' );

function wpse_77892_filter_filename( $filename )
    return str_replace( '%', '-', $filename );

See my plugin Germanix URL for an extended example.

  • Hello toscho, I already thought of using sanitize_file_name but when we sanitize the file it doesn't restrict the file. Instead the file name was rewritten in a sanitized format. e.g. file name 'best picture/new.jpg' may become 'best-picture-new.jpg' after sanitization. But what I want is not to allow the file to be uploaded. My solution is more near to the function like validiate_file in wordpress. – wpCallCenter Jan 1 '13 at 16:43
  • But you get the name after the upload. Whatever you do, you cannot prevent to upload based on the filename (file type is a different story). So it would be very frustrating for the user to waste time with an upload and then getting no usable result. Just change the name on the server side. – fuxia Jan 1 '13 at 16:47
  • Ok toscho, thanks for your prompt reply. I have been going through your plugin code. Now can you just give me an idea how your plugin will sanitize this particular file name i.e. 'malic.html%00.jpg' – wpCallCenter Jan 1 '13 at 17:00
  • It will remove the % and leave the rest intact. – fuxia Jan 1 '13 at 17:02
  • what about the dot '.' after 'malic' – wpCallCenter Jan 1 '13 at 17:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.