Array to string conversion error while file upload,Error is displaying but not success data - codeigniter-3

My code is working fine on upload fail but on upload success error is thrown as undefined variable: data. Can anyone help me how I can pass the success data to view
public function index()
{
$this->load->view('Pdf', array('error' => ' ' ));
}
public function do_upload()
{
if($this->upload->do_upload())
{
$data['success']= $this->upload->data();
}
else
{
$data['error'] = $this->upload->display_errors();
}
}
view:
<?php echo $error;?>
<?php echo $data["file_name"];?>

When you upload using $this->upload->data(), you are get an Array as a result, not a variable or string.
e.g Below is an result array from Image upload.
Array
(
[file_name] =>
[file_type] =>
[file_path] =>
[full_path] =>
[raw_name] =>
[orig_name] =>
[client_name] =>
[file_ext] =>
[file_size] =>
[is_image] =>
[image_width] =>
[image_height] =>
[image_type] =>
[image_size_str] =>
)
And here you are printing an array using echo instead of print_r.
echo is used to give output the data.
print_r is used to print array.
So solution for this "Array to string conversion error while file upload" is,
Change echo $data["file_name"]; ==> print_r($data); or print_r($data['success'])

Related

Yii2: How to save/update field with integer array data type

I am trying to save a record with a field of integer array int[] data type to pgsql table but am unable to set the value in that field.
My save code is as follows:
$record = $this->findModel($modifiedRecord[$this->_idField]);
if($record){
try{
if($record->load($modifiedRecord,'') && $record->save()){
$response=[
'success'=>TRUE,
'message'=>'Record Saved Successfully.',
];
}
else{
$response=[
'success'=> FALSE,
'message'=>'Record Save Failed.',
'errors' => $record->getErrors()
];
}
}catch(Exception $e){
}
}
When I tried to view the data being passed and the model attribute after save with following code:
The output is as follows:
1) Update Attributes:
array (size=6)
'view_role' => string '{1,10,50}' (length=9)
'id' => string '12568' (length=5)
'updated_datetime' => string '2022-04-26 15:52:26' (length=19)
'updated_by' => int 1
2) After load to model:
array (size=23)
'id' => int 12568
.
.
.
'view_role' => string '{1,10,50}' (length=9)
.
.
.
3) After save success:
'id' => int 12568
.
.
.
'view_role' => string '{1,10,50}' (length=9)
.
.
.
Even though the model save result showed that the value was updated, the view_role field in the table was reset to {}.
Can anybody tell me how to fix this?

CodeIgniter Suddenly Cannot Upload Image and says Cannot Be Null

