PHP file upload adventure…

โ€”

by

in

For the project I am working on for Client A I have had to tackle file uploading via the browser in PHP. I had purchased a Dreamweaver extension a while back to handle this sort of thing, but it turns out to be inadequate for my needs  in this case. I certainly have gotten the value from it, but it just isn’t flexible enough any more. So here is a little code snippet and some links that helped me out.

I am not sure what I am going to do with the result, I may release it publicly or I might make it commercial. Anyway, here is a snippet that might help you out if you are looking for a way to make a unique filename in PHP.

Assuming that:

  • $iterations is an integer telling you mow many attempts you want to prevent endless loops in nightmare situations
  • $name is a filename root like “upload”
  • $ext is a filename extension like “jpg”
  • $path is a path to a accessible directory like “/tmp”

Then you can do this:

ed. note: I altered this code for posting, so check it for errors before you use it in anything important. It’s at your own risk, if it wipes your data or turns you into a [[wp:zombie]] don’t blame me.

function make_unique_name( $name, $ext, $path, $iterations ){
    for( $i = 0; $i < $iterations; $i++ ) {
        $testname = uniqid( $name . “_” );
        $testfullname = $testname . “.” . $ext;
        if( !file_exists( $path . “/” . $testfullname ) ){
            return $testfullname;
        }
    }
    return “”;
}

These links were particularly helpful: