Last active
          February 9, 2019 23:20 
        
      - 
      
- 
        Save yanknudtskov/b704027c8b041b92112b to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or 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
    
  
  
    
  | <?php | |
| /** | |
| * Sanitize upload filenames | |
| * For reference: | |
| * @See http://codex.wordpress.org/Function_Reference/wp_handle_upload | |
| * @See http://php.net/manual/en/function.rename.php | |
| */ | |
| if( !function_exists('vires_artes_sanitize_upload_filenames') ) { | |
| function vires_artes_sanitize_upload_filenames($vals) | |
| { | |
| // Extract the filename and URL Decode it | |
| $name = array_reverse(explode('/', $vals['file'])); | |
| $name = urldecode($name[0]); | |
| // Extract the local path to the uploaded file and remove the current filename | |
| $url = str_replace($name, '', urldecode($vals['file'])); | |
| // Extract the public URL for the uploaded file and remove the current filename | |
| $wurl = str_replace($name, '', urldecode($vals['url'])); | |
| // Sanitize the filename replacing non UTF8 characters | |
| $filetype = wp_check_filetype($name); | |
| $name = str_replace('.'.$filetype['ext'], '', $name); | |
| $name = sanitize_title($name); | |
| $sanitized_file_name = $name . '.' . $filetype['ext']; | |
| // Update the file array with the updated filename in it, precerving the local | |
| // and public url, just updating the filename with the sanitized version. | |
| if(@rename($vals['file'], $url . $sanitized_file_name)) | |
| { | |
| return array( | |
| 'file' => $url . $sanitized_file_name, | |
| 'url' => $wurl . $sanitized_file_name, | |
| 'type' => $vals['type'] | |
| ); | |
| } | |
| // Return the filearray | |
| return $vals; | |
| } | |
| } | |
| add_action('wp_handle_upload', 'vires_artes_sanitize_upload_filenames'); | |
| ?> | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment