How to many image upload in Codeigniter? - codeigniter

now i'm trying user images(user_pic,background_image) upoload.
but my codes not working.
should i be doing something different? Not really sure what's going wrong.
Here my html code
<form action="<?=base_url();?>edit/up_profile/" method="post" enctype="multipart/form-data">
<input type="file" name="pic_file">
<input type="file" name="pic_bgfile" />
<button type="submit">
my controller code is
if($this->form_validation->run() === false){
}else{
$config = array(
'upload_path' => "./images/u/photo",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => TRUE,
'max_size' => "2048000",
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload',$config);
if($this->upload->do_upload('pic_file')){
$data['profile_image'] = $this->upload->data();
}else if($this->upload->do_upload('pic_bgfile')){
$data['pic_bgfile'] = $this->upload->data();
}
$this->load->model('user_model');
$data = array(
'user_id' => $this->session->userdata('user_id'),
'info_tit' => $this->input->post('info_tit'),
'scope' => $this->input->post('scope')
);
$this->user_model->p_update($data);
//redirect
redirect('/edit/profile/', 'location', 301);
}

You should use CodeIgniter's own upload class instead of using html code.
In the view, or rather, the .html file:
<?php
echo form_open_multipart('user/upload_picture');
?>
<input type="file" name="userfile" />
<br /><br />
<input type="submit" value="submit" />
</form>
Noted that in 'user/upload_picture', 'user' is the name of the controller, 'upload_picture' is the method in 'user'.
In the 'upload_picture' method:
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg';
$config['max_size'] = 0;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['file_name'] = 'Apink.jpg';
$this->load->library('upload', $config);
$this->upload->do_upload();

The View :
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?> <!-- Error Message will show up here -->
<?php echo form_open_multipart('upload_controller/do_upload');?>
<?php echo "<input type='file' name='userfile' size='20' />"; ?>
<?php echo "<input type='submit' name='submit' value='upload' /> ";?>
<?php echo "</form>"?>
</body>
</html>
The Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Upload_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function file_view(){
$this->load->view('file_view', array('error' => ' ' ));
}
public function do_upload(){
$config = array(
'upload_path' => "./uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => TRUE,
'max_size' => "2048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload', $config);
if($this->upload->do_upload())
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success',$data);
}
else
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('file_view', $error);
}
}
}
?>
Note : You can change preferences depending upon the file you wish to upload.
The Page to show uploaded file:
<html>
<head>
<title>Upload File Specification</title>
</head>
<body>
<h3>Your file was successfully uploaded!</h3>
<!-- Uploaded file specification will show up here -->
<ul>
<?php foreach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>
<p><?php echo anchor('upload_controller/file_view', 'Upload Another File!'); ?></p>
</body>
</html>

You can use clear function after first image upload
unset($config);
$this->image_lib->clear();
See CI Manual
https://codeigniter.com/user_guide/libraries/image_lib.html

Related

Show second dependent dropdown without reloading the page

