Hi all,

i am working with Uploadify ( a neat little file uploader ) and had a tough time finding an image re-sizer to work with it. I finally found one that works quite well but it encodes the file name using md5 encoding.

I am not sure where and how to grab the md5 encoded filename and query an INSERT into sql with it.

Here is the code:

if (!empty($_FILES)) {

        class Image {
            
            var $uploaddir;
            var $quality = 80;
            var $ext;
            var $dst_r;
            var $img_r;
            var $img_w;
            var $img_h;
            var $output;
            var $data;
            var $datathumb;
            
            function setFile($src = null) {
                $this->ext = strtoupper(pathinfo($src, PATHINFO_EXTENSION));
                if(is_file($src) && ($this->ext == "JPG" OR $this->ext == "JPEG")) {
                    $this->img_r = ImageCreateFromJPEG($src);
                } elseif(is_file($src) && $this->ext == "PNG") {
                    $this->img_r = ImageCreateFromPNG($src);      
                } elseif(is_file($src) && $this->ext == "GIF") {
                    $this->img_r = ImageCreateFromGIF($src);
                }
                $this->img_w = imagesx($this->img_r);
                $this->img_h = imagesy($this->img_r);
            }
            
            function resize($w = 100) {
                $h =  $this->img_h / ($this->img_w / $w);
                $this->dst_r = ImageCreateTrueColor($w, $h);
                imagecopyresampled($this->dst_r, $this->img_r, 0, 0, 0, 0, $w, $h, $this->img_w, $this->img_h);
                $this->img_r = $this->dst_r;
                $this->img_h = $h;
                $this->img_w = $w;
            }
            
            function createFile($output_filename = null) {
                if($this->ext == "JPG" OR $this->ext == "JPEG") {
                    imageJPEG($this->dst_r, $this->uploaddir.$output_filename.'.'.$this->ext, $this->quality);
                } elseif($this->ext == "PNG") {
                    imagePNG($this->dst_r, $this->uploaddir.$output_filename.'.'.$this->ext);
                } elseif($this->ext == "GIF") {
                    imageGIF($this->dst_r, $this->uploaddir.$output_filename.'.'.$this->ext);
                }
                $this->output = $this->uploaddir.$output_filename.'.'.$this->ext;
            }
            
            function setUploadDir($dirname) {
                $this->uploaddir = $dirname;
            }
            
            function flush() {
        $tempFile = $_FILES['Filedata']['tmp_name'];
        $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
        $targetFile =  str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
                
                imagedestroy($this->dst_r);
                unlink($targetFile);
                //imagedestroy($this->img_r);
                
            }
            
        }
        
        $tempFile = $_FILES['Filedata']['tmp_name'];
        $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
        $targetFile =  str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
        
        mkdir(str_replace('//','/',$targetPath), 0755, true);
        
        move_uploaded_file ($tempFile, $targetFile);
        
        $image = new Image();
        $image->setFile($targetFile);
        $image->setUploadDir($targetPath);
        $image->resize(640);
        $image->createFile(md5($tempFile));
        $image->resize(100);
        $image->createFile("small".md5($tempFile));
        $image->flush();
    }

Also, why encode an image filename? Is this to avoid any malicious uploads to the server?

Any help on this would be greatly appreciated.

Dani AI

Generated

Quick summary and next steps based on the thread: was getting names like large_.JPG because the variable holding the original filename was never set; correctly suggested returning the generated filename from the image-save routine so it can be captured for the DB. Below are practical additions that were not covered yet — safe filename generation, basic validation, and a concise example of inserting the final name into MySQL securely.

Generate a safe, unique filename (sanitise the original name, add randomness, keep the extension):

$original = basename($_FILES['uploaded_field']['name']);
$safe = preg_replace('/[^A-Za-z0-9._-]/', '', $original);
$unique = bin2hex(random_bytes(8)) . '_' . $safe;
$ext = strtolower(pathinfo($original, PATHINFO_EXTENSION));
$finalName = $unique . '.' . $ext;

Use that returned finalName (or whatever your save method returns) for both the resized files and the DB insert so names always match what’s on disk.

Insert the filename safely with a prepared statement (PDO example):

$pdo = new PDO('mysql:host=localhost;dbname=yourdb','user','pass',[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
$stmt = $pdo->prepare('INSERT INTO images (filename, directory, mime, size) VALUES (?, ?, ?, ?)');
$stmt->execute([$finalName, 'uploads/images', $mime, $size]);

Validation and security checklist (do these before saving/inserting):

  • Use getimagesize() or finfo_file() to confirm actual image MIME type.
  • Reject unexpected extensions or oversized files.
  • Use basename() to avoid path traversal and store only the basename (not server full path) in DB.
  • Prefer cryptographically strong randomness (e.g., random_bytes) over MD5 for uniqueness. MD5’ing a temp path does not prevent malicious uploads — validation and safe storage do.
  • Place uploads outside executable web roots or block execution via server config, and check move_uploaded_file() return values and permissions.

These steps make the filename reliable for INSERTs and improve overall upload security and traceability.

Recommended Answers

All 4 Replies

There is no real good reason to md5 your filename. That would not avoid any malicious uploads, so, if you wanted you could remove the md5 calls. Also you are calling resize and then createFile with an md5'd 'tempname'. I would make the call something like $large_file = $image->createFile("large_".$targetFile);
How to grab the filename:
change your function createFile($output_filename = null) {
At the very end of it have this line:
return $output_filename;
and when you call $image->createFile('filename'); change it to be like the call above
$large_file = $image->createFile('large_'.$filename);
$resize(100);
$small_file = $image->createFile('small_'.$filename);
You should then have your two new filenames saved in variables $large_file and $small_file if you need to do an insert.

Hi ddymacek and a big thanks for this missing piece to my puzzle. The images are getting uploaded nicely except for one small issue.

In this line: $large_file = $image->createFile('large_'.$filename);
and this line: $small_file = $image->createFile('small_'.$filename);

the filenames are not coming through and all that gets uploaded is large_.JPG and small_.JPG

I tried ('large_'.$output_filename); but no worky.

any ideas would be huge at this point.

Thanks again for your help.

yes, '$filename' was never being set... was just an example:
you already have this code:
$targetFile = str_replace('//','/',$targetPath) . $_FILES;
but $targetFile is the full path on your server, you only need to use
the $_FILES for your filename so:
$filename = $_FILES;
probably right before or after your $targetFile line of code.

Then you can pass your $filename variable anywhere you want, and it will be consistently named with the 'source' file that was originally uploaded and not resized by the code.

Of course....You are a good man or good woman, whichever the case may be. Big thanks to you...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.