Reputation: 315
I'm trying to register 2 uploaded images in the database and upload them to an 'upload' folder. It gives me #400 bad request as in "Unable to verify your data submission." Any ideas on how to fix this? Below's my code.
Controller actionCreate():
public function actionCreate()
{
$model = new PhotoCategories();
if ($model->load(Yii::$app->request->post())) {
$model->image = UploadedFile::getInstance($model, 'image');
$model->thumbnail_image = UploadedFile::getInstance($model, 'thumbnail_image');
if ($model->upload()) {
$model->save();
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Model uses the ImageValidator. Here are the rules() and upload() functions:
public function rules()
{
return [
[['name', 'thumbnail_image', 'image', 'description'], 'required'],
[['description'], 'string'],
[['name'], 'string', 'max' => 256],
[['name'], 'unique'],
[['thumbnail_image'], 'image', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
[['image'], 'image', 'skipOnEmpty' => false, 'extensions' => 'png, jpg']
];
}
public function upload() {
if ($this->validate()) {
$this->image->saveAs('uploads/' . $this->image->baseName . '.' . $this->image->extension);
$this->thumbnail_image->saveAs('uploads/' . $this->image->baseName . '.' . $this->image->extension);
return true;
} else {
return false;
}
}
The View file for the form is as it follows:
<div class="photo-categories-form">
<?php $form = ActiveForm::begin(); ?>
<input type="hidden" name="<?= Yii::$app->request->csrfParam; ?>" value="<?= Yii::$app->request->csrfToken; ?>" />
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'thumbnail_image')->fileInput() ?>
<?= $form->field($model, 'image')->fileInput() ?>
<?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Even though I have also written the hidden input back there, it still throws me the error.
Upvotes: 0
Views: 300
Reputation: 2258
Yii won't allow CSRF is an abbreviation for cross-site request forgery default. so if you want disable CSRF checking then add below code in you controller
public $enableCsrfValidation = false;
for more information see this. http://www.yiiframework.com/doc-2.0/guide-security-best-practices.html#avoiding-csrf
Warning: Disabling CSRF will allow any site to send POST requests to your site. It is important to implement extra validation such as checking an IP address or a secret token in this case.
or
you need set as input value inside the form.
<input type="hidden" name="<?= Yii::$app->request->csrfParam; ?>" value="<?= Yii::$app->request->csrfToken; ?>" />
Note:- this is better way to handle "Unable to verify your data submission." errors.
Upvotes: 0