CakePHP 1.1 File Upload Plays Rough With PHP 4
Uploading files via CakePHP has been covered a few times on Labs. Based on the feedback, it’s safe to assume bridging the gap between file uploads and PHP can be tricky. Usually Cake is ready to lend a helpful hand. Not this time.
If you're finding that executing this:
<?php echo $html->formTag('/' . $params['url']['url'], 'post', array('enctype' => 'multipart/form-data')); ?>
<?php echo $html->input('Test/title'); ?>
<?php echo $html->file('Test/file'); ?>
<?php echo $html->submit('Save'); ?>
</form>
... returns something like this:
$this->data:Array
(
[Test] => Array
(
[title] => Foo
[file] => 4tmp/phpHGSjDA
)
)
... instead of something like this:
$this->data:Array
(
[Test] => Array
(
[title] => Foo
[file] => Array
(
[name] => aeo.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phppM8tfc
[error] => 0
[size] => 45471
)
)
)
... then you must be as annoyed as I am.
The reason why the file form field is returning the tmp name is because CakePHP expects register_globals is OFF.
Solution One
Turn off register_globals via .htaccess:
#/app/webroot/.htaccess
php_flag register_globals off
Solution Two
Manually write your HTML form fields without using an input array:
-- do this --
<input type="file" name="file" />
-- not this --
<?php echo $html->file('Test/file'); ?> // will output: <input type="file" name="data[Test][test]" />
Solution two is a slight pain in the ass, because now that you’ve eliminated the array within the form input field, you need to do a little extra work in your CakePHP controller. (If there’s a demand, I’ll give some examples.)
Hopefully this’ll clear up Cake’s messhole.

Comments(3)
Where can i see an example of this image uploader in action?
I’d be interested in seeing an example – using CakePHP a lot now.
I’m kind of late getting to this article – I’m only starting to use Cake now for a client that had their site created in it for no apparent reason.
As I’m new to Cake – I know my questions may be dumb, but I’ll try anything.
I have this form that is with the other general pages in views/pages – that is using the Pages_controller. I need to have this form upload images – is there a way to integrate the current Pages_controller page with the images_controller? Or will I need to create a new views folder and have it only work with the images_controller?
I dread this…as I’ve already tried to create a new page that doesn’t use the Pages_controller and failed miserably.
Any help is appreciated.