I am trying to build a "price calculator" on my website, to show repair prices for various smartphones.
I already managed to create to dropdowns, the second one only showing after the first one is selected.
After making a choice in the first dropdown, the page reloads and then shows the second one. I would like to achieve the same without reloading the page. This is the code I have so far:
<form method="POST" action="">
<div>
<?php
$args = array(
'hierarchical' => 1,
'depth' => 1,
'orderby' => 'name',
'echo' => 0,
'taxonomy' => 'marke',
// this leads to variable name $_POST['marke']
'name' => 'marke-sel'
);
if( ! isset($_POST['marke-sel']) ):
$args['show_option_none'] = 'Hersteller auswählen';
else:
$args['selected'] = $_POST['marke-sel'];
endif;
$marke = wp_dropdown_categories( $args );
// this enables the buttonless js possibility
$marke = preg_replace("#<select([^>]*)>#", "<select$1 onchange='return this.form.submit()'>", $marke);
echo $marke;
?>
<noscript>
<div>
<input type="submit" value="marke" />
</div>
</noscript>
</div>
</form>
<?php
if( isset($_POST['marke-sel']) && $_POST['marke-sel'] ):
?>
<form method="POST" action="<? bloginfo('url'); ?>">
<input type="hidden" name="marke" value="<?php echo $_POST['marke-sel'] ?>">
<div>
<?php
$the_query = new WP_Query( array(
'post_type' => 'reparaturpreise',
'tax_query' => array(
array (
'taxonomy' => 'marke',
'field' => 'id',
'terms' => $_POST['marke-sel'],
)
),
) );
if ( $the_query->have_posts() ) :
?>
<div class="form-option parent-field-wrapper">
<label for=""></label>
<select name='modell' id='modell' onchange='document.location=this.value'>
<option value="">Modell auswählen</option>
<?php while ( $the_query->have_posts() ) :
$the_query->the_post();
?>
<option value="<?php the_permalink();?>"><?php the_title(); ?></option>
<?php endwhile; ?>
</select>
</div>
<?php endif;
wp_reset_postdata();
$modell = preg_replace("#<select([^>]*)>#", "<select$1 onchange='this.form.submit()'>", $modell);
echo $modell;
?>
<noscript>
<div>
<input type="submit" value="modell" />
</div>
</noscript>
</div>
</form>
<?php endif; ?>
<?php
if( isset($_POST['marke-sel']) && $_POST['modell'] ):
$args = array(
'post_type' => 'reparaturpreise',
'cat' => $_POST['marke-sel'],
'posts_per_page' => 1
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
the_title();
echo '<div class="entry-content">';
the_content();
echo '</div>';
endwhile;
endif;
?>
I finally managed to get it working using this code from here: http://webprow.com/blog/dynamic-dependent-dropdown-categories-posts/
For anyone else looking for a similar solution, this is the code you need to insert in functions.php:
if ( ! class_exists( 'frontendAjaxDropdown' ) ):
class frontendAjaxDropdown {
function __construct() {
add_shortcode( 'ajax-dropdown', array($this, 'init_shortocde') );
add_action( 'wp_ajax_get_subcat', array($this, 'getSubCat') );
add_action('wp_ajax_nopriv_get_subcat', array($this, 'getSubCat') );
}
function init_shortocde()
{ ?>
<div class="ajax-dropdown">
<?php
$args = array(
'name' => 'main_cat',
'id'=> 'main_cat',
'selected' => -1,
'hierarchical' => '1',
'depth' => 1,
'show_option_none' => 'ENTER PLACEHOLDER FOR TAXONOMY HERE',
'option_none_value' => '',
'hide_empty' => 0,
'taxonomy' => 'ENTER YOUR TAXONOMY HERE'
);
wp_dropdown_categories($args);
?>
<script type="text/javascript">
(function($){
$("#main_cat").change(function(){
$("#sub_cat").empty();
$.ajax({
type: "post",
url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data: { action: 'get_subcat', cat_id: $("#main_cat option:selected").val() },
beforeSend: function() {$("#loading").animate({ opacity: 1 });},
success: function(data) {
$("#loading").animate({ opacity: 0 });
$("#sub_cat").append(data);
}
});
});
$("select option[value='']").attr('disabled',"disabled");
$("select option[value='']").attr('selected',"selected");
})(jQuery);
</script>
<div id="loading" style="opacity: 0;">wird geladen...</div>
<div id="sub_cat"></div>
</div>
</div>
<?php }
function getSubCat() {
$cat_id = $_POST['cat_id'];
$args=array(
'post_type' => 'ENTER YOUR CPT HERE',
'tax_query' => array(
array (
'taxonomy' => 'ENTER YOUR TAXONOMY HERE',
'field' => 'id',
'terms' => $cat_id
)
),
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) { ?>
<select name="menu[]" onchange='document.location=this.value'>
<option value="" disabled selected>ENTER PLACEHOLDER FOR CPT HERE</option>
<?php
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<option value="<?php the_permalink();?>" ><?php the_title(); ?> </option>
<?php
endwhile;
wp_die();
?>
</select>
<?php
wp_reset_query();
die();
?> <?php }
}
}
endif;
new frontendAjaxDropdown();
After that, you can place the dropdowns using this shortcode:
<?php echo do_shortcode("[ajax-dropdown]"); ?>

Error Showing on image upload in codeigniter

public function set_news($id = 0)
{
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$name=$_FILES["myimage"]["name"];
$folder="./uploads/";
$imageFileType = strtolower(pathinfo($name,PATHINFO_EXTENSION));
$extensions_arr = array("jpg","jpeg","png");
if( in_array($imageFileType, $extensions_arr) )
{
$data = array(
'title' => $this->input->post('title'), // $this->db->escape($this->input->post('title'))
'date' => $this->input->post('date'),
'slug' => $slug,
'text' => $this->input->post('text'),
'myimage' => $name,
'user_id' => $this->input->post('user_id'),
);
move_uploaded_file($_FILES["myimage"]["tmp_name"], "$folder".$_FILES["myimage"]["name"]);
}
// else
// {
// echo "<script>alert('Image Error');window.history.back(); </script>";
// }
if ($id == 0) {
//$this->db->query('YOUR QUERY HERE');
return $this->db->insert('news', $data);
} else {
$this->db->where('id', $id);
return $this->db->update('news', $data);
}
}
this is my controller file
on uploading image it showing error as follows
A PHP Error was encountered
Severity: Notice
Message: Undefined index: myimage
Filename: models/News_model.php
Line Number: 48
Backtrace:
File: C:\xampp\htdocs\web\codeigniter\application\models\News_model.php
Line: 48
Function: _error_handler
File: C:\xampp\htdocs\web\codeigniter\application\controllers\News.php
Line: 123
Function: set_news
File: C:\xampp\htdocs\web\codeigniter\index.php
Line: 315
Function: require_once
Seems you missed to set the input name as "myimage". Here is the complete codeigniter image upload code(As Mention on their Documentation).
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
</body>
</html>
Controller Code:
class Upload extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
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('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$uploadData= array(
'title' => TITLE,
'date' => date("Y-m-d H:i:s"),
'slug' => SLUG,
'text' => TEXT,
'myimage' => FILE_NAME,
'user_id' => USER_ID,
);
$this->db->insert('mytable', $uploadData);
$this->load->view('upload_success', $data);
}
}
}

