I have a problem when uploading a file with a .php file extension. The problem is becoming blank pages and unsuccessfully redirected to index (files uploaded but the page is blank)
This does not happen when I use other extension files (jpeg, jpg, txt, doc, docx etc).
Ps. I am using Oracle as database and using yii2 UploadedFile
Here my model
public static function tableName()
{
return 'JOB';
}
public function rules()
{
return [
[['JOBNAME', 'CLASS', 'ACTION', 'SCHEDULE', 'STATUS'], 'required'],
[['ID', 'STATUS'], 'integer'],
[['JOBNAME'], 'string', 'max' => 30],
[['FILECOMMAND'], 'file', 'skipOnEmpty' => false, 'extensions' => 'jpeg, php, txt'],
[['CLASS', 'ACTION', 'SCHEDULE'], 'string', 'max' => 100],
[['ID'], 'unique'],
];
}
}
Here my controller
public function actionCreate()
{
$scheduleList = yii::$app->params['cronparam'];
$model = new JOB();
if (yii::$app->request->post()) {
$state = true;
$data = yii::$app->request->post()['JOB'];
try {
$transaction = Yii::$app->db->beginTransaction();
$model->JOBNAME = $data['JOBNAME'];
$model->CLASS = $data['CLASS'];
$model->ACTION = $data['ACTION'];
$model->SCHEDULE = $data['SCHEDULE'];
$model->STATUS = $data['STATUS'];
$model->files = UploadedFile::getInstance($model, 'FILECOMMAND');
$model->FILECOMMAND = $model->files;
$model->files->saveAs(yii::getAlias('#app') . yii::$app->params['pathJobFile'] . $model->files->baseName . '.' . $model->files->extension, false);
if (!$model->save()) {
$ErrorMessage = $model->getErrorMessage($model->getErrors());
throw new Exception($ErrorMessage);
}
$message = "Success insert Job " . ucwords($model->JOBNAME);
$transaction->commit();
} catch (Exception $e) {
$message = $e->getMessage();
$state = false;
$transaction->rollBack();
}
if ($state) {
Yii::$app->session->setFlash('SuccessJob', $message);
$this->redirect('index');
} else {
Yii::$app->session->setFlash('ErrorJob', $message);
$this->render('create', ['scheduleList' => $scheduleList, 'model' => $model]);
}
} else {
return $this->render('create', ['scheduleList' => $scheduleList, 'model' => $model]);
}
}
Add return statements here:
if ($state) {
Yii::$app->session->setFlash('SuccessJob', $message);
return $this->redirect('index'); //here
} else {
Yii::$app->session->setFlash('ErrorJob', $message);
return $this->render('create', ['scheduleList' => $scheduleList, 'model' => $model]); //and here
}
Related
When I am trying to insert new column using codeigniter version 4 with dbforge.
I got an error in Production mode:
Whoops!We seem to have hit a snag. Please try again later...
public function addLanguage()
{
$language = preg_replace('/[^a-zA-Z0-9_]/', '', $this->request->getPost('language',FILTER_SANITIZE_STRING));
$language = strtolower($language);
if (!empty($language)) {
if (!$this->db->fieldExists($language, "language")) {
$this->dbforge->addColumn("language", [
$language => [
'type' => 'TEXT'
]
]);
$this->session->setFlashdata('message', 'Language added successfully');
return redirect()->route('backend/setting/language');
}
} else {
$this->session->setFlashdata('exception', display('please_try_again'));
}
return redirect()->route('backend/setting/language');
}
What am I doing wrong in this code? Any potential help would be greatly appreciated!
Development mode error image below:
You can use this code
public function addLanguage()
{
$dbforge = \Config\Database::forge();
$language = preg_replace('/[^a-zA-Z0-9_]/', '', $this->request->getPost('language',FILTER_SANITIZE_STRING));
$language = strtolower($language);
if (!empty($language)) {
if (!$this->db->fieldExists($language, "language")) {
$dbforge->addColumn("language", [
$language => [
'type' => 'TEXT'
]
]);
$this->session->setFlashdata('message', 'Language added successfully');
return redirect()->route('backend/setting/language');
}
} else {
$this->session->setFlashdata('exception', display('please_try_again'));
}
return redirect()->route('backend/setting/language');
}
I have a Yii2 ActiveForm with two form field that accepts file input.
<?= $form->field($model, 'mainImage')->fileInput() ?>
<?= $form->field($model, 'productImage[]')->fileInput() ?>
In the controller i have:
public function actionCreate()
{
$model = new Product();
$model->supplier_id = Yii::$app->user->identity->id;
$imageArray = ['mainImage','productImage'];
$mainImageIndex = 1;
if ($model->load(Yii::$app->request->post())) {
$model->mainImage = UploadedFile::getInstance($model, 'mainImage');
$model->images = $model->singleImageUpload();
//UploadedFile::reset();
// var_dump($model->mainImage);
// exit();
$model->productImage = UploadedFile::getInstances($model, 'productImage');
$images = $model->multipleImageUpload();
$imageCount = count($images);
if ($model->validate() && $model->save(false)) {
for ($i=0; $i < $imageCount; $i++) {
$imageModel = new ProductImage();
$imageModel->product_id = $model->id;
$imageModel->image = $images[$i];
$imageModel->save();
}
return $this->redirect(['view', 'id' => $model->id]);
}
}
return $this->render('create', [
'model' => $model,
]);
}
In the Model class, I have these validations rules:
[['mainImage','productImage'], 'safe'],
[['mainImage','productImage'], 'file','skipOnEmpty' => true, 'extensions' => 'jpeg, jpg, png','checkExtensionByMimeType'=>false, 'maxFiles'=>10],
Every time i submit the form I get an error of mainImage field stating Please upload a file. There is no error for productImage
What could be the possible fix for this?
Edit
Images for mainImageand productImage are successfully uploaded though the validation error persists on for the mainImage
The problem was validation in the model class.
I had marked them as safe
[['mainImage','productImage'], 'safe'],
I commented out this validation and it worked
If you want to upload multiple files then you needed to change your view
<?= $form->field($model, 'mainImage')->fileInput() ?>
<?= $form->field($model, 'productImage[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>
And your rule in model says that you have been trying to upload multiple image for attributes productImage[] and mainImage. But view says that attribute mainImage used for single file so change the rule.
[['mainImage'], 'file', 'skipOnEmpty' => true, 'extensions' => 'jpeg, jpg, png'],
[['productImage'], 'file','skipOnEmpty' => true, 'extensions' => 'jpeg, jpg, png','checkExtensionByMimeType'=>false, 'maxFiles'=>10],
In controller,
$model->productImage = UploadedFile::getInstances($model, 'productImage');
$model->mainImage = UploadedFile::getInstance($model, 'mainImage');
if ($model->multipleImageUpload()) {
// file is uploaded successfully
return;
}
In your model,
public function multipleImageUpload()
{
if ($this->validate()) {
foreach ($this->imageFiles as $file) {
$file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);
}
return true;
} else {
return false;
}
}
For more reference please go through this link: https://www.yiiframework.com/doc/guide/2.0/en/input-file-upload
So I've set a CRUD to upload a file to the server's root, in a folder called 'uploads'.
Now, the file is properly saved in the particular folder and the database entry appears to be alright - but the images don't display in the CRUD's 'index' and 'view' actions. Any thoughts on this one?
Create:
public function actionCreate()
{
$model = new PhotoGalleryCategories();
if ($model->load(Yii::$app->request->post())) {
$model->image = UploadedFile::getInstance($model, 'image');
if (Yii::$app->ImageUploadComponent->upload($model)) {
Yii::$app->session->setFlash('success', 'Image uploaded. Category added.');
return $this->redirect(['view', 'id' => $model->id]);
} else {
Yii::$app->session->setFlash('error', 'Proccess could not be successfully completed.');
return $this->render('create', [
'model' => $model
]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
ImageUploadComponent file:
<?php
namespace app\components;
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
class ImageUploadComponent extends Component {
public function upload($model) {
if ($model->image) {
$imageBasePath = dirname(Yii::$app->basePath, 1) . '\uploads\\';
$imageData = 'img' . $model->image->baseName . '.' . $model->image->extension;
$time = time();
$model->image->saveAs($imageBasePath . $time . $imageData);
$model->image = $imageBasePath . $time . $imageData;
if ($model->save(false)) {
return true;
} else {
return false;
}
}
}
}
And the index file for the views:
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel app\modules\admin\models\PhotoGalleryCategoriesSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Photo Gallery Categories';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="photo-gallery-categories-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Photo Gallery Categories', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'name',
'image' => [
'attribute' => 'image',
'value' => 'image',
'format' => ['image', ['class' => 'col-md-6']]
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
Edit: In the dev tools, I can see the correct source for the image. What's more, I can access it by copy-pasting the address in the browser. (the first rows are images taken from the internet through their address, they are not saved locally.)
if image upload in folder
you check below code in gridview with own path:
[
'attribute' => 'image',
'format' => 'html',
'value' => function($data) {
if (empty($data['image'])) {
$img = 'default.jpg';
} else {
$img = $data['image'];
}
if (file_exists(\Yii::$app->basePath . \Yii::$app->params['path']['product'] . $img)) {
if (file_exists(\Yii::$app->basePath . \Yii::$app->params['path']['product'] . "t-" . $img)) {
$path = \Yii::$app->params['path']['webproduct'] . "t-" . $img;
} else {
$path = \Yii::$app->params['path']['webproduct'] . $img;
}
} else {
if (file_exists(\Yii::$app->basePath . \Yii::$app->params['path']['product'] . "t-default.jpg")) {
$path = \Yii::$app->params['path']['webproduct'] . "t-default.jpg";
} else {
$path = \Yii::$app->params['path']['webproduct'] . "default.jpg";
}
}
return Html::img($path, ['width' => '100px', 'height' => '100px']);
},
],
in params.php
\Yii::$app->params['path']['webproduct']:
'product' => '/web/uploads/product/',
'webproduct' => '/uploads/product/',
notice: i use basic template.
I found this anomaly: while inspecting the image sources, I found out that Yii prepended the baseUrl to the image source, even though it displayed only the correct bit. So I manually assigned the path that goes into the database - this way the images show properly.
This is the upload function after the changes. To test it for the whole backend, I made it a component, and it works flawlessly.
public function upload($model) {
/**
* If the $model->image field is not empty, proceed to uploading.
*/
if ($model->image) {
/**
* Assign current time.
*/
$time = time();
/**
* Create the basePath for the image to be uploaded at #root/uploads.
* Create the image name.
* Create the database model.
*/
$imageBasePath = dirname(Yii::$app->basePath, 1) . '\uploads\\';
$imageData = 'img' . $model->image->baseName . '.' . $model->image->extension;
$imageDatabaseEntryPath = '../../../uploads/';
$modelImageDatabaseEntry = $imageDatabaseEntryPath . $time . $imageData;
$model->image->saveAs($imageBasePath . $time . $imageData);
$model->image = $modelImageDatabaseEntry;
/**
* If the model can be saved into the database, return true; else return false.
* Further handling will be done in the controller.
*/
if ($model->save(false)) {
return true;
} else {
return false;
}
}
}
}
My Code related is the following:
Model Rules
[['documentTypeId', 'itemId', 'name', 'document'], 'required'],
[['document'], 'file', 'skipOnEmpty' => false, 'extensions' => ['png', 'jpg', 'doc', 'pdf'], 'checkExtensionByMimeType'=>false],
Model method
public function upload($file)
{
if ($this->validate()) {
$userFolder = Yii::getAlias("#app")."/uploads/".$this->item->userId;
if(BaseFileHelper::createDirectory($userFolder) !== false) {
$fileName = uniqid(rand(), false) . '.' . $this->document->extension;
$file->saveAs($userFolder.'/' . $fileName);
$this->document = $file->name;
return true;
} else {
return false;
}
} else {
return false;
}
}
Controller
$model = new ItemDocument();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$file = UploadedFile::getInstance($model, 'document');
if($model->upload($file) !== false) {
$model->save();
}
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
This is giving me a validation error: "Document can not be blank". If I set "Document" field as not required and submit form I get "Please upload a file."
I am uploading this through a form with some other fields.
Any ideas?
I have found the error it was the model->validate() on controller. When i do:
$model->load(Yii::$app->request->post())
File content is not loaded to the "document" field. Yii generates a hidden field which is empty. So I need first to do this:
$file = UploadedFile::getInstance($model, 'document');
So now my controller looks like this:
$model = new ItemDocument();
if ($model->load(Yii::$app->request->post())) {
$model->document = UploadedFile::getInstance($model, 'document');
if($model->validate()) {
if ($model->upload() !== false) {
$model->save();
}
return $this->redirect(['view', 'id' => $model->id]);
}
}
return $this->render('create', [
'model' => $model,
]);
And I removed the validation inside upload method on model. Hope it helps someone.
My controller :
public function actionCreate()
{
$model = new CreateBookings();
if ($model->load(Yii::$app->request->post()))
{
$imageName = $model->primary_name;
$model->file = UploadedFile::getInstance($model, 'file');
$model->file->saveAs('uploads/'.$imageName.'.'.$model->file->extension);
$model->id_image = 'uploads/'.$imageName.'.'.$model->file->extension;
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else
{
return $this->render('create', [
'model' => $model,
]);
}
}
Getting this error on submitting my form, dont know what's wrong with it..
Tried with $model->save(false); ..but not working as well
Try with getPrimaryKey() method:
public function actionCreate()
{
$model = new CreateBookings();
if ($model->load(Yii::$app->request->post()))
{
$imageName = $model->primary_name;
$model->file = UploadedFile::getInstance($model, 'file');
$model->file->saveAs('uploads/'.$imageName.'.'.$model->file->extension);
$model->id_image = 'uploads/'.$imageName.'.'.$model->file->extension;
if($model->save())
{
$lastInsertID = $model->getPrimaryKey();
return $this->redirect(['view', 'id' => $lastInsertID]);
}
else
{
// print_r($model->getErrors()); => check whether any validation errors are there
}
} else
{
return $this->render('create', [
'model' => $model,
]);
}
}