Jump to content

rename() convention for duplicate files


Hani
 Share

Recommended Posts

When calling rename() on a file where the same filename already exists in that pagefiles array, the unique name given to the target file doesn't follow the same convention used when uploading a file using WireUpload.  Is there a reason or was this just a carryover from old version of PW that never got revised?

For example, I have two files in a file field.  The first being called "los_angeles.jpg" and the second called "new_york.jpg".  If I rename "new_york.jpg" (using rename() via the API, of course), the file ends up being called "1_angeles.jpg".

If I were to upload a duplicate of "los_angeles.jpg" to the field normally from within ProcessWire, the file ends up being called "los_angeles-1.jpg" - which is arguably the better result.

To fix this, I tweaked the cleanBasename function in Pagefiles.php in the core (gasp!).   :)

I replaced the following:

while(is_file($path . $basename)) {
        $basename = (++$n) . "_" . preg_replace('/^\d+_/', '', $basename);
}

With:

$p = pathinfo($basename);
while(is_file($path . $basename)) {
        $n++;
        $basename = "$p[filename]-$n.$p[extension]";
}

I don't think there are any negative trickle-down implications for doing this.  Is this something we can get changed in an upcoming build?

Side note: just had to share that by inspecting the code, I learned about the pathinfo() function - which for some reason, I never knew about.  What an amazing little function!  Whenever I have needed to get a file's name and extension before, I'd do something that now seems embarrassingly amateurish (and now laughable):

$filename = 'myfilename.jpg';
$name = substr($filename , 0, strrpos( $filename , '.') );
$ext = end( explode('.',$filename) );

:-X

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...