Greeting everyone and especially to Senior of CodeIgniter Developer.
I have a problem with website that was built from CodeIgniter (I am not the developer inherited by previous epmployer). This website cannot working properly, especially when upload the image and shows warning about
Error Number: 1048 Column 'article_image' cannot be null
I did try with find the problem on the script and database, but nothing change and because no one change the codes & contents. Today, i try again with changing the "Null into yes" (previously is "No"), and tried to upload the article. It is miracle that it is working but the next problem is the image is gone (broken). I search at other and looking people with same problem with me says that i need to upgrade the CodeIgniter. Mine is 3.0.0 while the latest is 3.1.10. I copy paste the content inside /System and /views/error/cli not making better but make it worse, the image at the web page is gone(missing).
This is my Article_model
defined('BASEPATH') OR exit('No direct script access allowed');
class Article_model extends CI_Model {
public function get_all()
{
// $this->db->order_by('article_date', 'desc');
// $this->db->order_by('article_view', 'desc');
// $query = $this->db->get_where('article', array('flag !=' => 3));
// return $query->result_array();
$query = $this->db->query("SELECT A.*,B.*, A.id AS id_article FROM article AS A JOIN category B ON A.article_category = B.id WHERE A.flag != 3 ORDER BY article_date DESC, article_view DESC ");
return $query->result_array();
}
public function check($article_id)
{
$query = $this->db->get_where('article', array('flag !=' => 3, 'id' => $article_id));
return $query->row_array();
}
public function get_category()
{
$query = $this->db->order_by('category_name', 'ASC')->get_where('category', array('flag' => 1));
return $query->result_array();
}
public function get_tag()
{
$query = $this->db->order_by('tag_name', 'ASC')->get_where('tag', array('flag' => 1));
return $query->result_array();
}
public function get_selected_tag($article_id)
{
$query = $this->db
->select('tag.id, tag_name')
->join('article_tag', 'tag_id = tag.id')
->where(array('tag.flag' => 1, 'article_id' => $article_id))
->get('tag');
return $query->result_array();
}
public function insert()
{
$this->load->helper('upload');
$this->load->library('image_moo');
$image = file_upload('article_image', 'upload/article');
$this->image_moo->load($image['full_path']);
$this->image_moo->resize(924, 527)->save($image['path'] . '/' . $image['file_name'], TRUE);
$this->image_moo->resize_crop(100, 69)->save($image['path'] . '/thumb/' . $image['file_name']);
$this->image_moo->resize_crop(367, 232)->save($image['path'] . '/cover/' . $image['file_name']);
$insert_data = array(
'article_author' => $this->session->admin_id,
'article_title' => $this->input->post('article_title'),
'article_slug' => url_title($this->input->post('article_title'), '-', TRUE),
'article_category' => $this->input->post('article_category'),
'article_image' => $image['file_name'],
'article_content' => $this->input->post('article_content'),
'is_popup' => $this->input->post('is_poup'),
'article_date' => $this->input->post('article_date'),
);
$this->db->insert('article', $insert_data);
$article_id = $this->db->insert_id();
foreach ($this->input->post('article_tag') as $tag)
{
// Check apakah tag itu udah ada di database?
if (is_numeric($tag))
{
$tag_id = $tag;
}
else
{
$this->db->insert('tag', array('tag_name' => strtolower(trim($tag)), 'tag_slug' => url_title(trim($tag), '-', TRUE)));
$tag_id = $this->db->insert_id();
}
if ( ! $this->db->get_where('article_tag', array('article_id' => $article_id, 'tag_id' => $tag_id))->row_array())
{
$this->db->insert('article_tag', array('article_id' => $article_id, 'tag_id' => $tag_id));
}
}
}
public function update($id)
{
$this->load->helper('upload');
$this->load->library('image_moo');
$image = file_upload('article_image', 'upload/article');
$this->image_moo->load($image['full_path']);
$this->image_moo->resize(924, 527)->save($image['path'] . '/' . $image['file_name'], TRUE);
$this->image_moo->resize_crop(100, 69)->save($image['path'] . '/thumb/' . $image['file_name']);
$this->image_moo->resize_crop(367, 232)->save($image['path'] . '/cover/' . $image['file_name']);
$insert_data = array(
'article_author' => $this->session->admin_id,
'article_title' => $this->input->post('article_title'),
'article_slug' => url_title($this->input->post('article_title'), '-', TRUE),
'article_category' => $this->input->post('article_category'),
'is_popup' => $this->input->post('is_popup'),
'article_content' => $this->input->post('article_content'),
'article_date' => $this->input->post('article_date'),
);
if ($image)
{
$insert_data['article_image'] = $image['file_name'];
}
$article_id = $id;
$this->db->where('id', $id);
$this->db->update('article', $insert_data);
$this->db->where('article_id', $id);
$this->db->delete('article_tag');
foreach ($this->input->post('article_tag') as $tag)
{
// Check apakah tag itu udah ada di database?
if (is_numeric($tag))
{
$tag_id = $tag;
}
else
{
$this->db->insert('tag', array('tag_name' => strtolower(trim($tag)), 'tag_slug' => url_title(trim($tag), '-', TRUE)));
$tag_id = $this->db->insert_id();
}
if ( ! $this->db->get_where('article_tag', array('article_id' => $article_id, 'tag_id' => $tag_id))->row_array())
{
$this->db->insert('article_tag', array('article_id' => $article_id, 'tag_id' => $tag_id));
}
}
}
}
What should i do guys? i did backup but it remain same like after upgraded. Thank you. Web Url (http://www.hidupseimbangku.com/)
First. If you want to upgrade CI Version you must follow Upgrading Guide one by one. There may be break changes and you need to correct them, you can find this guide here:
https://www.codeigniter.com/userguide3/installation/upgrading.html
I suggest you rollback upgrade changes and start again doing one by one. It is not hard, it is just time consuming.
The error you're getting is probably related to an error of uploading process. What is file_upload?
I also suggest you read this, for properly file upload.

cakephp formhelper : getting current file from input file on edit

I have a form where images can be submitted, this isn't originally my code, I'm inheriting it and I'm trying to figure it out and fix the problem.
When editing the datas from this form, the input file is empty as opposed to the other inputs. So saving actually replaces the current file to "array" in database.
I would like to be able to keep the current one if it is unchanged ?
Form edit :
<h1>Edit</h1>
<?php
echo $this->Form->create($template,['enctype' => 'multipart/form-data']);
echo $this->Form->input('title');
echo $this->Form->input('works_id');
echo $this->Form->input('photo',['type' => 'file']);
echo $this->Form->input('text', ['rows' => '4']);
echo $this->Form->input('url');
echo $this->Form->button(__('Save'));
echo $this->Form->end();
?>
edit function from controller :
public function edit($id = null){
$template = $this->Templates->get($id);
if ($this->request->is(['post', 'put'])) {
$template = $this->Templates->patchEntity($template, $this->request->data,['associated' => ['Works']]);
if ($this->Templates->save($template)) {
$this->Flash->success(__('Your template has been updated.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to update your template.'));
}
$this->set('template', $template);
$works = $this->Templates->Works->find('list');
$this->set(compact('works'));
}
In my database it saves on two colomns :
file_dir and filename, so it confuses me even more on how to get the file in the edit form.
edit : adding TemplatesTable :
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class TemplatesTable extends Table
{
protected function _initializeSchema(\Cake\Database\Schema\Table $table){
$table->columnType('photo', 'proffer.file');
return $table;
}
public function initialize(array $config){
$this->addBehavior('Timestamp');
$this->addBehavior('Proffer.Proffer', [
'photo' => [
'root' => WWW_ROOT.'files',
'dir' => 'photo_dir',
'thumbnailSizes' => [
'square' => ['w' => 200, 'h' => 200],
'portrait' => ['w' => 100, 'h' => 300, 'crop' => true],
],
'thumbnailMethod' => 'gd' // Options are Imagick, Gd or Gmagick
]
]);
$this->belongsTo(
'Works',
[
'foreignKey' => 'work_id',
]
);
}
public function validationDefault(Validator $validator){
$validator
->notEmpty('work_id')
->notEmpty('title');
return $validator;
}
}
According to the docs, the Proffer behavior can handle empty uploads out of the box, and you just have to configure the validation rules for the field accordingly to allow it to be empty on update:
If you want your users to submit a file when creating a record, but
not when updating it, you can configure this using the basic Cake
rules.
$validator
->requirePresence('image', 'create')
->allowEmpty('image', 'update');
So now your users do not need to upload a file every time they update
a record.
https://github.com/davidyell/CakePHP3-Proffer/blob/0.8.2/docs/validation.md
https://github.com/davidyell/CakePHP3-Proffer/blob/0.8.2/src/Model/Behavior/ProfferBehavior.php#L56
So in your case that would be:
->requirePresence('photo', 'create')
->allowEmpty('photo', 'update')

Form bindAndSave method doesn't save files

Parsing an XML feed and save it this way:
$action = new CouponActionForm();
$values = array(
'name' => $offer->name,
'link' => $offer->url,
'description' => $offer->description,
'discount' => $offer->discount,
'price' => $offer->price
);
$files = $this->getImages($offer->picture);
if(!$action->bindAndSave($values, $files)){
echo $action->renderGlobalErrors();
die('BAD THING');
}
Here is the getImages method:
private function getImages($url){
$ret = array('error' => 0);
$tmp_dir = sys_get_temp_dir();
$tmp_file = tempnam($tmp_dir, 'kupon');
if(copy($url, $tmp_file)){
$ret['tmp_name'] = $tmp_file;
$ret['name'] = basename($url);
$ret['size'] = filesize($tmp_file);
$ret['type'] = 'image/jpeg';
return array('filename' => $ret);
}else{
die('HELP');
}
}
Why do I use form saving instead of object saving with ->fromArray method ? Well, I already made the form and all validation, so I don't want to implement the same thing twice (DRY), but as important, I actually don't know how to use validators in doctrine model.
So the problem is that the form doesn't save files in specific directory specified by the path property of sfValidatorFile validator, but it exists in tmp directory.

cakephp email plugin to pull email by imap

I am using this cakephp email plugin to pull the emails from the account. Here are my parameters
'datasource' => 'Emails.Imap',
'server' => 'mail.example.com',
'connect' => 'imap/novalidate-cert',
'username' => 'username',
'password' => 'password',
'port' => '143',
'ssl' => false,
'encoding' => 'UTF-8',
'error_handler' => 'php',
and I make a query as it is indicated in documentation
$ticketEmails = $this->TicketEmail->find('first', array('recursive' => -1));
but when I debug the result, the following fields show data like this
Array
(
[TicketEmail] => Array
(
. . . other fields
[body] => CjxIVE1MPjxCT0RZPnNvbWUgbWVzc2FnZTxicj48L0JPRFk+PC9IVE1MPgo=
[plainmsg] => IHNvbWUgbWVzc2FnZQo=
. . . other fields
)
)
I can not understand why it shows these strings, e.g. in email account's message's body is just this text some message.
My cake version is 1.3
Thanks !
That's Base64 encoding, looks like the plugin doesn't handle that, it only checks for the quoted-printable format.
You could decode the data in your model, for example in the Model::afterFind() callback or in a custom method, or you could try modifying the plugin so that it returns the decoded data (untested):
protected function _fetchPart ($Part) {
$data = imap_fetchbody($this->Stream, $Part->uid, $Part->path, FT_UID | FT_PEEK);
if ($data) {
// remove the attachment check to decode them too
if ($Part->format === 'base64' && $Part->is_attachment === false) {
return base64_decode($data);
}
if ($Part->format === 'quoted-printable') {
return quoted_printable_decode($data);
}
}
return $data;
}