@snisnik esta bueno.. Pero es bastante incomodo acostumbrarse

Uploading images using CakePHP

First of all, I need to say that I’m not even close to being a good CakePHP developer. Not even a PHP developer. I Don’t even like it very much, but well, somethings we have to do things we don’t like. Having that said, this is a little snippet I use on my CakePHP controllers to upload images, save them, and add the URL into the database table. In the view, I use a file input.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function __upload($file_array){
    $file = new File($file_array['tmp_name']);
    $file_base = pathinfo($file_array['name']);;
    $ext = strtolower($file_base['extension']);
    if ($ext != 'jpg' && $ext != 'jpeg' && $ext != 'gif' && $ext != 'png') {
        $this->Session->setFlash('You may only upload image files.');
        $this->render();
    } else {
        $data = $file->read();
        $file->close();
        $full_path = '/upload_images/'.$file_array['name'];
        $file = new File(WWW_ROOT.$full_path, true);
        $file->write($data);
        $file->close();
         return $full_path;
    }
    return 'Ouch!';
}

If you copy and paste this example, the images are uploaded to wwwroot/upload_images/

This snippet it’s not just for uploading images, it can be used with any file type

How do I use it?

1
2
3
4
5
6
7
8
9
10
11
12
function admin_add() {
    if (!empty($this->data)) {
            $this->data['News']['image'] = $this->__upload($this->data['News']['image']);
            $this->News->create();
        if ($this->News->save($this->data)) {
            $this->Session->setFlash(__('The news has been saved', true));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The news could not be saved. Please, try again.', true));
        }
    }
}

And in the view…

1
2
3
4
5
6
7
8
9
echo $this->Form->input('title');
echo $this->Form->input('title');
echo $this->Form->input('subtitle');
echo $this->Form->input('body');
if($this->data['News']['image'] != '')
    echo $this->Html->image($this->data['News']['image'],array('height' => '50'));
echo $this->Form->file('image');
echo $this->Form->checkbox('active');
echo $this->Form->input('publish_date');

We you see in lines 5 y 6 is just a simple way to show the image if it is actually something uploaded or not show anything if it’s not

And at last. During the edit, cakephp sends the data object copying the information form the form. When we use the file input to upload the image, that image is not pre-loaded in the form, so when we click send, cake understands that we removed the image from the post. So, here is a little trick to avoid that

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function admin_edit($id = null) {
    if (!$id && empty($this->data)) {
        $this->Session->setFlash(__('Invalid news', true));
        $this->redirect(array('action' => 'index'));
    }
    if (!empty($this->data)) {
        if(!empty($this->data['News']['image']['name']))
            $this->data['News']['image'] = $this->__upload($this->data['News']['image']);
        else unset($this->data['News']['image']);
        if ($this->News->save($this->data)) {
            $this->Session->setFlash(__('The news has been saved', true));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The news could not be saved. Please, try again.', true));
        }
    }
    if (empty($this->data)) {
        $this->data = $this->News->read(null, $id);
    }
}

Well, this is my way to upload images, it is probably awfull and not the best one but it does what it should. Probably a good idea is to move this as a component, but I’m to lazy :P

6 Comments »

1 Feb 2011 @ 5:14 pm

Your tut gave me a reference guide, a good one indeed. I had implemented this before on a customer’s project. But after sometime, I discovered it’s not working properly anymore. It’s been about six months now.

And having been away for other projects, I can say I’ve forgotten some steps involed. Any, coming across your tuorial really helped refreshen my memory in the right direction.

Thanks and keep it up.

1 Feb 2011 @ 7:30 pm

Im glad it was usefull for you :) . It can be better in soooo many ways, but it gets the thing done so i’m keeping it :P


m16u31

26 May 2011 @ 4:07 am

Hola supongo que hablas español, me salvaste de no presentar un proyecto a tiempo, gracias de verdad.
me fue super util el articulo.

this article was very usefull 4 me , thank you very much.

20 Dec 2011 @ 10:41 am

Hmm… I just started with cakePHP and I don’t really understand anything that’s going on, so that’s a major problem to start with.
But I have no idea where I have to put all that code? Could you please help me?

20 Dec 2011 @ 10:43 am

Hmm… I just started with cakePHP and I don’t really understand anything that’s going on, so that’s a major problem to start with.
But I have no idea where I have to put all that code? Could you please help me?

(Yes I can spell my name)


Cinnamon

21 May 2012 @ 3:38 am

thanks a lots!

RSS feed for comments on this post. TrackBack URL


Leave a comment