I would like to know with my code how am I able to make my file upload required. Because codeigniter form validation set rules is for post only.
I am unsure on how to make the file upload a requirement on form submit so it checks if file is required. And lets me submit form if file is upload or something along those lines
The callback works fine but required function cannot get to work with file upload.
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Store_add extends MX_Controller {
public function __construct() {
parent::__construct();
if (!$this->session->userdata('isLogged')) {
redirect('admin');
}
$this->load->model('admin/setting/model_store_add');
$this->load->model('admin/setting/model_store_get');
$this->lang->load('admin/setting/store_add', $this->settings->get('config_admin_language'));
}
public function index() {
// Title Language
$this->document->setTitle($this->lang->line('heading_title'));
$this->load->library('form_validation');
$this->form_validation->set_rules('config_image', 'Store Image', 'callback_do_upload_image');
if ($this->form_validation->run($this) == FALSE) { // "$this is for HMVC MY_Form_validation"
return $this->load->view('setting/store_add.tpl');
} else {
$store_id = $this->model_store_add->add_store();
$this->do_upload_image($store_id);
$this->session->set_flashdata('success', $this->lang->line('text_success'));
redirect('admin/setting/store');
}
}
public function do_upload_image($store_id) {
$config['upload_path'] = './image/upload/';
$config['allowed_types'] = $this->settings->get('config_file_ext_allowed');
$config['max_size'] = $this->settings->get('config_file_max_size');
$config['overwrite'] = $this->settings->get('config_file_overwrite');
$config['max_width'] = '*';
$config['max_height'] = '*';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('config_image')) {
$this->load->library('form_validation');
$this->form_validation->set_message('do_upload_image', $this->upload->display_errors('<b>config_image</b>' .' '));
return false;
} else {
if ($store_id) {
$this->model_store_add->add_config_image($store_id, $this->upload->data());
}
}
}
}
Sample View form
<div class="panel-body">
<?php $data = array('id' => 'form-store-add', 'role' => 'form', 'class' => 'form-horizontal' );?>
<?php echo form_open_multipart('admin/setting/store/add', $data);?>
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<?php echo validation_errors('<div class="alert alert-danger">', '</div>'); ?>
<?php echo $this->load->view('setting/store_flashdata.tpl');?>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="input-image"><?php echo $entry_image; ?></label>
<div class="col-sm-10">
<input type="hidden" name="config_image" value="<?php echo set_value('config_image', '');?>">
<input type="file" name="config_image" size="20"/>
</div>
</div>
<?php echo form_close();?>
</div>
WORKING NOW: I did more research on http://php.net/ I have fixed form validation for file upload made sure it is required I added is_file_upload and also added set form validation message with a return of false
public function do_upload_image($store_id) {
$config['upload_path'] = './image/upload/';
$config['allowed_types'] = $this->settings->get('config_file_ext_allowed');
$config['max_size'] = $this->settings->get('config_file_max_size');
$config['overwrite'] = $this->settings->get('config_file_overwrite');
$config['max_width'] = '*';
$config['max_height'] = '*';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (is_uploaded_file($_FILES['config_image']['tmp_name'])) {
if (!$this->upload->do_upload('config_image')) {
$this->load->library('form_validation');
$this->form_validation->set_message('do_upload_image', $this->upload->display_errors('<b>config_image</b>' .' '));
return false;
} else {
if ($store_id) {
$this->model_store_add->add_config_image($store_id, $this->upload->data());
}
}
} else {
$this->form_validation->set_message('do_upload_image', 'Image Required');
return false;
}
}
Related
Codeigniter When i use enctype="multipart/form-data" in signup form photo not save in database but photo going to uploads folder. Then When i remove enctype="multipart/form-data" photo save in database but photo not coming uploads folder. If this is problem for the code, please do the full code. Because I'm not a good developer.
View
<form method="post" action="family_join" enctype="multipart/form-data" id="wizard">
<h4 class="text-center mb-4 mt-4">Upload Photo</h4>
<div class="form-group mt-3 mb-4">
<div class="dropzone-wrapper">
<div class="dropzone-desc">
<i class="glyphicon glyphicon-download-alt"></i>
<p>Choose an image file or drag it here.</p>
</div>
<input type="file" name="photo" class="dropzone">
</div>
</div>
<h4 class="text-center mb-4">Please enter the zipcode</h4>
<div class="default-form contact-form">
<div class="form-group">
<input type="text" name="zipcode" placeholder="Enter Zip Code" required>
</div>
</div>
</form>
Controller
< ? php
defined('BASEPATH') OR exit('No direct script access allowed');
Class Family_Join extends CI_Controller {
public
function __construct() {
parent::__construct();
$this->load-> helper(array('form', 'url'));
}
public
function index() {
$this->form_validation-> set_rules('zipcode', 'Zipcode', 'required|min_length[4]');
if ($this->form_validation->run()) {
$zipcode=$this->input->post('zipcode');
$photo=$this->input->post('photo');
$status = 1;
$this->load->model('Family_Join_Model');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
$this->upload->do_upload('photo');
$this-> Family_Join_Model->insert($zipcode, $photo, $status);
} else {
$this->load->view('user/family_join', array('error' => ' '));
}
}
}
Model
< ? php
defined('BASEPATH') OR exit('No direct script access allowed');
Class Family_Join_Model extends CI_Model {
public
function insert($zipcode, $photo, $status) {
$data = array(
'zipcode' => $zipcode,
'photo' => $photo,
'isActive' => $status
);
$sql_query=$this->db->insert('tblfm', $data);
if ($sql_query) {
$this->session->set_flashdata('success', 'Registration successfull');
redirect('user/family_join');
} else {
$this->session->set_flashdata('error', 'Somthing went worng. Error!!');
redirect('user/family_join');
}
}
}
That happens because when you set enctype to multipart/form-data your input send to server as a binary file and a binary file can not be inserted in database.
For inserting file name into your database follow steps below.
Keep enctype=multipart/form-data (So your file will be uploaded to server)
replace this line :
$this->Family_Join_Model->insert($zipcode, $photo, $status);
with these:
$upload_data = $this->upload->data();
$this->Family_Join_Model->insert($zipcode, $upload_data['file_name'], $status);
Upload file first and get the file name from uploaded file data.
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if ($this->upload->do_upload('photo')) {
$file_details = $this->upload->data();
$photo = $file_details['file_name'];
} else {
$file_upload_msg = $this->upload->display_errors('<p>', '</p>');
}
$this->upload->do_upload('photo');
$upload_data = $this->upload->data();
$this->Family_Join_Model->insert($zipcode, $upload_data, $status);
**Model**
public
function insert($zipcode, $upload_data, $status) {
$data = array(
'zipcode' => $zipcode,
'photo' => $upload_data['file_name'],
'isActive' => $status
);
$sql_query=$this->db->insert('tblfm', $data);
if ($sql_query) {
$this->session->set_flashdata('success', 'Registration successfull');
redirect('user/family_join');
} else {
$this->session->set_flashdata('error', 'Somthing went worng. Error!!');
redirect('user/family_join');
}
}
so i try to make some upload form which will upload some image. but when the image has chosen then the button submit has clicked the result say "You did not select a file to upload."
im using php, with codeigniter framework
The view
<form class="text-left" enctype="multipart/form-data" method="post" action="<?= base_url('aduan/add'); ?>">
<div class="form-group">
<label>Upload Foto Bukti Aduan</label>
<div class="form-group">
<label>Bukti Aduan 1</label>
<input class="form-control-file" type="file" id="bukti1" name="bukti_aduan1" />
<?= form_error('bukti_aduan1', '<p class="text-danger font-weight-bold pl-2">', '</p>'); ?>
</div>
<div class="form-group">
<label>Bukti Aduan Pelapor di Lokasi</label>
<input class="form-control-file" type="file" id="bukti2" name="bukti_aduan2" />
<?= form_error('bukti_aduan2', '<p class="text-danger font-weight-bold pl-2">', '</p>'); ?>
</div>
</div>
which the view will run the controller "aduan" for input function
Controller file:
$aduan = $this->aduan_model;
$validation = $this->form_validation;
$validation->set_rules($aduan->rules());
if ($validation->run()) {
$aduan->tambah();
$this->session->set_flashdata('success', 'Berhasil disimpan');
$data['title'] = 'Buat Aduan Kasus Lingkungan';
$this->load->view('home/home_header', $data);
$this->load->view('home/aduansukses');
$this->load->view('home/home_footer');
} else {
$data['aduan'] = $this->aduan_model->getAll();
$data['title'] = 'Buat Aduan Kasus Lingkungan';
$this->load->view('home/home_header', $data);
$this->load->view('home/buataduan');
$this->load->view('home/home_footer');
}
then the controller will load a model which is "aduan_model"
Model file :
public function tambah()
{
$post = $this->input->post();
$this->nik_pelapor = $post["nik_pelapor"];
$this->nama_pelapor = $post["nama_pelapor"];
$this->email_pelapor = $post["email_pelapor"];
$this->telp_pelapor = $post["telp_pelapor"];
$this->alamat_pelapor = $post["alamat_pelapor"];
$this->aduan = $post["aduan"];
$this->bukti_aduan1 = $this->_uploadImage();
$this->bukti_aduan2 = $this->_uploadImage2();
$this->status_aduan = 'Dalam proses';
$this->tgl_aduan = time();
$this->db->insert($this->_table, $this);
}
private function _uploadImage()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
// $config['max_width'] = 1024;
// $config['max_height'] = 768;
$this->load->library('upload', $config);
if ($this->upload->do_upload('bukti_aduan1')) {
return $this->upload->data();
}
return "default.jpg";
}
private function _uploadImage2()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
// $config['max_width'] = 1024;
// $config['max_height'] = 768;
$this->load->library('upload', $config);
if ($this->upload->do_upload('bukti_aduan2')) {
return $this->upload->data();
}
return "default.jpg";
}
i expect the output of image can be stored in file upload and inserted in database but it doesnt select any file
please help :)
try my code
replace if condition in controller to upload
if(
(!$this->upload->do_upload('bukti_aduan2')) &&
(! $this->upload->do_upload('bukti_aduan1'))
)
{
echo "failed";
}
else
{
echo "success";
}
I'm stuck from make a update image from codeigniter, i want replace image when i update it but, the code its doesn't work.
here is my code :
this is Controller :
public function updatefoto(){
$this->load->model('model_users');
$this->model_users->updatefoto();
}
This is The Model
public function updatefoto($userId){
if($this->input->post('submit')){
$config['upload_path'] = "./uploads/images/";
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '2000';
$config['max_width'] = '2000';
$config['max_height'] = '2000';
$config['file_name'] = 'gambar-'.trim(str_replace(" ","",date('dmYHis')));
$this->load->library('upload', $config);
if (!$this->upload->do_upload("gambar")) {
$error = array('error' => $this->upload->display_errors('<div class="alert alert-danger">×','</div>'));
$this->load->view('view_ubah_data-profile', $error);
}else{
$nama=$this->upload->data('file_name');
$this->db->where('id', $userId);
$this->db->update('foto',array('nama_foto'=>$nama));
redirect('view_ubah_data-profile','refresh');
}
}
}
and the last is view
<div class="col-md-4 col-sm-6 col-xs-12">
<form action="users/updatefoto" method="post" id="updateUserImage">
<div class="text-center">
<img src="<?php echo base_url();?>uploads/images/<?php echo $userData['nama_foto'] ?>" cclass="img-thumbnail" alt="avatar">
<h6>Upload a different photo...</h6>
<input type="file" class="text-center center-block well well-sm" name="gambar" id="files" accept="image/*" required>
<button type="submit" value="Upload" name="submit" class="btn btn-primary">
<i class="fa fa-upload" aria-hidden="true"></i>upload
</button>
</div>
</form>
</div>
Thanks I appreciate any help :)
Here is how I do it.
Edit- Class Construct
class Team extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->load->helper(array('form', 'url'));
$this->load->model('team_model');
}
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile1'))
{
$data['errors'] = array('error' => $this->upload->display_errors());
$data['client_Id']=$this->team_model->getUserId($email);
$data['pic']=$this->team_model->getImage($data['client_Id']['id']);
// Here I load my Views
}
else
{
$upload_data = $this->upload->data();
$file_name=$upload_data['file_name'];
$email=$this->session->userdata['email'];
$data['client_Id']=$this->team_model->getUserId($email);
$data['pic']=$this->team_model->getImage($data['client_Id']['id']);
// If there is no image insert one other wise update
if($data['pic']['image']!=''){
$this->team_model->updateEmployeeImage($data['pic']['id'],$file_name);
$data['success']='Congratulations! Image Updated Successfully';
}else{
$this->team_model->InsertEmployeeImage($data['client_Id']['id'],$file_name);
$data = array('upload_data' => $this->upload->data());
$data['success']='Congratulations! Image Uploaded Successfully';
}
$file_name=$upload_data['file_name'];
$email=$this->session->userdata['email'];
$data['client_Id']=$this->team_model->getUserId($email);
$data['pic']=$this->team_model->getImage($data['client_Id']['id']);
// Here I load my Views
}
}
}
Edit- Model Functions
public function InsertEmployeeImage($id,$image){
$Image=array(
'id' => '',
'team_id' => $id,
'image' => $image
);
$this->db->insert('teams_image',$Image);
return ;
}
public function updateEmployeeImage($id,$img){
$this->deleteOldImage($id);
$pic=array(
'image' => $img
);
$this->db->WHERE('id',$id)->update('teams_image',$pic);
}
I am upload an image in one my form but its always giving me an error like
"A PHP Error was encountered Severity: Notice Message:
Undefined index: vimage Filename: controllers/vouchers.php Line
Number: 42"
My View File code :
<?php echo form_open_multipart(site_url("promotions/add_item/"), array("class" => "form-horizontal","id"=>"addItem")) ?>
<div class="form-group">
<label class="col-sm-3 control-label">Show on</label>
<div class="col-sm-3">
Artist Directory : <input type="checkbox" name="artist_dir" value='1'>
</div>
<div class="col-sm-3">
Highlight : <input type="checkbox" name="highlight" value='1'>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Title</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="title" id="title" placeholder="Title">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Image</label>
<div class="col-sm-9">
<input type="file" name="pro_image">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
<textarea class="form-control" rows="3" name="description" placeholder="Description"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<button type="submit" class="btn btn-success" name="submit" id="submit">Submit</button>
</div>
</div>
<?php echo form_close() ?>
My Controller Code :
<pre>
public function add_item(){
$this->load->library('upload');
$this->form_validation->set_rules('title','Title','required');
$this->form_validation->set_rules('description','Description','required');
print_r($_FILES['pro_image']);
if ($_FILES['pro_image']['size'] > 0) {
$this->upload->initialize(array(
"upload_path" => './uploads/',
"overwrite" => FALSE,
"encrypt_name" => TRUE,
"remove_spaces" => TRUE,
"allowed_types" => "gif|jpg|png|jpeg",
));
if (!$this->upload->do_upload('vimage')) {
$this->upload->display_errors();
}
$data = $this->upload->data();
echo 'img : '.$img = $data['file_name'];
}
exit;
if($this->form_validation->run()==FALSE){
echo '<div class="alert alert-dismissable alert-danger"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><small>'. validation_errors().'</small></div>';
}
else {
$title = $this->input->post('title');
$description = $this->input->post('description');
$artist_dir = $this->input->post('artist_dir');
$highlight = $this->input->post('highlight');
$this->promotions_model->add_item($title, $description,$artist_dir,$highlight);
}
}
</pre>
please let me know what i am doing wrong here
Try this
if ($_FILES['vimage']['size'] > 0) {
$this->load->library('upload');
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$fileName = $_FILES['vimage']['name'];
private function set_upload_options()
{
// upload an image options
$config = array();
$config['upload_path'] = './upload/'; //give the path to upload the image in folder
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
return $config;
}
For more read this Link
Try this
if (!empty($_FILES['vimage']))
{
$config['upload_path'] = './uploads/';
//$config['max_size'] = '102400';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['overwrite'] = FALSE;
$config['remove_spaces'] = TRUE;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('vimage'))
{
$this->session->set_flashdata('error', $this->upload->display_errors());
//redirect('controller/method');
}
else
{
$this->session->set_flashdata('success', 'Image Has been Uploaded');
//redirect('controller/method');
$img = $data['file_name'];
}
}
Please check first,
print_r(_FILES);
If you get files array then you can use below code for uploading image.
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
// You can give Image formats if you want to upload any video file.
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' = $this->upload->display_errors());
// uploading failed. $error will holds the errors.
}
else
{
$data = array('upload_data' => $this->upload->data());
// uploading successfull, now do your further actions
}
}
I have added your code in my system it's working for fine for me.
public function add(){
$this->load->library('upload');
$this->load->helper('form');
$this->load->helper('url');
print_r($_FILES);die;
$this->form_validation->set_rules('title','Title','required');
$this->form_validation->set_rules('description','Description','required');
if ($_FILES['pro_image']['size'] > 0) {
$this->upload->initialize(array(
"upload_path" => './uploads/',
"overwrite" => FALSE,
"encrypt_name" => TRUE,
"remove_spaces" => TRUE,
"allowed_types" => "gif|jpg|png|jpeg",
));
if (!$this->upload->do_upload('vimage')) {
$this->upload->display_errors();
}
$data = $this->upload->data();
echo 'img : '.$img = $data['file_name'];
}
exit;
if($this->form_validation->run()==FALSE){
echo '<div class="alert alert-dismissable alert-danger"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><small>'. validation_errors().'</small></div>';
}
else {
$title = $this->input->post('title');
$description = $this->input->post('description');
$artist_dir = $this->input->post('artist_dir');
$highlight = $this->input->post('highlight');
$this->promotions_model->add_item($title, $description,$artist_dir,$highlight);
}
}
I'm currently building a portfolio site for a client, and I'm having trouble with one small area. I want to be able to upload multiple images (varying number) inline for each portfolio item, and I can't see an obvious way to do it.
My view.php:
<?php echo form_open_multipart('uploadfile/upload');?>
<fieldset>
<div class="form-group">
<div class="row">
<div class="col-md-12">
<label for="filename[]" class="control-label">Select File to Upload</label>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-12">
<input type="file" name="filename" size="20" />
<span class="text-danger"><?php if (isset($error)) { echo $error; } ?></span>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-12">
<input type="submit" value="Upload File" class="btn btn-primary"/>
</div>
</div>
</div>
</fieldset>
<?php echo form_close(); ?>
<?php if (isset($success_msg)) { echo $success_msg; } ?>
</div>
my controller
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
ini_set("display_errors",1);
class Update_profile extends CI_Controller {
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->is_login();
$this->load->helper(array('form', 'url'));
$this->load->model('Edit_profile');
}
public function index() {
// $this->load->view('header2');
$this->load->view('edit_profile');
}// index function ends
public function is_login() {
$is_login=$this->session->userdata('is_login');
if(!isset($is_login) || $is_login !=true)
{
//don't echo the message from controller
echo "you don't have permission to access this page <a href=../Homecontroller/index/>Login</a>";
die();
}
} //is_login function ends
// function to upload images
function upload()
{
$name_array = array();
$count = count($_FILES['filename']['size']);
foreach($_FILES as $key=>$value)
for($s=0; $s<=$count-1; $s++) {
$_FILES['filename']['name']=$value['name'][$s];
$_FILES['filename']['type'] = $value['type'][$s];
$_FILES['filename']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['filename']['error'] = $value['error'][$s];
$_FILES['filename']['size'] = $value['size'][$s];
//set preferences
$config['remove_spaces']=TRUE;
// $config['encrypt_name'] = TRUE; // for encrypting the name
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'jpg|png|gif';
$config['max_size'] = '10248';
//load upload class library
$this->load->library('upload', $config);
if (!$this->upload->do_upload('filename'))
{
// case - failure
$upload_error = array('error' => $this->upload->display_errors());
$this->load->view('edit_profile', $upload_error);
}
else
{
// case - success
$upload_data = $this->upload->data();
$name_array[] = $data['file_name'];
$data['success_msg'] = '<div class="alert alert-success text-center">Your file <strong>' . $upload_data['file_name'] . '</strong> was successfully uploaded!</div>';
$this->load->view('edit_profile', $data);
}
}
}
function edit_profile() {
//echo "some success";
} //function edit profile ends
}
code above not working
This is what I've used for the last year when I've wanted/needed multiple image uploads in codeigniter:
https://github.com/stvnthomas/CodeIgniter-Multi-Upload