I have an upload_images function
$config['upload_path'] = './uploads/individual_stands/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['overwrite'] = FALSE;
This config is passed to upload_images function.
function upload_images($config, $files, $name) {
if (!file_exists($config['upload_path'])) {
mkdir($config['upload_path'], 0777, true);
}
$this->load->library('upload', $config);
$filesCount = count($files[$name]['name']);
for ($i = 0; $i < $filesCount; $i++) {
$_FILES = array();
$_FILES['image']['name'] = $files[$name]['name'][$i];
$_FILES['image']['type'] = $files[$name]['type'][$i];
$_FILES['image']['tmp_name'] = $files[$name]['tmp_name'][$i];
$_FILES['image']['error'] = $files[$name]['error'][$i];
$_FILES['image']['size'] = $files[$name]['size'][$i];
$this->upload->initialize($config);
if ($this->upload->do_upload('image')) {
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] = $fileData['file_name'];
image_resizing($config['upload_path'] . $fileData['file_name'], $fileData['file_name'] . '_250x250', $config['upload_path'], '250', TRUE, '250');
}
}
if (!empty($uploadData)) {
$data = array(
'status' => 'success',
'images' => $uploadData
);
} else {
$data = array(
'status' => 'error',
'error' => $this->upload->display_errors()
);
}
return $data;
}
And I have a helper function called 'image_resizing'. I am passing the correct parameters inside my helper function but neither the thumb directory is being created, nor the images are being resized.
function image_resizing($imageObj, $fileName, $path = '', $width = 0, $create_thumb = TRUE, $height = 0) {
$newdir = $path. 'thumb/';
if (!file_exists($newdir)) {
mkdir($path, 0777, true);
}
$CI = & get_instance();
$config['image_library'] = 'gd2';
$config['source_image'] = $imageObj;
$config['new_image'] = $path . 'thumb/' . $fileName;
$config['create_thumb'] = $create_thumb;
$config['maintain_ratio'] = TRUE;
if ($width != 0)
$config['width'] = $width;
if ($height != 0)
$config['height'] = $height;
$CI->load->library('image_lib', $config);
$CI->image_lib->initialize($config);
if (!$CI->image_lib->resize()) {
return FALSE;
} else {
return TRUE;
}
}
Related
My controller function is
public function add() {
$blog_title = $this->input->post("qes_blog_title");
$description = htmlentities($_POST['qes_blog_description']);
$edit_status = $this->input->post("edit");
$filename = $blog_title . date('ymdhis');
if ($this->session->userdata('user_type') == "SA") {
$dirname = (dirname(dirname(dirname(__FILE__)))) .
'/uploads/blog/admin';
$usertype = "1";
} else {
$dirname = (dirname(dirname(dirname(__FILE__)))) . '/uploads/blog/'
. $this->session->userdata('user_id');
$usertype = "0";
}
if (!file_exists($dirname)) {
mkdir($dirname, 0777, true);
}
$config['upload_path'] = $dirname;
$config['file_name'] = $filename;
$config['allowed_types'] = 'jpeg|jpg|png';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload("qes_blog_image")) {
//print_r($this->upload->display_errors());
$data = array(
'qes_blog_title' => $blog_title,
'qes_blog_description' => $description,
'qes_vendor_id' => $this->session->userdata('user_id'),
'qes_user_type' => $usertype,
'qes_created_at' => date('Y-m-d H:i:s')
);
} else {
if ($edit_status) {
$condition = array(
'qes_vendor_blog_id' => $edit_status
);
$categoryDetails = $this->common_model->get_row($condition, $this->tablename);
if ($categoryDetails->qes_category_image != NULL) {
if ($this->session->userdata('user_type') == "SA") {
unlink((dirname(dirname(dirname(__FILE__)))) . '/uploads/blog/admin/' . $categoryDetails->qes_blog_image);
} else {
unlink((dirname(dirname(dirname(__FILE__)))) . '/uploads/blog/' . $categoryDetails->qes_vendor_id . "/" . $categoryDetails->qes_blog_image);
}
}
}
$uploqes_data = $this->upload->data();
$uploqes_filename = $uploqes_data['file_name'];
$data = array(
'qes_blog_title' => $blog_title,
'qes_blog_description' => $description,
'qes_vendor_id' => $this->session->userdata('user_id'),
'qes_user_type' => $usertype,
'qes_blog_image' => $uploqes_filename,
'qes_created_at' => date('Y-m-d H:i:s')
);
}
$condition = array(
'qes_blog_title' => $blog_title
);
$blog_details = $this->common_model->get_row($condition, $this->tablename);
if ($edit_status) {
if (count($blog_details) > 0) {
if ($blog_details->qes_blog_title == $blog_title) {
$condition = array(
'qes_vendor_blog_id' => $edit_status
);
$result = $this->common_model->update_row($data, $condition, $this->tablename);
$status = 'Blog "<b>' . $blog_title . '</b>" Successfully Updated';
} else {
$htm = "0";
$result = "0";
$status = "0";
}
} else {
$condition = array(
'qes_vendor_blog_id' => $edit_status
);
$result = $this->common_model->update_row($data, $condition, $this->tablename);
$status = 'Blog "<b>' . $blog_title . '</b>" Successfully Updated';
}
} else {
if (count($blog_details) > 0) {
if ($blog_details->qes_blog_title == $blog_title) {
$htm = "0";
$result = "0";
$status = "0";
} else {
$result = $this->common_model->insert_data($this->tablename, $data);
$status = 'Blog "<b>' . $blog_title . '</b>" Successfully Created';
}
} else {
$result = $this->common_model->insert_data($this->tablename, $data);
$status = 'Blog "<b>' . $blog_title . '</b>" Successfully Created';
}
}
if ($result) {
$htm = $result;
$this->session->set_flashdata('success_msg', $status);
} else {
$htm = '0';
$this->session->set_flashdata('success_msg', 'Error While Creating Parent');
}
echo $htm;
}
I'm a beginner in Codeigniter.
How to restrict the size of image while uploading. Only images of specific size can be uploaded. The above is the controller function to add blog. How to specify the size in the above code. How to keep a condition like "upload image only of the specified size" while uploading image in Codeigniter?
Please refer this code, this may help you..thanks!
$file_name = '';
$error = '';
if ($_FILES['image']['name'] != '') {
$config['upload_path'] = 'uploads/blog/main/';
$config['allowed_types'] = 'jpg|png|jpeg';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('image')) {
$error = $this->upload->display_errors();
} else {
$data = array('upload_data' => $this->upload->data());
$file_name = $data['upload_data']['file_name'];
$config['source_image'] = 'uploads/blog/main/' . $file_name;
$config['new_image'] = 'uploads/blog/thumb/' . $file_name;
$config['width'] = 172;
$config['height'] = 122;
$config['maintain_ratio'] = FALSE;
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
if ($data['upload_data']['image_height'] > $this->main_height || $data['upload_data']['image_width'] > $this->main_width) {
$config['image_library'] = 'gd2';
$config['source_image'] = 'uploads/blog/main/' . $file_name;
$config['new_image'] = 'uploads/blog/main/' . $file_name;
$config['width'] = $this->main_width;
$config['height'] = $this->main_height;
$config['maintain_ratio'] = FALSE;
$this->image_lib->initialize($config);
$this->image_lib->resize();
}
}
}
instead of copy pasting the raw code , let me give you the sample for each actions you like to do with image uploading in php. so that you can make us of any of below to achieve your result.
1. To check if image is received or not. use,
if(isset($_FILES["image"])){
// image received
} else {
// image not received
}
2. To check if the image is properly uploaded or not. use,
if ($_FILES['image']['error'] !== UPLOAD_ERR_OK) {
// error
die("Upload failed with error code " . $_FILES['image']['error']);
} else {
// no error
}
3. To check if your image is in valid format. use,
$info = getimagesize($_FILES['image']['tmp_name']);
if ($info === FALSE) {
//Unable to determine image type of uploaded file
}
if (($info[2] !== IMAGETYPE_GIF) && ($info[2] !== IMAGETYPE_JPEG) && ($info[2] !== IMAGETYPE_PNG)) {
// File received is not in valid format
}
4. to get size of the image, use above method and as well as,
$width = $info[0];
$height = $info[1];
4.1 To check if image is square,
if($width!=$height) {
//Image is not square
}
4.1 To check minimum pixel image width
if($width<50) { // Image width should be atleast 50 pixel }
you can play with conditional statement to receive the required image size you are looking for.
To upload the image ( not exactly need to be in below format, modify it according to the need ),
$imagename=($_FILES["image"]["tmp_name"]);
$filename = $_FILES['image']['name'];
$temp = explode(".",$_FILES["image"]["name"]);
$filename = rand(1,99999).'.'.end($temp);
move_uploaded_file($_FILES["image"]["tmp_name"], "../your_path/" . $filename);
Edit
If you want to restrict the image size to a specific width and height, set both minimum and maximum of width and height to the same value in the config. For eg. to restrict image size to 1024x768, you can set the preferences in config as follows
$config['min_width'] = '1024'; // restrict width to 1024px
$config['min_height'] = '768'; // restrict height to 768px
$config['max_width'] = '1024'; // restrict width to 1024px
$config['max_height'] = '768'; // restrict height to 768px
$this->load->library('upload', $config); // pass the config when loading the library
If you use autoload, pass the config to the initialize method.
$this->upload->initialize($config);
Side note:
I see that you are passing the config while loading the library and then also initializing. This is redundant. initialize method is used if you are using the autoload feature.
I want to crop my image upload and change my profile photo, but I don't know why it's not working even the picture was upload, profile picture not change, you must logout and picture was be change. this is my controller.
private $pk = 'nim';
private $table = 'mahasiswa';
public function update()
{
$nim = $this->session->userdata('nim');
if($_POST) {
$file = $this->upload();
if ($this->m_data->update($this->pk, $nim, $this->table, $this->field_data($file['data']))) {
redirect('Mahasiswa/Profil');
}
} else {
redirect('Mahasiswa/Formubah');
}
}
private function field_data($file = '')
{
$data['username'] = $this->input->post('username');
$data['password'] = $this->input->post('password');
if ($file != '') {
$data['foto'] = $file['file_name'];
}
return $data;
}
public function upload()
{
$config['upload_path'] = './assets/image/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 0;
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('foto')){
return[
'data' => $this->upload->display_errors(),
];
} else {
$data = $this->upload->data();
$resize['image_library'] = 'gd2';
$resize['x_axis'] = 50;
$resize['y_axis'] = 50;
$resize['width'] = $img['config']['foto']['width'];
$this->image_lib->initialize($resize);
$this->image_lib->crop();
return [
'data' => $this->upload->data(),
];
}
}
i hope controller was enough. i forgot to tell, i use this show my picture. <?php echo base_url('assets/image/').$this->session->userdata('foto');?>
You are not properly implementing the library. Y forgot the library load and have not given its path.
$image_data = $this->upload->data();
$config['image_library'] = 'imagemagick';
$config['library_path'] = 'C:ImageMagick-7.0.1-3-portable-Q16-x86';//your library
$config['source_image'] = $image_data['full_path']; //get original image
$config['x_axis'] = 50;
$config['y_axis'] = 50;
$this->load->library('image_lib', $config);
if (!$this->image_lib->crop()) {
$this->handle_error($this->image_lib->display_errors());
}
i want to upload several image with different input and different field name for each image. i actually try to separate it in two different method like this
public function tambahketua(){
if(isset($_POST["reg"]))
{
$config['upload_path'] = './asset/img/foto/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf|doc|xml|docx|GIF|JPG|PNG|JPEG|PDF|DOC|XML|DOCX|xls|xlsx';
$config['max_size'] = 200048;
$config['file_name'] = $this->input->post("namaketua");
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('attachment'))//ini name di input choose file
{
}
else
{
$datas = $this->upload->data();
$edit['image_library'] = 'gd2';
$edit['source_image'] = './asset/img/foto/'.$datas['file_name'];
$edit['create_thumb'] = TRUE;
$edit['maintain_ratio'] = TRUE;
$edit['height'] = 600;
$this->load->library('image_lib', $edit);
$this->image_lib->resize();
$edit_file = explode('.', $datas['file_name']);
$data['foto'] = $edit_file[0].'_thumb.'.$edit_file[1];
unlink($config['upload_path'].$datas['file_name']);
}
$a = $this->miniatur_model->insertPeserta($data);
if($a){
$this->tambahanggota1();
}
else{
echo "failed";
}
}
$this->load->view('pendaftaran');
}
public function tambahanggota1(){
if(isset($_POST["reg"]))
{
$config['upload_path'] = './asset/img/foto/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf|doc|xml|docx|GIF|JPG|PNG|JPEG|PDF|DOC|XML|DOCX|xls|xlsx';
$config['max_size'] = 200048;
$config['file_name'] = $this->input->post("namaanggota1");
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('fotoktmanggota1'))//ini name di input choose file
{
}
else
{
$datas = $this->upload->data();
$edit['image_library'] = 'gd2';
$edit['source_image'] = './asset/img/foto/'.$datas['file_name'];
$edit['create_thumb'] = TRUE;
$edit['maintain_ratio'] = TRUE;
$edit['height'] = 600;
$this->load->library('image_lib', $edit);
$this->image_lib->resize();
$edit_file = explode('.', $datas['file_name']);
$data['foto'] = $edit_file[0].'_thumb.'.$edit_file[1];
unlink($config['upload_path'].$datas['file_name']);
}
$a = $this->miniatur_model->insertPeserta($data);
if($a){
echo "success";
}
else{
echo "failed";
}
}
$this->load->view('pendaftaran');
}
and so far i could only write both of the image name into my database, but only the first one uploaded into my folder.
and this is my view
<input type="file" id="attachment" name="attachment">
<input type="file" id="fotoktmanggota1" name="fotoktmanggota1">
and for some reason i cant change the name of my files into array like name="attachment[]"
I have minimized your extra code. Try this and do your own magic if I missed something.
function tambahketua() {
if (isset($_POST["reg"])) {
$config['upload_path'] = './asset/img/foto/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf|doc|xml|docx|GIF|JPG|PNG|JPEG|PDF|DOC|XML|DOCX|xls|xlsx';
$config['max_size'] = 200048;
$this->upload->initialize($config);
if (!$this->upload->do_upload('attachment')) {
$error = array('error' => $this->upload->display_errors());
// var_dump($error);
} else {
$fileData = $this->upload->data();
$data['foto'] = $fileData['file_name'];
$this->doResize($fileData['file_name']);
}
$insertedFirstImage = $this->miniatur_model->insertPeserta($data);
if ($insertedFirstImage) {
// Upload Second Image on Success
if (!$this->upload->do_upload('fotoktmanggota1')) {
$error = array('error' => $this->upload->display_errors());
} else {
$fileData = $this->upload->data();
$data['foto'] = $fileData['file_name'];
$this->doResize($fileData['file_name']);
}
$insertedSecondImage = $this->miniatur_model->insertPeserta($data);
/*---------------------------------------*/
} else{
echo "Image insertion Failed in database";
}
}
$this->load->view('pendaftaran');
}
function doResize($filename) {
$sourcePath = './asset/img/foto/' . $filename;
$targetPath = './asset/img/foto/thumb/thumb_' . $filename;
$config_manip = array(
'image_library' => 'gd2',
'source_image' => $sourcePath,
'new_image' => $targetPath,
'maintain_ratio' => true,
'width' => 150,
'height' => 150
);
$this->image_lib->initialize($config_manip);
$this->load->library('image_lib', $config_manip);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
exit;
}
// clear //
// $this->image_lib->clear();
}
<?php
public function videoupld()
{
$this->load->helper('string');
$config['upload_path'] = 'assets/upload/video'; # check path is correct
$config['max_size'] = '102400000';
$config['allowed_types'] = 'mp4'; # add video extenstion on here
$config['overwrite'] = FALSE;
$config['remove_spaces'] = TRUE;
$video_name =$_FILES['video_image']['name'];`
$config['file_name'] = $video_name;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('video_image'))
{
echo 'fail';
return;
//redirect('Admin/video_upload');
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
$url = 'assets/upload/video'.$video_name;
$this->Admin_model->videoupld($url);
redirect('Admin/video_upload');
}
}
?>
model
public function videoupld($url)
{
$title = $this->input->post('video_image');
//$details = $this->input->post('details');
//$type = $this->input->post('gallery');
$data = array(
'title' => $title,
'url' => $url,
//'category' => $type`
);
$this->db->insert('videoss', $data);
}
$uploaded = $this -> upload -> do_upload('video_image');
//here you will receive the object that you uploaded
// you will test if the file exist if yes the variable $file will recieve the full path
if ($uploaded) {
if ($data['file_ppt'] != '') {
$file = 'uploads/ppt/' . $data['file_ppt']; //full path
if (file_exists($file)) {
unlink($file);
}
}
}
//if file uploaded
//$save['file_ppt'] will have the name of the file uploaded
if ($uploaded) {
$file_ppt = $this -> upload -> data();
$save['file_ppt'] = $file_ppt['file_name'];
}
$uploaded = $this -> upload -> do_upload('video_image');
if ($uploaded) {
if ($data['file_ppt'] != '') {
$file = 'uploads/ppt/' . $data['file_ppt'];
if (file_exists($file)) {
unlink($file);
}
}
}
if ($uploaded) {
$file_ppt = $this -> upload -> data();
$save['file_ppt'] = $file_ppt['file_name'];
}
$this->db->insert('videoss', $save);
put this in the view :
and in controller : $names ="";
$name_array = array();
if(isset($_FILES['file_ppt'])){
$count = count($_FILES['file_ppt']['size']);
}else{
$count=0;
}
foreach($_FILES as $key=>$value)
for($s=0; $s<=$count-1; $s++) {
$_FILES['file_ppt']['name']=md5(time())."".$value['name'][$s];
$_FILES['file_ppt']['type'] = $value['type'][$s];
$_FILES['file_ppt']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['file_ppt']['error'] = $value['error'][$s];
$_FILES['file_ppt']['size'] = $value['size'][$s];
// $config['allowed_types'] = 'gif|jpg|png';
$config['upload_path'] = 'uploads/messages';
$config['allowed_types'] = '*';
$config['max_size'] = '200000';
$this->load->library('upload', $config);
$uploaded = $this->upload->do_upload('file_ppt');
$data = $this->upload->data();
$names = $names.','.$_FILES['file_ppt']['name'];
}
if ($uploaded) {
// $file_ppt = $this -> upload -> data();
$save['file_ppt'] = $names;
// print_r('file ppt'.$file_ppt['file_name']);
}else {
echo $this->upload->display_errors();
}
I am trying to upload an image.
Here is the code
<?php
$PerpetualCalendar = $this->input->post();
if($files['imgQuarter1']['name'][$key]!="")
{
$_FILES['imgQuarter1']['name']= $files['imgQuarter1']['name'][$key];
$_FILES['imgQuarter1']['type']= $files['imgQuarter1']['type'][$key];
$_FILES['imgQuarter1']['tmp_name']= $files['imgQuarter1']['tmp_name'][$key];
$_FILES['imgQuarter1']['error']= $files['imgQuarter1']['error'][$key];
$_FILES['imgQuarter1']['size']= $files['imgQuarter1']['size'][$key];
if(isset($PerpetualCalendar['id1'][$key]))
{
$img_id=$PerpetualCalendar['id1'][$key];
}
else
{
$img_id=$GetLastID;
}
$fileName = $img_id.'_NAME_'. $files['imgQuarter1']['name'][$key];
$config['file_name'] = $fileName;
$this->upload->initialize($config);
if($this->upload->do_upload('imgQuarter1'))
{
if(isset($PerpetualCalendar['NAMEpath_idQ1'][$key])){
$ImgUpdate[$imgkey]['tbl_name']='perpetual_calendar';
$ImgUpdate[$imgkey]['field_name']='event_name';
$ImgUpdate[$imgkey]['user_FK']=$user_id;
$ImgUpdate[$imgkey]['path']=$uploadpath.'/'.$fileName;
$ImgUpdate[$imgkey]['entry_id']=$img_id;
$ImgUpdate[$imgkey]['path_id']=$PerpetualCalendar['NAMEpath_idQ1'][$key]; //for update purpose
}else{
$ImgInsert[$imgkey]['tbl_name']='perpetual_calendar';
$ImgInsert[$imgkey]['field_name']='event_name';
$ImgInsert[$imgkey]['user_FK']=$user_id;
$ImgInsert[$imgkey]['path']=$uploadpath.'/'.$fileName;
$ImgInsert[$imgkey]['entry_id']=$img_id;
}
$imgkey++;
}
else
{
$this->data['error'] = $this->session->set_flashdata(array('error' => $this->upload->display_errors()));
}
}
?>
here is the View
echo form_upload(array('name'=>'imgQuarter1['.$key.']','class'=>'default'),'');
echo form_input(array('name' => 'id1['.$key.']', 'type'=>'hidden','value'=>$ValuePerpetualCalendar['cal_id']));
in above code,i can get $PerpetualCalendar['id1'][$key] this Id,but
image can not upload in the folder and can't save in Database Aswell !
Any Help?
public function upload_multiple_image($user_id){
$image = $_FILES['image']['name'];
$files = $_FILES['image'];
$image_title = $this->input->post('image_title');
$image_link = $this->input->post('image_link');
foreach($image as $key=>$data){
if($files['name'][$key]!=""){
$add_data['user_id'] = $user_id;
$add_data['title'] = $image_title[$key];
$add_data['description'] = $image_link[$key];
$add_data['status'] = 1;
$this->db->insert('user_images',$add_data);
$last_inserted_id = $this->db->insert_id();
$_FILES['image']['name'] = $files['name'][$key];
$_FILES['image']['type'] = $files['type'][$key];
$_FILES['image']['tmp_name'] = $files['tmp_name'][$key];
$_FILES['image']['error'] = $files['error'][$key];
$_FILES['image']['size'] = $files['size'][$key];
$config['upload_path'] = './user_images/original/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['overwrite'] = TRUE;
$config['file_name'] = 'place_image_'.$last_inserted_id;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('image')){
$file_details = $this->upload->data();
$update_data = array('image'=>$file_details['file_name']);
$this->db->update('user_images',$update_data,array('id'=>$last_inserted_id));
}
}
}
}