错误500在上载文件时从空值创建默认对象

时间:2015-06-07 16:28:05

标签: php yii upload

我正在使用yii和php 5.5.3创建一个上传文件的表单。这是我在控制器中的代码:

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是模型中的额外属性:

array('image_file', 'file', 'types' => 'gif, jpg, jpeg, png', 'maxSize' => 1024 * 1024, 'tooLarge' => 'File upload must not exceed 1MB.'),

以下是观点:

<input type="file" name="settings[store_logo]" class="input-small">

$setting->image_file->saveAs可以成功上传文件,但也会生成

  

错误500从空值创建默认对象

出了什么问题?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我想,$ _FILES ['settings'] ['name']在最后一个Key中有一个空值。 如果您上传文件,它们将按预期处理。 POST数组中的最后一个值导致NULL返回:

// $setting === null
$setting = Setting::model()->find('setting_name=:name', array(':name' => $settingName))

这次通话会抛出500。

$setting->image_file = CUploadedFile::getInstanceByName('settings['.$settingName.']');

这是我的代码版本:

<?php
foreach($_FILES['settings']['name'] as $settingName => $value) {
    $setting = Setting::model()->find('setting_name=:name', array(':name' => $settingName));

    // catch null-return 
    if(!$setting) {
        echo "can't find stuff at<pre>"; print_r($settingName); echo "</pre>";
        continue;
    }

    $setting->image_file = CUploadedFile::getInstanceByName('settings['.$settingName.']');

    if ($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"))
            // dont 0777!       
            mkdir("uploads", 0740, TRUE);

            $setting->image_file->saveAs("uploads/" . $filename.".".$extension, false);
            $setting->setting_value = "uploads/" . $filename.".".$extension;
            $setting->save();
    }
}
?>