I'm creating a form to upload a file, using yii and php 5.5.3. Here is my code in the controller:
foreach($_FILES['settings']['name'] as $settingName => $value) {
$setting = Setting::model()->find('setting_name=:name', array(':name' => $settingName));
$setting->image_file = CUploadedFile::getInstanceByName('settings['.$settingName.']');
if (!empty($setting->image_file)) {
$extension = "jpg";
$filename = "";
if (($pos = strrpos($setting->image_file, '.')) !== FALSE) {
$extension = substr($setting->image_file, $pos + 1);
$filename = substr($setting->image_file, 0, $pos)."_".strtotime("now");
}
if (!file_exists("uploads") and !is_dir("uploads"))
mkdir("uploads", 0777, TRUE);
$setting->image_file->saveAs("uploads/" . $filename.".".$extension, false);
$setting->setting_value = "uploads/" . $filename.".".$extension;
$setting->save();
}
}
image_file
is an extra attribute in model:
array('image_file', 'file', 'types' => 'gif, jpg, jpeg, png', 'maxSize' => 1024 * 1024, 'tooLarge' => 'File upload must not exceed 1MB.'),
and here is the view:
<input type="file" name="settings[store_logo]" class="input-small">
$setting->image_file->saveAs
can successfully upload the file, but it also generates
Error 500 Creating default object from empty value
What went wrong? Any help would be much appreciated.
i guess, the $_FILES['settings']['name'] has a empty value in the last Key. If you upload a File(s), they will be process as expected. The last value in your POST-array cause a NULL-return here:
and this call throws the 500.
This is my Version of your code: