Stop form validation submitting if error on file upload - codeigniter

Question: When the user has filled in the form validation correct but there is a error on image upload how is it possible to stop the form being submitted
Currently still submits data even if there is a error on my image upload.
<?php
class Users extends MY_Controller {
private $error = array();
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->library('countries');
$this->load->library('upload');
$this->load->model('admin/user/user_model');
$this->load->model('admin/user_group/usergroup_model');
}
public function add() {
$this->form_validation->set_rules('username', 'Username', 'trim|required');
if ($this->form_validation->run() == true) {
if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0) {
if (!is_dir(FCPATH . 'uploads/users/' . $this->input->post('username') . '/')) {
mkdir(FCPATH . 'uploads/users/' . $this->input->post('username') . '/');
}
$config['upload_path'] = './uploads/users/' . $this->input->post('username') . '/';
$config['allowed_types'] = 'gif|png';
$config['max_size'] = 3000;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if ($this->upload->do_upload('userfile')) {
return true;
}
}
$this->user_model->insert($this->upload->data());
}
if ($this->upload->display_errors() != false) {
$this->error['warning'] = $this->upload->display_errors();
}
if (validation_errors() != false) {
$this->error['warning'] = validation_errors('<div class="alert alert-danger">', '</div>');
}
if (isset($this->error['warning'])) {
$data['warning_error'] = $this->error['warning'];
} else {
$data['warning_error'] = '';
}
$data['countries'] = $this->countries->get();
$data['timezones'] = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
$data['usergroups'] = $this->usergroup_model->get_user_groups();
$data['header'] = Modules::run('admin/common/header/index');
$data['footer'] = Modules::run('admin/common/footer/index');
$this->load->view('user/add_view', $data);
}
}
Model
<?php
class User_model extends CI_Model {
public function insert($upload_data = array()) {
$this->db->trans_begin();
$options = [
'cost' => 12,
];
$hash = password_hash($this->input->post('password'), PASSWORD_BCRYPT, $options);
$data = array(
'user_group_id' => $this->input->post('user_group_id'),
'username' => $this->input->post('username'),
'password' => $hash,
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname'),
'email' => $this->input->post('email'),
'image' => ($upload_data['file_name']) ? $upload_data['file_name'] : '',
'country' => $this->input->post('country'),
'timezone' => $this->input->post('timezone'),
'status' => $this->input->post('status'),
'date_added' => date('Y-m-d')
);
$this->db->set($data);
$this->db->insert($this->db->dbprefix . 'user');
if ($this->db->trans_status() === FALSE) {
$this->db->trans_rollback();
} else {
$this->db->trans_commit();
}
}
}
Codeigniter Version 3.1.0 & XAMPP Windows 10

Have solved it now.
<?php
class Users extends MY_Controller {
private $error = array();
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->library('countries');
$this->load->library('upload');
$this->load->model('admin/user/user_model');
$this->load->model('admin/user_group/usergroup_model');
}
public function add() {
$this->form_validation->set_rules('username', 'username', 'trim|required|is_unique[user.username]');
$this->form_validation->set_message('is_unique', 'Opps looks like someone has all ready got that {field}');
if ($this->form_validation->run() == true) {
if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0) {
if ($this->upload() == true) {
$this->user_model->insert($this->upload->data());
}
} else {
$this->user_model->insert();
}
}
if (validation_errors() != '') {
$this->error['warning'] = validation_errors('<div class="alert alert-danger">', '</div>');
}
if (isset($this->error['warning'])) {
$data['warning_error'] = $this->error['warning'];
} else {
$data['warning_error'] = '';
}
$data['countries'] = $this->countries->get();
$data['timezones'] = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
$data['usergroups'] = $this->usergroup_model->get_user_groups();
$data['header'] = Modules::run('admin/common/header/index');
$data['footer'] = Modules::run('admin/common/footer/index');
$this->load->view('user/add_view', $data);
}
public function upload() {
if (!is_dir(FCPATH . 'uploads/users/' . $this->input->post('username') . '/')) {
mkdir(FCPATH . 'uploads/users/' . $this->input->post('username') . '/');
}
$config['upload_path'] = './uploads/users/' . $this->input->post('username') . '/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 3000;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if (!$this->upload->do_upload('userfile')) {
$this->error['warning'] = $this->upload->display_errors('<div class="alert alert-danger">', '</div>');
} else {
return true;
}
return !$this->error;
}
}

Related

How to get/view images dynamically in homepage using CodeIgniter?

image
New_model
=========
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class New_model extends CI_Model
{
private $_table = "news";
public $title;
public $date;
public $description;
public $image = "default.jpg";
public $url;
public function rules()
{
return [
['field' => 'title',
'label' => 'Title',
'rules' => 'required'],
['field' => 'date',
'label' => 'Date',],
// 'rules' => 'required'],
['field' => 'description',
'label' => 'Description',
'rules' => 'required']
];
}
public function getAll()
{
return $this->db->get($this->_table)->result();
}
public function getById($id)
{
return $this->db->get_where($this->_table, ["new_id" => $id])->row();
}
public function save()
{
$post = $this->input->post();
// $this->new_id = uniqid();
$this->title = $post["title"];
$this->date = $post["date"];
$this->description = $post["description"];
$this->image = $this->_uploadImage();
$this->db->insert($this->_table, $this);
// $this->url = base_url() . 'uploads/';
$post['url'] = base_url() . 'uploads/';
}
public function update()
{
$post = $this->input->post();
$this->new_id = $post["id"];
$this->title = $post["title"];
$this->date = $post["date"];
$this->description = $post["description"];
if (!empty($_FILES["image"]["name"])) {
$this->image = $this->_uploadImage();
} else {
$this->image = $post["old_image"];
}
$this->db->update($this->_table, $this, array('new_id' => $post['id']));
}
public function delete($id)
{
$this->_deleteImage($id);
return $this->db->delete($this->_table, array("new_id" => $id));
}
private function _uploadImage()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
// $config['file_name'] = $this->new_id;
$config['overwrite'] = true;
$config['max_size'] = 1024; // 1MB
// $config['max_width'] = 1024;
// $config['max_height'] = 768;
$this->load->library('upload', $config);
if ($this->upload->do_upload('image')) {
return $this->upload->data("file_name");
}
return "default.jpg";
}
private function _deleteImage($id)
{
$new = $this->getById($id);
if ($new->image != "default.jpg") {
$filename = explode(".", $new->image)[0];
return array_map('unlink', glob(FCPATH."uploads/$filename.*"));
}
}
}
public function single($id)
{
$data['news'] = $this->New_model->where('new_id',$id)->order_by('new_id','desc')->get_all();
$data['news1'] = $this->New_model->limit(5)->order_by('id','desc')->get_all();
$this->current = 'news';
$this->load->view(['current' => $this->current]);
$this->load->view('news',$data);
}
Controller
==========
public function index()
{
$data["news"] = $this->New_model->getAll();
$this->load->view('index',$data);
}
public function latestnews()
{
$data['news'] = $this->New_model->where('new_id',$id)->order_by('new_id','desc')->get_all();
$this->load->view('news',$data);
}
view
====
<?php
if (isset($news) and $news) {
foreach ($news as $new) {
?>
<div class="tile-primary-content">
<img src="<?php echo $new->url . $new->image;?>" alt="image" />
</div>
<div class="tile-secondary-content">
<div class="section-title-1">
<span class="title"><?php echo $new->title;?></span>
</div>
<h2 class="heading-20"><?php echo $new->date;?></h2>
</div>
<?php
}
}
?>
I'm trying to upload an image in the dashboard with a title and date along with the image upload.
How to display that image on the homepage?
How to set the URL in the New_model?
How to set the links to display the images in the homepage?
How to set the date links?
The title field can be viewed in the homepage, but no image and date…
Try this code.
Controller: (Edited)
function index() {
$this->data["news"] = $this->new_model->getAll();
$this->load->view('index', $this->data);
}
function single_news($id) {
$this->data['news_data'] = $this->new_model->getNewsByID($id);
$this->load->view('single-news', $this->data); // Create New View file named single-news.php
}
function add_news() {
$image_status = FALSE;
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('description', 'Description', 'required');
if($this->form_validation->run() == TRUE) {
$image_name = NULL;
if ($_FILES['image']['size'] > 0) {
$this->load->library('upload');
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '1024';
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if( ! $this->upload->do_upload('image')){
$this->data['error'] = $this->upload->display_errors();
}
$image_name = $this->upload->file_name;
$image_status = TRUE;
}
$data = array(
'title' => $this->input->post('title'),
'date' => $this->input->post('date')?date('Y-m-d', strtotime($this->input->post('date'))):NULL,
'description' => $this->input->post('description'),
'image' => $image_name
);
}
if($this->form_validation->run() == TRUE && $image_status && $this->new_model->addNews($data)) {
$this->session->set_flashdata('message', 'News has been created successfully.');
redirect('index');
} else {
$this->data['error'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('error');
$this->data['page_title'] = 'Add News';
$this->load->view('add_news', $this->data);
}
}
When adding new News you don't need to add the uploaded location (Not necessary).
Model: (Edited)
function getAll() {
$q = $this->db->get('news');
if($q->num_rows() > 0) {
foreach($q->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
function getNewsByID($id) {
$this->db->where('id', $id);
$q = $this->db->get('news');
if($q->num_rows() > 0) {
return $q->row();
}
return false;
}
function addNews($data) {
if($this->db->insert('news', $data)){
return true;
}
return false;
}
View: (Edited)
<?php
if ($news) {
foreach ($news as $new) {
?>
<div class="tile-primary-content">
<a href="<?php echo base_url('single_news/'.$new->id); ?>"
<img src="<?php echo site_url('uploads/'.$new->image); ?>" alt="image" />
</a>
</div>
<div class="tile-secondary-content">
<div class="section-title-1">
<span class="title"><?php echo $new->title;?></span>
</div>
<h2 class="heading-20"><?php echo !is_null($new->date)?date('d.m.Y', strtotime($new->date)):' - ';?></h2>
</div>
<?php
}
}
?>
single-news.php: (View)
...
<img src="<?php echo site_url('uploads/'.$news_data->image); ?>" />
...

How to redirect to another page in codeigniter from one page?

I have written a code in the controller which is given below. This code is for login page. In this code, the if statement notification is properly working but the else part is not working. It is not redirect to the url given in the redirect() instead it is showing a blank page. Can anyone tell y it is like that and correct it for me ? I have used header() function but also it is not working.I have placed all the code inside the 'kw' folder. This code is properly working in the localhost but when uploaded the same code to the live server, its not working.Is it due to version of the CI ?
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->library('validation');
$this->load->model('studentsmodel');
}
public function index() {
if (isset($_POST['submit']))
{
$post_data = array('stud_cin' => $this->input->post('stud_cin'),'stud_password' => $this->input->post('stud_password'),
);
$this->validation->set_data($post_data);
$this->validation->set_rules('stud_cin','Cin','required|trim');
$this->validation->set_rules('stud_password','Password','required|trim');
if ($this->validation->run() === FALSE)
{
}
else
{
$this->load->model("studentsmodel");
$this->load->helper('url');
$result = $this->studentsmodel->loginCheck($post_data);
if (!$result){
$this->notifications->notify('Wrong username/password; Login Failed','error');
}
else{
$this->session->set_userdata('student_id', $result['id']);
$this->session->set_userdata('stud_cin', $result['stud_cin']);
$this->session->set_userdata('stud_photopath', $result['stud_photopath']);
redirect('student/profile/edit/id/'.$this->session->userdata('student_id'),'refresh');
//header('location:http://www.website.com/kw/application/controller/student/profile/edit/id/$this->session->userdata("student_id")');
}
}
} $this->load->view("login");
}
}
profile controller edit function
public function index()
{
$student_id=$this->session->userdata('student_id');
$data['profile_data'] =$this->studentsmodel->get_Cinprofile($student_id);
$this->load->view("profileDetails.php", $data);
}
public function edit()
{
$uri = $this->uri->uri_to_assoc(4);
$student_id=$uri['id'];
if(isset($_POST['btn_submit']))
{
//echo "<pre>";print_r($_FILES);exit;
$img_val = $this->studentsmodel->getStudent_photo($student_id);
$photo_val = $img_val['stud_photopath'];
$photo_unlink = "";
if ($_FILES['stud_photopath']['name'] != "")
{
/*echo "in";exit;*/
$photo_chk = explode("photo/", $photo_val);
$photo_unlink = $photo_chk[1];
$photo_path = "";
$flag = "";
$f_type_chk = $_FILES['stud_photopath']['type'];
if ($f_type_chk != "image/gif" && $f_type_chk != "image/jpg" && $f_type_chk != "image/jpeg"
&& $f_type_chk != "image/bmp" && $f_type_chk != "image/png" && $f_type_chk != "")
{
$flag = "Select allowed file type and size for photo";
}
if ($_FILES['stud_photopath']['size'] >= 5242880) { $flag = "Select allowed file type and size for photo"; }
$target_path = getcwd() . "/public/photo/";
$db_path = "photo/";
if ($_FILES['stud_photopath']['name'] != '')
{
$file_name = $_FILES["stud_photopath"]["name"];
$file_size = $_FILES["stud_photopath"]["size"] / 1024;
$file_type = $_FILES["stud_photopath"]["type"];
$file_tmp_name = $_FILES["stud_photopath"]["tmp_name"];
$random = rand(111, 999);
$new_file_name = $random . $file_name;
$newfile_name=$cin."_". $file_name;
$upload_path = $target_path . $newfile_name;;
if (move_uploaded_file($file_tmp_name, $upload_path)) { $photo_path = addslashes($db_path . $newfile_name); } /*end if*/
else { $this->notifications->notify('Photo cannot upload', 'error'); }/*end else var_dump($this->validation->show_errors());*/
}/*end if $_FILES['photo']['name']*/
} /*END OF if ($_FILES['photo']['name'] != "") */
else { $photo_path = $photo_val; } /*END OF ELSE ($_FILES['photo']['name'] != "") */
$this->session->unset_userdata('stud_photopath');
$this->session->set_userdata('stud_photopath', $photo_path);
$data['photo_unlink'] = $photo_unlink;
/* echo $dob_dd = $this->input->post('dob_dd');exit;
$dob_mm = $this->input->post('dob_mm');
$dob_yy = $this->input->post('dob_yy');
$dob = $dob_dd . "-" . $dob_mm . "-" . $dob_yy;*/
$stud_age_dob =$this->input->post('stud_age_dob');
$timestamp = strtotime($stud_age_dob);
$dob = date('Y-m-d', $timestamp);
$validation_data = array(
'stud_name' => $this->input->post('stud_name'),
'stud_gender' => $this->input->post('stud_gender'),
'stud_age_dob' =>$this->input->post('stud_age_dob'),
'stud_mobile' => $this->input->post('stud_mobile'),
'stud_email' => $this->input->post('stud_email'),
);
//echo "<pre>";print_r($validation_data); exit;
$this->validation->set_data($validation_data);
$this->validation->set_rules('stud_name', 'Student Name', 'trim|alpha_space|required');
$this->validation->set_rules('stud_gender', 'Gender', 'required');
$this->validation->set_rules('stud_age_dob', 'DOB', 'required');
$this->validation->set_rules('stud_mobile', 'Mobile number', 'numeric|required');
$this->validation->set_rules('stud_email', 'Email Id', 'trim|required|valid_email|xss_clean');
if ($this->validation->run() === FALSE)
{ /* var_dump($this->validation->show_errors()); */ $this->notifications->notify('Please make all entries', 'error');}
else
{
$updation_data=array(
'stud_name' => $this->input->post('stud_name'),
'stud_gender' => $this->input->post('stud_gender'),
'stud_age_dob' => $this->input->post('stud_age_dob'),
'stud_gaurdian' =>$this->input->post('stud_gaurdian'),
'stud_mother' =>$this->input->post('stud_mother'),
'stud_mobile' => $this->input->post('stud_mobile'),
'stud_email' => $this->input->post('stud_email'),
'stud_tel' => $this->input->post('stud_tel'),
'stud_guardian_address' => $this->input->post('stud_guardian_address'),
'stud_pin' => $this->input->post('stud_pin'),
'stud_photopath' => $photo_path,
'stud_age_dob' => $dob
);
/*echo "<pre>";print_r($updation_data); exit; */
$update_status=$this->studentsmodel->update_profile($updation_data, $student_id);
if($update_status==1)
{
//$this->session->set_userdata('profile_status', 'Yes');
/*$this->session->userdata('profile_status');*/
redirect('student/profile/index/', 'refresh');
}
else
{
$this->notifications->notify('profile updted failed', 'error');
}
$data['profile_data']=$_POST;
}
$data['profile_data']=$_POST;
}
$data['profile_data']=$this->studentsmodel->get_Cinprofile($student_id);
$this->load->view("profile_edit.php",$data);
}
Check if you already load this helper
$this->load->helper('url');
This is the information about the redirect function
redirect($uri = '', $method = 'auto', $code = NULL);
Parameters:
$uri (string) URI string $method (string)
Redirect method (‘auto’,
‘location’ or ‘refresh’)
$code (string) HTTP Response code (usually 302 or 303)
Note:
Don't forget add in the config file the value for base_uri
https://www.codeigniter.com/user_guide/helpers/url_helper.html
https://www.codeigniter.com/userguide3/libraries/config.html
remove /id/ from your redirect()
redirect('student/profile/edit/'.$this->session->userdata('student_id'));

error column 'picture' cannot be null

My initial question was posted wrong so i'm reposting it. I am practicing with a tutorial on tutsplus by joost van veen and i added an image upload to the controller but every time i try to save a post i get an error from database saying column 'picture' cannot be null. I've checked other answers but nothing explains the problem. Any help would be appreciated.
MY CONTROLLER
public function edit($post_id = NULL) {
// Fetch all articles or set a new one
if ($post_id) {
$this->data['article'] = $this->article_m->get($post_id);
count($this->data['article']) || $this->data['errors'][] = 'article could not be found';
}
else {
$this->data['article'] = $this->article_m->get_new();
}
// Set up the form
$rules = $this->article_m->rules;
$this->form_validation->set_rules($rules);
if ($this->input->post('userSubmit')) {
//check if user uploads picture
if (!empty($_FILES['picture']['name'])) {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|png|gif|jpeg';
$config['file_name'] = $_FILES['picture']['name'];
//load upload library and initialize configuration
$this->upload->initialize($config);
if ($this->upload->do_upload('picture')) {
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
} else {
$picture = '';
}
} else {
$picture = '';
}
// prepare array of posts data
$data = $this->article_m->array_from_post(array(
'title',
'slug',
'content',
'category_id',
'picture',
'pubdate'
));
$insertPosts = $this->article_m->save($data, $post_id);
redirect('admin/article');
//storing insertion status message
if ($insertPosts) {
$this->session->set_flashdata('success_msg', 'Post has been added Successfully.');
} else {
$this->session->set_flashdata('error_msg', 'error occured while trying upload, please try again.');
}
}
// Load view
$this->data['subview'] = 'admin/article/edit';
$this->load->view('admin/components/page_head', $this->data);
$this->load->view('admin/_layout_main', $this->data);
$this->load->view('admin/components/page_tail');
}
MY_MODEL
public function array_from_post($fields) {
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
$data['category_id'] = $this->input->post('category');
}
return $data;
}
public function save($data, $id = NULL) {
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
}
// Update
else {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
RULES TO SET FORM VALIDATION
public $rules = array(
'pubdate' => array(
'field' => 'pubdate',
'label' => 'Publication date',
'rules' => 'trim|required|exact_length[10]'
),
'title' => array(
'field' => 'title',
'label' => 'Title',
'rules' => 'trim|required|max_length[100]'
),
'slug' => array(
'field' => 'slug',
'label' => 'Slug',
'rules' => 'trim|required|max_length[100]|url_title'
),
'content' => array(
'field' => 'content',
'label' => 'Content',
'rules' => 'trim|required'
),
'picture' => array(
'field' => 'picture',
'label' => 'Upload File',
'rules' => 'trim'
),
);
public function get_new() {
$article = new stdClass();
$article->title = '';
$article->category_id = '';
$article->slug = '';
$article->content = '';
$article->picture = '';
$article->pubdate = date('Y-m-d');
return $article;
}
I fixed the problem by creating a new method array_me() in the model and calling it in the controller.
NEW METHOD IN MY_MODEL
public function array_me($fields) {
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
$data['category_id'] = $this->input->post('category');
$data['picture'] = $picture;
}
return $data;
}
EDITED CONTROLLER
public function edit($post_id = NULL) {
// Fetch all articles or set a new one
if ($post_id) {
$this->data['article'] = $this->article_m->get($post_id);
count($this->data['article']) || $this->data['errors'][] = 'article could not be found';
}
else {
$this->data['article'] = $this->article_m->get_new();
}
// Set up the form
$rules = $this->article_m->rules;
$this->form_validation->set_rules($rules);
if ($this->input->post('userSubmit')) {
//check if user uploads picture
if (!empty($_FILES['picture']['name'])) {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|png|gif|jpeg';
$config['file_name'] = $_FILES['picture']['name'];
//load upload library and initialize configuration
$this->upload->initialize($config);
if ($this->upload->do_upload('picture')) {
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
} else {
$picture = '';
}
} else {
$picture = '';
}
// prepare array of posts data
$data = $this->article_m->array_me(array(
'title',
'slug',
'content',
'category_id',
'picture',
'pubdate'
));
$insertPosts = $this->article_m->save($data, $post_id);
redirect('admin/article');
//storing insertion status message
if ($insertPosts) {
$this->session->set_flashdata('success_msg', 'Post has been added Successfully.');
} else {
$this->session->set_flashdata('error_msg', 'error occured while trying upload, please try again.');
}
}
// Load view
$this->data['subview'] = 'admin/article/edit';
$this->load->view('admin/components/page_head', $this->data);
$this->load->view('admin/_layout_main', $this->data);
$this->load->view('admin/components/page_tail');
}

When echo multiple file data it only display last file info

On my multiple upload library I have a function which is called upload data.
And another function called upload.
For some reason when I select multiple images and is success full when I use on my controller
$data = $this->multiple_upload->upload_data();
echo $data['file_name'];
It will only get the name of the last file selected it does not return all file names selected. It should display all file names selected.
Question: How on my library function upload_data() can I make sure can return data correctly rather than just the last one. the upload_data function just seems to only return the last file information.
Library
<?php
class Multiple_upload {
public function __construct($config = array()) {
$this->CI =& get_instance();
$this->files = $this->clean($_FILES);
empty($config) OR $this->set_config($config);
}
public function set_config($config) {
foreach ($config as $key => $value) {
$this->$key = $value;
}
return $this;
}
public function upload($field = 'userfile') {
if (empty($this->upload_path)) {
$this->set_error('upload_path_not_set');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path)) {
$this->set_error('upload_path_in_correct');
return FALSE;
}
if (!empty($this->files[$field]['name'][0])) {
$check_error = 0;
foreach ($this->files[$field]['name'] as $key => $value) {
$this->file_name = $this->files[$field]['name'][$key];
$this->file_temp = $this->files[$field]['tmp_name'][$key];
$this->file_size = $this->files[$field]['size'][$key];
$this->get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($this->get_file_extension));
if (!in_array($this->get_file_extension_end, $this->allowed_types)) {
$this->set_error('file_extension_not_allowed');
$check_error++;
}
if ($this->files[$field]['size'][$key] > $this->max_size) {
$this->set_error('file_size_check');
$check_error++;
}
if ( ! #copy($this->file_temp, FCPATH . $this->upload_path . '/' . $this->file_name)) {
if ( ! #move_uploaded_file($this->file_temp, FCPATH . $this->upload_path . '/' . $this->file_name)) {
$this->set_error('upload_destination_error', 'error');
$check_error++;
}
}
}
if($check_error > 0 ) {
return FALSE;
}
// This lets me get file data in another function
return $this;
}
}
public function upload_data() {
$data = array(
'file_name' => $this->file_name,
'file_path' => FCPATH . $this->upload_path . '/'
);
return $data;
}
public function set_error($message) {
$this->CI->lang->load('upload', 'english');
$msg = "";
if ($message == 'upload_path_not_set') {
$msg .= $this->CI->lang->line($message);
}
if ($message == 'upload_path_in_correct') {
$msg .= $this->CI->lang->line($message);
}
if ($message == 'file_extension_not_allowed') {
$msg .= sprintf($this->CI->lang->line($message), $this->file_name, $this->get_file_extension_end);
}
if ($message == 'file_size_check') {
$msg .= sprintf($this->CI->lang->line($message), $this->file_name, $this->max_size);
}
return $this->error_message[] = $msg;
}
public function display_error_messages($open_tag = '<p>', $close_tag = '</p>') {
$message = "";
if (isset($this->error_message)) {
foreach($this->error_message as $msg) {
$message .= $open_tag . $msg . $close_tag;
}
}
return $message;
}
public function clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[$this->clean($key)] = $this->clean($value);
}
} else {
$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
}
return $data;
}
}
I have tried
public function upload_data() {
$data[] = array(
'file_name' => $this->file_name,
'file_path' => FCPATH . $this->upload_path . '/'
);
return $data;
}
Controller index function
public function index(){
$data['error'] = '';
$this->load->library('multiple_upload');
$config['upload_path'] = 'uploads';
$config['allowed_types'] = array('jpg', 'png');
$config['max_size'] = 3000000;
//$config['max_size'] = 1000;
$config['overwrite'] = TRUE;
$this->multiple_upload->set_config($config);
if ($this->multiple_upload->upload() == FALSE) {
$data['error'] = $this->multiple_upload->display_error_messages('<div class="alert alert-danger">', '</div>');
$this->load->view('upload', $data);
} else {
$data = $this->multiple_upload->upload_data();
echo $data['file_name'];
}
}
<?php
class Multiple_upload {
private $filenames;
public function __construct($config = array()) {
$this->CI =& get_instance();
$this->files = $this->clean($_FILES);
$this->filenames = array();
empty($config) OR $this->set_config($config);
}
public function set_config($config) {
foreach ($config as $key => $value) {
$this->$key = $value;
}
return $this;
}
public function upload($field = 'userfile') {
if (empty($this->upload_path)) {
$this->set_error('upload_path_not_set');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path)) {
$this->set_error('upload_path_in_correct');
return FALSE;
}
if (!empty($this->files[$field]['name'][0])) {
$check_error = 0;
foreach ($this->files[$field]['name'] as $key => $value) {
$this->file_name = $this->files[$field]['name'][$key];
$this->filenames[] = $this->files[$field]['name'][$key];
$this->file_temp = $this->files[$field]['tmp_name'][$key];
$this->file_size = $this->files[$field]['size'][$key];
$this->get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($this->get_file_extension));
if (!in_array($this->get_file_extension_end, $this->allowed_types)) {
$this->set_error('file_extension_not_allowed');
$check_error++;
}
if ($this->files[$field]['size'][$key] > $this->max_size) {
$this->set_error('file_size_check');
$check_error++;
}
if ( ! #copy($this->file_temp, FCPATH . $this->upload_path . '/' . $this->file_name)) {
if ( ! #move_uploaded_file($this->file_temp, FCPATH . $this->upload_path . '/' . $this->file_name)) {
$this->set_error('upload_destination_error', 'error');
$check_error++;
}
}
}
if($check_error > 0 ) {
return FALSE;
}
// This lets me get file data in another function
return $this;
}
}
public function upload_data()
{
$data = array();
foreach($this->filenames as $filename)
{
$data[] = array(
'file_name' => $filename,
'file_path' => FCPATH . $this->upload_path . '/'
);
}
return $data;
}
public function set_error($message) {
$this->CI->lang->load('upload', 'english');
$msg = "";
if ($message == 'upload_path_not_set') {
$msg .= $this->CI->lang->line($message);
}
if ($message == 'upload_path_in_correct') {
$msg .= $this->CI->lang->line($message);
}
if ($message == 'file_extension_not_allowed') {
$msg .= sprintf($this->CI->lang->line($message), $this->file_name, $this->get_file_extension_end);
}
if ($message == 'file_size_check') {
$msg .= sprintf($this->CI->lang->line($message), $this->file_name, $this->max_size);
}
return $this->error_message[] = $msg;
}
public function display_error_messages($open_tag = '<p>', $close_tag = '</p>') {
$message = "";
if (isset($this->error_message)) {
foreach($this->error_message as $msg) {
$message .= $open_tag . $msg . $close_tag;
}
}
return $message;
}
public function clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[$this->clean($key)] = $this->clean($value);
}
} else {
$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
}
return $data;
}
}
And
public function index()
{
$data['error'] = '';
$this->load->library('multiple_upload');
$config['upload_path'] = 'uploads';
$config['allowed_types'] = array('jpg', 'png');
$config['max_size'] = 3000000;
//$config['max_size'] = 1000;
$config['overwrite'] = TRUE;
$this->multiple_upload->set_config($config);
if ($this->multiple_upload->upload() == FALSE)
{
$data['error'] = $this->multiple_upload->display_error_messages('<div class="alert alert-danger">', '</div>');
$this->load->view('upload', $data);
}
else
{
$data = $this->multiple_upload->upload_data();
foreach($data as $file)
{
echo $file['file_name']."<br>";
}
}
}
you can use array to save all files information in upload_data function.
public function upload_data() {
$data = array(
'file_name' => $this->file_name,
'file_path' => FCPATH . $this->upload_path . '/'
);
return $data;
}
to
public function upload_data() {
$data[] = array(
'file_name' => $this->file_name,
'file_path' => FCPATH . $this->upload_path . '/'
);
return $data;
}
it will return array of all the file details

Grocery Crud default value after add

I need to add default images to post, if user do not select an image to upload.
Field to load the image optional.
How can i make it?
I use this controller.
public function news() {
$cur_user_id['user_id'] = $this->ion_auth->user()->row()->user_id;
$this->db->update('news', $cur_user_id);
$crud = new grocery_CRUD();
$crud->set_table('news')
->display_as('title', 'Заголовок')
->display_as('content', 'Текст')
->display_as('date', 'Дата')
->display_as('urlpict', 'Изображение')
->display_as('hide', 'Отображение')
->display_as('tags', 'Теги')
->display_as('add_new_tags', 'Добавить новые теги')
->display_as('menu_id', 'Раздел меню');
$crud->unset_columns('user_id');
$crud->required_fields('title', 'content', 'date', 'hide');
//relation
$crud->set_relation('menu_id', 'my_menu', 'name');
$crud->set_relation_n_n('tags', 'tag2art', 'tags', 'art_id', 'tag_id', 'tag');
//configuration for uploading
$this->config->set_item('grocery_crud_file_upload_allow_file_types', 'gif|jpeg|jpg|png');
$crud->set_field_upload('urlpict', 'assets/uploads/images');
//callback function
$crud->callback_after_upload(array($this, 'func_callback_after_upload'));
$state = $crud->getState();
$state_info = $crud->getStateInfo();
if ($state == 'add') {
$crud->fields('title', 'content', 'date', 'urlpict', 'hide', 'tags', 'add_new_tags', 'menu_id');
$crud->callback_add_field('add_new_tags', array($this, 'add_field_callback_1'));
} else {
$crud->unset_fields('add_new_tags', 'views', 'user_id');
}
$output = $crud->render();
$this->load->view('administrator/news', $output);
}
It's my callback_function
function func_callback_after_upload($uploader_response, $field_info, $files_to_upload)
{
$config['image_library'] = 'gd2';
$config['source_image'] = $field_info->upload_path . '/' . $uploader_response[0]->name;
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 175;
$config['height'] = 175;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
return true;
}
Mine solution
Instead $crud->callback_after_update(array($this, 'default_img'));
I used $crud->callback_after_insert(array($this, 'default_img'));
And my controller
function default_img($post_array, $primary_key) {
if (!$this->input->post('urlpict')) {
$default_img = array(
"id" => $primary_key,
"urlpict" => "news_default.png"
);
$this->db->update('news', $default_img, array('id' => $primary_key));
return true;
}
}

Resources