Automatically Rename Files when Uploading

Recently I was working on a project and I was required to rename the uploaded files (mostly images) in a way so that it doesn’t give away any specific information about the content it is associated with. I thought about for few seconds and realized I can easily do that using timestamp as the file name.

This is what I came up with.

add_filter('sanitize_file_name','rename_uploaded_files', 10 );
function rename_uploaded_files($filename) {
   // get the filename
   $info = pathinfo($filename);
   $ext  = empty($info['extension']) ? '' : '.' . $info['extension'];
   $name = basename($filename, $ext);
   // get the current date and time
   $date = date('ymdHis');
   // rename the file and leave the extension as it is
   return $date.$ext;
}

What’s Going on?

Well, on this snippet I am using number of PHP functions to gather information about the uploaded file first. In this case it’s the file name and it’s extension. I am also capturing the current timestamp (including year, month, date, hours, minutes and seconds) to keep the file name to be unique. Because you don’t want multiple file names to be the same as it may overwrite the other files with similar file extensions.

Lastly I am passing that unique name to be the name of the file as soon as the uploading process is done. Yes, it would keep the extension of the file intact. I hope you would find this snippet to be helpful. Let me know if you have any additional question of query on this regard. Thanks.

References: sanitize_file_name, add_filter

Today In History

  •  
  •  

Comment

2 Comments

  1. MartinPublished: 2 years ago

    Hi, this is a great idea !

    I have just a very similar problem.
    Many product pics which have crazy names and I want them to have the productnumber+.ext Additional it would be useful, if a PN-filename alreay exist to extent the file name with -01 or -02 …
    if exist filename then add “-” + “2 digit running number”

    This function can only be used when editing products in the product create or edit window of WooCommerce.

    I am not familiar with the PHP scriptlanguage so I ask you for help

    Thanks
    Martin

    • iftekharPublished: 2 months ago

      Since you mentioned “product number” on you comment, I am assuming you are talking about WooCommerce. It is very much possible but unfortunately it’s beyond the limited scope of my focal point here. I hope you would understand. Thank you.

Leave a Reply

Note: Convet HTML, PHP, JavaScripts from Postable, before posting from comment section.
License: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution. Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.