form_validation not working where everything in ok in my code, Kindly help me

autoload:
$autoload['libraries'] = array('database','form_validation');
controller:
class Adminlogin extends CI_controller
{
public function new_user()
{
$this->form_validation->set_rules('name','name','required');
$this->form_validation->set_rules('email','email','required|valid_email');
$this->form_validation->set_rules('password','password','required|min_length[8]|max_length[15]');
if ($this->form_validation->run())
{
$Name = $this->input->POST('name');
$Email = $this->input->POST('email');
$Password = $this->input->POST('password');
$data = array('Name' => $Name, 'Email' => $Email, 'Password' => $Password);
$this->load->model('login_model');
$this->login_model->newuser_data($data);
//redirect('public/login_form');
$data['message'] = 'Data Inserted Successfully';
}
else
{
echo "not done";
}
}
if I remove condition from validation then form works and data in traveled and when I apply condition on validation then form not working data is also not traveling without showing any error.
model:
public function newuser_data($data)
{
$this->db->insert('users', $data);
$query = $this->db->insert_id();
}
view:
<?php echo form_open('adminlogin/new_user'); ?>
<div class="col-md-4">
<center><h3>Create User!</h3>
<div class="form-group">
<?php echo form_input(['type'=>'name','name'=>'name','placeholder'=>'Name','class'=>'form-control contact-form','value'=>set_value('name')]) ?>
<?php echo form_error('name'); ?>
</div>
<div class="form-group">
<?php echo form_input(['type'=>'email','name'=>'email','placeholder'=>'Email','class'=>'form-control contact-form','value'=>set_value('Email')]) ?>
<?php echo form_error('email'); ?>
</div>
<div class="form-group">
<?php echo form_input(['type'=>'Password','name'=>'password','placeholder'=>'Password','class'=>'form-control contact-form','value'=>set_value('Password')]) ?>
<?php echo form_error('password'); ?>
</div>
<div class="form-group text-right button-submit btn-submit">
<?php echo form_submit(['name'=>'submit','value'=>'Login','class'=>'btn btn-primary']) ?>
</div>
</div>
class Adminlogin extends CI_controller
{
public function new_user()
{
$this->form_validation->set_rules('name','name','required');
$this->form_validation->set_rules('email','email','required|valid_email');
$this->form_validation->set_rules('password','password','required|min_length[8]|max_length[15]');
if ($this->form_validation->run()!=FALSE)
{
$Name = $this->input->POST('name');
$Email = $this->input->POST('email');
$Password = $this->input->POST('password');
$data = array('Name' => $Name, 'Email' => $Email, 'Password' => $Password);
$this->load->model('login_model');
$this->login_model->newuser_data($data);
//redirect('public/login_form');
$data['message'] = 'Data Inserted Successfully';
}
else
{
echo "not done";
}
}
Change in if condition
if ($this->form_validation->run())
to
if ($this->form_validation->run()!=FALSE)
change this to
if ($this->form_validation->run())
to
if ($this->form_validation->run() != FALSE)
Read - Form Validation in codeigniter.com
Change your line
if ($this->form_validation->run())
to
if ($this->form_validation->run()===TRUE)
Change your statement
From
if ($this->form_validation->run())
To
if ($this->form_validation->run() == TRUE)
OR
if ($this->form_validation->run() != FALSE)
Try using this controller
class Adminlogin extends CI_controller
{
public function new_user()
{
$this->form_validation->set_rules('name','name','required');
$this->form_validation->set_rules('email','email','required|valid_email');
$this->form_validation->set_rules('password','password','required|min_length[8]|max_length[15]');
if ($this->form_validation->run()===FALSE)
{
echo 'Not done';
}
else
{
$Name = $this->input->POST('name');
$Email = $this->input->POST('email');
$Password = $this->input->POST('password');
$data = array('Name' => $Name, 'Email' => $Email, 'Password' => $Password);
$this->load->model('login_model');
$this->login_model->newuser_data($data);
$data['message'] = 'Data Inserted Successfully';
}
}

can't upload image codeigniter no error

I have a problem while uploading image files.
This my view file contents
<form action="<?php base_url()."profile/upload"?>" method="POST" enctype="multipart/form-data" >
<input type="hidden" name="id_akun" value="<?php echo $query->id_akun?>"size="20" />
<input type="file" name="userfile" required>
<input type="submit" name="submit" value="Upload" class="btn btn-success" />
</form>
Here is my controller (profile)
public function upload() {
$config = array(
'upload_path' => dirname($_SERVER["SCRIPT_FILENAME"])."/upload/",
'upload_url' => base_url()."upload/",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => false,
'max_size' => "2048000",
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload', $this->config);
if($this->upload->do_upload()) {
echo "file upload success";
} else {
echo "file upload failed";
}
}
When I try an upload, the image did not get upload, and there is no error shown. URL in my address bar looks like this
http://localhost/mataramtest/profile?id_akun=6&userfile=1.PNG&submit=Upload
There are several issues on your code. Revised and given below
public function upload()
{
$config = array(
'upload_path' => "./upload/",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => false,
'max_size' => "2048000",
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload', $config);
if($this->upload->do_upload('userfile'))
{
echo "file upload success";
}
else
{
echo "file upload failed";
}
}
In view file
<form action="<?php echo site_url("profile/upload");?>" method="POST" enctype="multipart/form-data" >
<!--rest of the code is ok-->
public function img_upload()
{
$config = array(
'upload_path' => "uploads",
'allowed_types' => "*",
'overwrite' => TRUE,
'max_size' => "5048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
'max_height' => "3000",
'max_width' => "3000"
);
$this->upload->initialize($config);
$this->load->library('upload', $config);
if($this->upload->do_upload()) {
$response = array('upload_data' => $this->upload->data());
}
else{
$error = array('error'=>$this->upload->display_errors());
print_r($error);
}
}

Save Image Name And Post Data Into Database

I am working on a project where volunteers have to fill in registration form.
I want volunteers to be able to upload a profile image and save image name to database as well as the post data on the same form.
How can I achieve that?
In the success part of upload form could do a if statement like below for update
Update
$user_info = $this->get_user();
if ($user_info) {
$image_info = $this->upload->data();
$data = array(
'username' => $user_info['username'],
'image' => $image_info['file_name']
);
// Only updates password if post value true
if(isset($_POST['password'])) {
$data = array(
'password' => $this->input->post('password');
);
}
$this->db->where('id', $user_info['id']);
$this->db->update('tablename', $data);
}
Else In the success part of upload form could do insert like below
Insert
$image_info = $this->upload->data();
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
'image' => $image_info['file_name']
);
$this->db->insert('tablename', $data);
Upload Controller
<?php
class Upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0'; // Unlimited
$config['max_width'] = '0'; // Unlimited
$config['max_height'] = '0'; // Unlimited
$this->load->library('upload', $config);
// Alternately you can set preferences by calling the initialize function. Useful if you auto-load the class:
$this->upload->initialize($config);
$input_name = "userfile";
if ( ! $this->upload->do_upload($input_name))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$user_info = $this->get_user();
if ($user_info) {
$image_info = $this->upload_data();
$data = array(
'username' => $user_info['username'],
'image' => $image_info['file_name']
);
$this->db->where('id', $user_info['id']);
$this->db->update('tablename', $data);
}
$this->load->view('upload_success', $data);
}
}
public function get_user() {
// your user model data
}
}
?>
View
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<input type="text" name="name"/>
<input type="password" name="password"/>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
</body>
</html>
Upload library
Codeigniter 2 http://www.codeigniter.com/userguide2/libraries/file_uploading.html
Codeigniter 3 http://www.codeigniter.com/user_guide/libraries/file_uploading.html
your question is not clear ,
provide ,view ,controller as well.
anyways see this post it will help you.
click here
or
use <?php echo form_open_multipart('yourcontroler/add');?>
in your view file when dealing with image and text data.
in controller ,the best practice is to define two function one for image upload the other to validate ,and filter data.Like
public function do_upload() {
$path = '_assets/images/';
$fileName = 'userpic.png';
$config = array(
'allowed_types' => 'jpg|png|gif',
'upload_path' => $path,
'max_size' => '200',
'overwrite' => true,
'file_name' => $fileName,
'max_height' => "300",
'max_width' => "300",
);
$this->load->library('upload', $config);
if (!$this->upload->do_upload('logo')) {
echo "error ";
die;
} else {
$imageData = $this->upload->data();
}
}
and for data storing use simple function you usually do with form input.

Resources