tags:

views:

25

answers:

2

im really having a tough time trying to upload images using php and mysql, and i really need help!

this is what i want to do in natural language:

1. upload an image
2. check if format is okay(png, jpeg, gif)
3. rename the image file, so theres no ambugity in this format(eg. pic-$userid.gif)

4. upload the pic to the images/folder
5. and delete the old one, or remove the defualt picture when on registration

im trying to look for resources online, but cnt seem to find any!!1 thanks :))

+1  A: 

If you have the patience, I think that looking into these guys code is the best way to go: http://www.verot.net/php_class_upload.htm

Or, why not, just use their class. It will save you from a lot of headache and help you reach your goal faster.

Cheers!

Claudiu
+2  A: 

Here comes some inspiration from a Zend Framework controller of mine! Maybe not production quality yet but it gets the job done.

   $location = $uploadForm->attachment->getFileName();

    $image = new Imagick($location);
    $size = $image->getImageGeometry();
    $image->destroy();

    $attachment = new Collection_Model_Attachment();
    $attachment->memberId = Zend_Auth::getInstance()->getIdentity()->id;
    $attachment->mimeType = $uploadForm->attachment->getMimeType();
    $attachment->name = $uploadForm->attachment->getValue();
    $attachment->width = $size['width'];
    $attachment->height = $size['height'];
    $attachment->sha1sum = sha1_file($location);

    $attachmentMapper = new Collection_Model_AttachmentMapper();
    $attachmentMapper->post($attachment);

    $designAttachment = new Collection_Model_DesignAttachment();
    $designAttachment->designId = $design->id;
    $designAttachment->attachmentId = $attachment->id;

    $designAttachmentMapper = new Collection_Model_DesignAttachmentMapper();
    $designAttachmentMapper->post($designAttachment);

    // Set default photo
    if (!$design->attachmentId)
    {
      $design->attachmentId = $attachment->id;
      $this->_designMapper->put($design);
    }

    $attachmentDir =
      realpath(sprintf(
        '%s/../data/attachments/%02d',
        $_SERVER['DOCUMENT_ROOT'],
        (int)($attachment->id / 100)
      ));
    if (!file_exists($attachmentDir))
      mkdir($attachmentDir);
    $attachmentPath = sprintf('%s/%04d.jpg', $attachmentDir, $attachment->id);

    $success = rename($location, $attachmentPath);
    if (!$success)
    {
      // TODO: error handling
      echo "move_uploaded_file failed: [$location] -> [$attachmentPath]";
      $this->render('notfound');
      return;
    }
divideandconquer.se