This question already has answers here:
Multiple files upload in Codeigniter
(5 answers)
Closed 8 months ago.
I have inilabs school management script, working fine. But I'm trying to modify. I want to upload more than one image in database
Here is add.php
' <?php
if(isset($image))
echo "<div class='form-group has-error' >";
else
echo "<div class='form-group' >";
?>
<label for="photo" class="col-sm-2 control-label col-xs-8 col-md-2">
<?=$this->lang->line("student_photo")?>
</label>
<div class="col-sm-4 col-xs-6 col-md-4">
<input class="form-control" id="uploadFile1" placeholder="Choose File" disabled />
</div>
<div class="col-sm-2 col-xs-6 col-md-2">
<div class="fileUpload btn btn-success form-control">
<span class="fa fa-repeat"></span>
<span><?=$this->lang->line("upload")?></span>
<input id="uploadBtn1" type="file" class="upload" name="image" />
</div>
</div>
<span class="col-sm-4 control-label col-xs-6 col-md-4">
<?php if(isset($image)) echo $image; ?>
</span>
</div>
<?php
if(isset($imageaadhar))
echo "<div class='form-group has-error' >";
else
echo "<div class='form-group' >";
?>
<label for="aadhar" class="col-sm-2 control-label col-xs-8 col-md-2">
<?=$this->lang->line("student_aadhar")?>
</label>
<div class="col-sm-4 col-xs-6 col-md-4">
<input class="form-control" id="uploadFile2" placeholder="Choose File" disabled />
</div>
<div class="col-sm-2 col-xs-6 col-md-2">
<div class="fileUpload btn btn-success form-control">
<span class="fa fa-repeat"></span>
<span><?=$this->lang->line("upload")?></span>
<input id="uploadBtn2" type="file" class="upload" name="imageaadhar" />
</div>
</div>
<span class="col-sm-4 control-label col-xs-6 col-md-4">
<?php if(isset($imageaadhar)) echo $imageaadhar; ?>
</span>
</div>
<?php
if(isset($imagebirthc))
echo "<div class='form-group has-error' >";
else
echo "<div class='form-group' >";
?>
<label for="birthc" class="col-sm-2 control-label col-xs-8 col-md-2">
<?=$this->lang->line("student_birthc")?>
</label>
<div class="col-sm-4 col-xs-6 col-md-4">
<input class="form-control" id="uploadFile3" placeholder="Choose File" disabled />
</div>
<div class="col-sm-2 col-xs-6 col-md-2">
<div class="fileUpload btn btn-success form-control">
<span class="fa fa-repeat"></span>
<span><?=$this->lang->line("upload")?></span>
<input id="uploadBtn3" type="file" class="upload" name="image" />
</div>
</div>
<span class="col-sm-4 control-label col-xs-6 col-md-4">
<?php if(isset($imagebirthc)) echo $imagebirthc; ?>
</span>
</div>'
This is controller/add.php for upload single image. How to modify for upload two more image ?
$classesID = $this->input->post("classesID");
if($classesID != 0) {
$this->data['sections'] = $this->section_m->get_order_by_section(array("classesID" =>$classesID));
} else {
$this->data['sections'] = "empty";
}
$this->data['sectionID'] = $this->input->post("sectionID");
if($_POST) {
$rules = $this->rules();
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() == FALSE) {
$this->data["subview"] = "student/add";
$this->load->view('_layout_main', $this->data);
} else {
$sectionID = $this->input->post("sectionID");
if($sectionID == 0) {
$this->data['sectionID'] = 0;
} else {
$this->data['sections'] = $this->section_m->get_allsection($classesID);
$this->data['sectionID'] = $this->input->post("sectionID");
}
$dbmaxyear = $this->student_m->get_order_by_student_single_max_year($classesID);
$maxyear = "";
if(count($dbmaxyear)) {
$maxyear = $dbmaxyear->year;
} else {
$maxyear = date("Y");
}
$section = $this->section_m->get_section($sectionID);
$array = array();
$array["name"] = $this->input->post("name");
$array["dob"] = date("Y-m-d", strtotime($this->input->post("dob")));
$array["sex"] = $this->input->post("sex");
$array["religion"] = $this->input->post("religion");
$array["email"] = $this->input->post("email");
$array["phone"] = $this->input->post("phone");
$array["address"] = $this->input->post("address");
$array["classesID"] = $this->input->post("classesID");
$array["sectionID"] = $this->input->post("sectionID");
$array["section"] = $section->section;
$array["roll"] = $this->input->post("roll");
$array["username"] = $this->input->post("username");
$array['password'] = $this->student_m->hash($this->input->post("password"));
$array['usertype'] = "Student";
$array['parentID'] = $this->input->post('guargianID');
$array['library'] = 0;
$array['hostel'] = 0;
$array['transport'] = 0;
$array['create_date'] = date("Y-m-d");
$array['year'] = $maxyear;
$array['totalamount'] = 0;
$array['paidamount'] = 0;
$array["create_date"] = date("Y-m-d h:i:s");
$array["modify_date"] = date("Y-m-d h:i:s");
$array["create_userID"] = $this->session->userdata('loginuserID');
$array["create_username"] = $this->session->userdata('username');
$array["create_usertype"] = $this->session->userdata('usertype');
$array["studentactive"] = 1;
$new_file = "";
if($_FILES["image"]['name'] !="") {
$file_name = $_FILES["image"]['name'];
$file_name_rename = $this->insert_with_image($this->input->post("username"));
$explode = explode('.', $file_name);
if(count($explode) >= 2) {
$new_file = $file_name_rename.'.'.$explode[1];
$config['upload_path'] = "./uploads/images";
$config['allowed_types'] = "gif|jpg|png";
$config['file_name'] = $new_file;
$config['max_size'] = '1024';
$config['max_width'] = '3000';
$config['max_height'] = '3000';
$array['photo'] = $new_file;
$this->load->library('upload', $config);
if(!$this->upload->do_upload("image")) {
$this->data["image"] = $this->upload->display_errors();
$this->data["subview"] = "student/add";
$this->load->view('_layout_main', $this->data);
} else {
$data = array("upload_data" => $this->upload->data());
$this->student_m->insert_student($array);
$this->session->set_flashdata('success', $this->lang->line('menu_success'));
redirect(base_url("student/index"));
}
} else {
$this->data["image"] = "Invalid file";
$this->data["subview"] = "student/add";
$this->load->view('_layout_main', $this->data);
}
} else {
$array["photo"] = $new_file;
$this->student_m->insert_student($array);
$this->session->set_flashdata('success', $this->lang->line('menu_success'));
redirect(base_url("student/index"));
}
}
} else {
$this->data["subview"] = "student/add";
$this->load->view('_layout_main', $this->data);
}
} else {
$this->data["subview"] = "error";
$this->load->view('_layout_main', $this->data);
}
}
Help me please
your file name
<input id="uploadBtn3" type="file" class="upload" name="image[]" />
in controller
$files = $_FILES;
$count = count($_FILES['uploadfile']['name']);
for($i=0; $i<$count; $i++)
{
$_FILES['uploadfile']['name']= $files['uploadfile']['name'][$i];
$_FILES['uploadfile']['type']= $files['uploadfile']['type'][$i];
$_FILES['uploadfile']['tmp_name']= $files['uploadfile']['tmp_name'][$i];
$_FILES['uploadfile']['error']= $files['uploadfile']['error'][$i];
$_FILES['uploadfile']['size']= $files['uploadfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());//function defination below
$this->upload->do_upload('uploadfile');
$upload_data = $this->upload->data();
$name_array[] = $upload_data['file_name'];
$fileName = $upload_data['file_name'];
$image[] = $fileName;
}
$fileName = $image;
Related
I have a form where parents can upload files (their child's completed homework) to be received by teachers.
However, I have been getting a lot of complaints that they can't upload files when they use their mobile phones. When they click on the save button, nothing happens.
Thing is when I (superadmin) and teachers upload from our pages using either pc or mobile phones, it uploads without hitches.
Why can't parents upload files, especially with their mobile phones.
I don't know if this is a coding issue or a server issue.
For now, I use a shared cloud hosting with 4 CPU Cores, 4GB DDR4 RAM, Unlimited Bandwidth and Unlimited SSD Space.
model
public function upload_docs($data)
{
$this->db->where('homework_id',$data['homework_id']);
$this->db->where('student_id',$data['student_id']);
$q = $this->db->get('submit_assignment');
if ( $q->num_rows() > 0 )
{
$this->db->where('homework_id',$data['homework_id']);
$this->db->where('student_id',$data['student_id']);
$this->db->update('submit_assignment',$data);
} else {
$this->db->insert('submit_assignment',$data);
}
}
// public function upload_docs($data)
// {
// if (isset($data['id']) && $data['id'] != null) {
// $this->db->where("id", $data["id"])->update("submit_assignment", $data);
// return $data['id'];
// } else {
// $this->db->insert("submit_assignment", $data);
// return $this->db->insert_id();
// }
// }
controller
public function upload_docs()
{
$homework_id = $_REQUEST['homework_id'];
$student_id =$_REQUEST['student_id'];
$data['homework_id'] = $homework_id;
$data['student_id'] = $student_id;
$data['message'] = $_REQUEST['message'];
// $data['id']=$_POST['assigment_id'];
$is_required=$this->homework_model->check_assignment($homework_id,$student_id);
$this->form_validation->set_rules('message', $this->lang->line('message'), 'trim|required|xss_clean');
$this->form_validation->set_rules('file', $this->lang->line('attach_document'), 'trim|xss_clean|callback_handle_upload['.$is_required.']');
if ($this->form_validation->run() == FALSE) {
$msg=array(
'message'=>form_error('message'),
'file'=>form_error('file'),
);
$array = array('status' => 'fail', 'error' => $msg, 'message' => '');
}else{
if (isset($_FILES["file"]) && !empty($_FILES['file']['name'])) {
$time = md5($_FILES["file"]['name'] . microtime());
$fileInfo = pathinfo($_FILES["file"]["name"]);
$img_name = $time . '.' . $fileInfo['extension'];
$data['docs'] = $img_name;
move_uploaded_file($_FILES["file"]["tmp_name"], "./uploads/homework/assignment/" . $data['docs']);
$data['file_name']=$_FILES["file"]['name'];
$this->homework_model->upload_docs($data);
}
$array = array('status' => 'success', 'error' => '', 'message' => $this->lang->line('success_message'));
}
echo json_encode($array);
}
public function handle_upload($str,$is_required)
{
$image_validate = $this->config->item('file_validate');
if (isset($_FILES["file"]) && !empty($_FILES['file']['name']) && $_FILES["file"]["size"] > 0) {
$file_type = $_FILES["file"]['type'];
$file_size = $_FILES["file"]["size"];
$file_name = $_FILES["file"]["name"];
$allowed_extension = $image_validate['allowed_extension'];
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$allowed_mime_type = $image_validate['allowed_mime_type'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mtype = finfo_file($finfo, $_FILES['file']['tmp_name']);
finfo_close($finfo);
if (!in_array($mtype, $allowed_mime_type)) {
$this->form_validation->set_message('handle_upload', 'File Type Not Allowed');
return false;
}
if (!in_array($ext, $allowed_extension) || !in_array($file_type, $allowed_mime_type)) {
$this->form_validation->set_message('handle_upload', 'Extension Not Allowed');
return false;
}
if ($file_size > $image_validate['upload_size']) {
$this->form_validation->set_message('handle_upload', $this->lang->line('file_size_shoud_be_less_than') . number_format($image_validate['upload_size'] / 1048576, 2) . " MB");
return false;
}
return true;
} else {
if($is_required==0){
$this->form_validation->set_message('handle_upload', 'Please choose a file to upload.');
return false;
}else{
return true;
}
}
}
view
<td class="mailbox-date pull-right">
<a onclick="upload_docs('<?php echo $homework['id']; ?>', '<?php echo $upload_docsButton; ?>');" class="btn btn-default btn-xs" data-toggle="tooltip" data-original-title="<?php echo $this->lang->line('homework') . " " . $this->lang->line('assignments'); ?>">
<i class="fa fa-upload"></i></a>
<a class="btn btn-default btn-xs" onclick="evaluation('<?php echo $homework['id']; ?>','<?php echo $hw;?>');" title="" data-target="#evaluation" data-toggle="modal" data-original-title="Evaluation">
<i class="fa fa-reorder"></i></a>
</td>
<div class="modal fade" id="upload_docs" tabindex="-1" role="dialog" aria-labelledby="evaluation" style="padding-left: 0 !important">
<div class="modal-dialog" role="document">
<div class="modal-content modal-media-content">
<div class="modal-header modal-media-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="box-title"><?php echo $this->lang->line('homework'); ?> <?php echo $this->lang->line('assignments'); ?></h4>
</div>
<form id="upload" method="post" class="ptt10" enctype="multipart/form-data">
<div class="modal-body pt0">
<div class="row">
<input type="hidden" name="student_id" value="<?php echo $student_id; ?>">
<input type="hidden" id="homework_id" name="homework_id">
<input type="hidden" id="assigment_id" name="assigment_id">
<div class="col-sm-12">
<div class="form-group">
<label for="pwd"><?php echo $this->lang->line('message'); ?></label>
<textarea type="text" id="assigment_message" name="message" class="form-control "></textarea>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label for="pwd"><?php echo $this->lang->line('attach_document'); ?></label>
<input type="file" id="file" name="file" class="form-control filestyle">
</div>
</div>
<p id="uploaded_docs"></p>
</div>
</div>
<div class="box-footer">
<div class="" id="footer_area">
<button type="submit" class="btn btn-info pull-right" id="submit" data-loading-text="<i class='fa fa-spinner fa-spin '></i> Please wait"><?php echo $this->lang->line('save'); ?></button>
</div>
Your view is mess.
First add form action then add button form attribute like this:
<button type="submit" form="upload" class="btn btn-info pull-right" id="submit" data-loading-text='SOME TEXT'> Please wait<?php echo $this->lang->line('save'); ?></button>
<form id="upload" role="form" method="post" class="ptt10" enctype="multipart/form-data" action="upload_docs">
I was getting an error of undifined index 'shop' when i submit the form bellow, and when i gave submit button a name and tested if it exists (isset) I had a negative response weridly, here's my code:
<?php
session_start();
$data['titre'] = 'Ajouter des médias';
$this->load->view('templates/header',$data);
$this->load->view('templates/navbar');
if(isset($_SESSION['username'])){
global $con;
$userid = getUserId($_SESSION['username']);
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['form_posted'])){
if(isset($_POST['shopid'])) $shop = $_POST['shopid'];
if($_POST['shopid'] == 0){
echo '<div class="alert alert-danger"> Aucune boutique n\'a été choisie!</div>';
}
else
{
if($_FILES['video']['name']!= NULL || $_FILES['images']['name'][0] != NULL){
if(isset($_FILES['images']) && $_FILES['images']['name'][0] != NULL){
$avatarAllowedExtensions = array("jpeg", "jpg", "png", "gif");
$name_array = $_FILES['images']['name'];
$tmp_name_array = $_FILES['images']['tmp_name'];
$type_array = $_FILES['images']['type'];
$size_array = $_FILES['images']['size'];
$error_array = $_FILES['images']['error'];
for($i = 0; $i < count($tmp_name_array) ; $i++){
$exploded_img = explode('.', $name_array[$i]);
$img_Extension = strtolower(end($exploded_img));
if(in_array($img_Extension, $avatarAllowedExtensions)){
$img_name = rand(1000000,10000000). '.' . $img_Extension;
move_uploaded_file($tmp_name_array[$i], "uploads/shops/" . $img_name);
$stmt = $con->prepare("INSERT INTO shop.shop_images (ID_boutique, pic) VALUES (?,?)");
$stmt->execute(array($shop, $img_name));
$insertid = $con->lastInsertId();
$stmt = $con->prepare("INSERT INTO publications ( type, tableid, ID_boutique) VALUES (?,?,?)");
$stmt->execute(array(2, $insertid, $shop));
if($_FILES['video']['name']== NULL){
echo '<div class="alert alert-success">Chargement réussi.</div>';
header('refresh:1.5;url='.base_url("boutiques/store/".$shop."#media"));
}
}
}
}
if(isset($_FILES['video']) && $_FILES['video']['name']!= NULL){
$maxsize = 5242880*3;
$name = $_FILES['video']['name'];
$target_dir = "uploads/videos/";
$videoFileType = strtolower(pathinfo($name,PATHINFO_EXTENSION));
$videoName = rand(1000000,10000000). '.' . $videoFileType;
$target_file = $target_dir . $videoName;
// Select file type
// Valid file extensions
$extensions_arr = array("mp4","avi","3gp","mov","mpeg");
// Check extension
if( in_array($videoFileType,$extensions_arr) ){
// Check file size
if(($_FILES['video']['size'] >= $maxsize) || ($_FILES["video"]["size"] == 0)) {
echo '<div class="alert alert-danger">Vidéo très large, 15MB maximum!</div>';
}else{
if(move_uploaded_file($_FILES['video']['tmp_name'],$target_file)){
// Insert record
global $con;
$stmt = $con->prepare("INSERT INTO shop_videos(ID_boutique,video) VALUES('".$shop."','".$videoName."')");
$stmt->execute();
$insertid = $con->lastInsertId();
$stmt = $con->prepare("INSERT INTO publications ( type, tableid, ID_boutique) VALUES (?,?,?)");
$stmt->execute(array(4, $insertid, $shop));
echo '<div class="alert alert-success">Chargement réussi.</div>';
header('refresh:1.5;url='.base_url("boutiques/store/".$shop."#media"));
}
}
}else{
echo '<div class="alert alert-danger">Extension invalide!</div>';
}
}
}
else{
echo '<div class="alert alert-danger">Aucun fichier selectionné!</div>';
}
}
}
else echo 'POST VARIABLE HASNT PASSED!';
?>
<div class="offset-md-2 col-md-8">
<div class="container block">
<div class="card bg-light mb-3">
<div class="panel-header">Nouvelles photos</div>
<div class="card-body">
<form enctype="multipart/form-data" action="<?php echo current_url(); ?>" method="POST" class="form-horizontal">
<div class="form-group row">
<label class="col-sm-3 control-label" for="file">Ajouter des photos:</label>
<input name="images[]" id="shop_pics" type="file" multiple>
</div>
<div class="gallery"></div>
<div class="form-group row">
<label class="col-sm-3 control-label" for="file">Ajouter une vidéo:</label>
<input name="video" id="video-upload" type="file">
</div>
<p class="offset-md-2" style="font-size: 12px; font-style: italic;">NB: La vidéo ne doit pas dépasser 15mb de volume.</p>
<div class="video-preview"></div>
<div class="form-group row">
<label class="col-sm-2 control-label">Assigner à une boutique:</label>
<div class="col-sm-8 col-md-6">
<?php
$stmt = $con->prepare("SELECT * from shop.boutiques where userID = ?");
$stmt->execute(array($userid));
$boutiques = $stmt->fetchALL();
if(!empty($boutiques)){
echo '<select name="shopid" class="shopselect" required="required">';
echo '<option>Choisir une boutique</option>';
foreach (myShops() as $boutique) {
echo '
<option value='.$boutique['ID_boutique'].'>'.$boutique['nom'].'</option>';
} echo '</select>';
}
?>
</div>
</div>
<div class="form-group">
<div class="text-center">
<input type="submit" name="form_posted" value="Ajouter" class="btn btn-primary">
<input type="reset" value="Annuler" class="btn btn-danger">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<?php
}
else{
echo '<p class="alert alert-primary">Connectez-vous ou créez un compte rapidement pour pouvoir déposer des articles</p>';
}
$this->load->view('templates/footer');
?>
PS: it happens only when I load a video, works well when I upload photos, any help would be welcome
About halfway down your code, you have:
// Valid file extensions
$extensions_arr = array("mp4","avi","3gp","mov","mpeg");
// Check extension
if (in_array($videoFileType, $extensions_arr)) {
if (($_FILES['video']['size'] >= $maxsize) || ($_FILES["video"]["size"] == 0)) {
// do stuff
So your code is checking if the file you've uploaded has any of the extensions in $extensions_arr (.mp4, .avi, .3gp, .mov, .mpeg).
Once you've uploaded the file, it then checks the size and makes sure it's not either 0 or greater than the max file size. As an aside, to make this a little bit more readable, why not just use
if (in_array($videoFileType, $extensions_arr)) {
if (($_FILES['video']['size'] <= $maxsize) || ($_FILES["video"]["size"] > 0)) {
// do stuff
and check that the file size is less than max size but greater than 0?
The problem here is that you haven't declared $shop anywhere in the code, maybe you meant $target_file?
I can succesfully save the image from my database using this code
if(isset($_POST['btn-update'])){
$id = $_REQUEST['id'];
$sql = "SELECT * FROM article WHERE id=:id";
$query= $db_con->prepare($sql);
$query->execute(array(':id' => $id));
while($row=$query->fetch(PDO::FETCH_ASSOC)){
$images_ = $row['image'];
$files_ = $row['file'];
}
$file_image = $_FILES['image-files'];
$file_image_Name = $_FILES['image-files']['name'];
$file_image_TmpName = $_FILES['image-files']['tmp_name'];
$file_image_Size = $_FILES['image-files']['size'];
$file_image_Error = $_FILES['image-files']['error'];
$file_image_Type = $_FILES['image-files']['type'];
if(!empty($_FILES['image-files']['tmp_name'])){
//handle first upload
$file_image_Ext = explode('.', $file_image_Name);
$file_image_ActualExt = strtolower(end($file_image_Ext));
$file_image_allowed = array("jpg", "jpeg", "png");
if(in_array($file_image_ActualExt, $file_image_allowed)){
if($file_image_Error === 0){
if($file_image_Size < 1000000){
$file_image_NameNew = "image-".uniqid('',true).'.'.$file_image_ActualExt;
$file_image_Destination = 'uploaded_files/uploaded_files_articles_images/' .$file_image_NameNew;
move_uploaded_file($file_image_TmpName, $file_image_Destination);
}else{
echo "You file size is too big!";
}
}else{
echo "There was an error uploading the file!";
}
}else{
echo "You cannot upload files of this type!";
}
}else{
$file_image_NameNew = '';
}
if($user->InsertArticle($articleTitle,$date_today,$bodyContent,$file_image_NameNew))
{
header("Location:admin-index?UploadedSuccesfully!");
}
}
Now what I am trying to do is edit the image but it seems like my code is missing something and I couldn't figure out why is it not succesfully editing.
Here's my code for editing the image from database
$location = $_FILES['image']['name'];
$fileTmpNameLocation = $_FILES['image']['tmp_name'];
if(!empty($_FILES['image']['tmp_name'])){
//allow file types
$fileExtLocation = explode('.', $location);
$fileActualExtLocation = strtolower(end($fileExtLocation));
$allowedLocation = array("jpg", "jpeg", "png");
if(in_array($fileActualExtLocation, $allowedLocation)){
$fileNameNewLocation = $images_;
$fileDestinationLocation = 'uploaded_files/uploaded_files_articles_images/' .$fileNameNewLocation;
move_uploaded_file($fileTmpNameLocation, $fileDestinationLocation);
}
}else{
$fileNameNewLocation = '';
}
if($user->UpdateFile($id,$title,$content,$fileNameNewLocation)){
$user->Redirect('edit-index.php?UpdatedSuccesfully');
}else{
echo "There's something wrong!";
}
Here's my UpdateFile Method
public function UpdateFile($id,$title, $content, $image){
try{
$stmt = $this->db->prepare("UPDATE article SET title=:title, content=:content, image=:image WHERE id=:id");
$stmt->bindParam(":title", $title);
$stmt->bindParam(":content", $content);
$stmt->bindParam(":image", $image);
$stmt->bindParam(":id", $id);
$stmt->execute();
return $stmt;
}catch(PDOException $ex){
echo $ex->getMessage();
}
}
Could someone help me out please.
EDIT:
<form action = "edit.php" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Title of the Article</label>
<input type="text" class="form-control" id="title" name="title" value="<?php echo $title; ?>">
<br \>
<label for="bodyContent">Content</label>
<textarea class="form-control" rows="5" id="content" name="content"><?php echo $content; ?></textarea>
<br>
<div class="row">
<div class="col-md-4">
<label for="exampleFormControlFile1">Upload Image Only</label>
<input type="file" name="image" class="form-control-file" id="image">
<div class="col-md-12">
<?php
if(empty($images_)){
//nnothing to display
}else{
echo "<img src='uploaded_files/uploaded_files_articles_images/$images_' class='img-responsive img-rounded'>";
}
?>
</div>
</div>
<div class="col-md-4">
<label for="exampleFormControlFile1">Upload File</label>
<input type="file" name="files" class="form-control-file" id="files">
<div class="col-md-12">
<?php
if(empty($files_)){
//nothing to display
}else{
echo "<a href='uploaded_files/uploaded_files_articles/$files_' download>".$files_."</p>";
}
?>
</div>
</div>
<div class="col-md-4">
<input type="hidden" name="id" value=<?php echo $_GET['id']; ?>>
</div>
</div>
<br>
<button type="submit" name="btn-update" class="btn btn-primary">Update</button>
</div>
</form>
I’m working in form to upload image in project folder and store the other data into Database. when I try to submit this form data was submitted and image was not uploaded and one more the image was uploaded and not all of data was stored in database this is my code
model:
function update_news($data) {
extract($data);
$this->db->where('news_id', $news_id);
$this->db->update($table_name, array('title_en' => $title_en, 'title_ar' => $title_ar,'news_date' => $news_date,'image' => $image,'is_visible' => $is_visible,'main_news' => $main_news));
return true;
}
controller
public function update() {
$filename = $this->input->post('image');
$date = DateTime::createFromFormat("Y-m-d", $this->input->post('news_date'));
$data = array(
'table_name' => 'news', // pass the real table name
'news_id' => $this->input->post('news_id'),
'title_en' => $this->input->post('title_en'),
'title_ar' => $this->input->post('title_ar'),
'news_date' => $this->input->post('news_date'),
'image' => $date->format("Y") . '/' . $this->input->post('image'),
'is_visible' => $this->input->post('is_visible'),
'main_news' => $this->input->post('main_news')
);
$this->m_news_crud->update_news($data);
$folderName = 'assets/images/press-news/2015';
$config['upload_path'] = "$folderName";
if (!is_dir($folderName)) {
mkdir($folderName, 0777, TRUE);
}
$config['file_name'] = $this->input->post('image');
$config['overwrite'] = TRUE;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('userfile','image')) {
$error = array('error' => $this->upload->display_errors());
$data['error'] = $error;
$data['title_en'] = $this->input->post('title_en');
$data['title_ar'] = $this->input->post('title_ar');
$data['news_date'] = $this->input->post('news_date');
$data['image'] = base_url('assets/images/press-news/' . $date->format("Y")) . '/' . $this->input->post('image');
$data['is_visible'] = $this->input->post('is_visible');
$data['main_news'] = $this->input->post('main_news');
$data['news_id'] = $this->input->post('news_id');
$this->load->view('admin/news/d_admin_header');
$this->load->view('admin/news/vcrudedit_news', $data);
$this->load->view('admin/news/d_admin_footer');
} else {
$data = array('upload_data' => $this->upload->data());
redirect('c_news_crud/get_news_data', $data);
echo $filename;
}
}
view:
<div class="container">
<div class="col-md-9">
<?php echo form_open('C_news_crud/update', 'role="form" style="margin-top: 50px;"'); ?>
<div class="form-group">
<label for="title_en">Title Name English</label>
<input type="text" class="form-control" id="title_en" name="title_en" value="<?php echo $title_en ?>">
</div>
<div class="form-group">
<label for="title_ar">Title Name Arabic</label>
<input type="text" class="form-control" id="title_ar" name="title_ar" value="<?php echo $title_ar ?>">
</div>
<div class="form-group">
<div class="col-md-4 col-md-offset-4">
<label for="is_visible">is visible</label>
<?php
if ($is_visible == 1) {
$check_visible = 'checked="checked"';
} else {
$check_visible = ' ';
}
?>
<input role="checkbox" type="checkbox" id="is_visible" class="cbox" <?php echo $check_visible; ?> name="is_visible" value="<?php echo $is_visible; ?>">
</div>
<div class="col-md-4">
<label for="main_news">Main Arabic</label>
<?php
if ($main_news == 1) {
$check_main = 'checked="checked"';
} else {
$check_main = ' ';
}
?>
<input role="checkbox" type="checkbox" id="main_news" class="cbox" <?php echo $check_main; ?> name="main_news" value="<?php echo $main_news; ?>">
</div>
</div>
<div class="form-group">
<label for="news_date">News date</label>
<input type="date" class="form-control" id="news_date" name="news_date" value="<?php echo $news_date ?>">
</div>
<div class="form-group">
<label for="image">image</label>
<input type="file" class="form-control" id="image" name="image" value="<?php echo $image ?>">
</div>
<input type="hidden" name="news_id" value="<?php echo $news_id ?>" />
<input type="submit" name="save" class="btn btn-primary" value="Update">
<button type="button" onclick="location.href = '<?php echo site_url('C_news_crud/get_news_data') ?>'" class="btn btn-success">Back</button>
</form>
<?php echo form_close(); ?>
</div>
Make sure the path to the uploading folder is correct and it has write permission.
Make sure you are referring to the correct file input name:
$config['file_name'] = $_FILES['image']['name'];
set your uploading directory as ./assets/images/press-news/2015/
You need to display the error you get so that you know what is causing the error!
if ( ! $this->upload->do_upload()){
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
Codigniter's Upload Class
I am uploading images in codeigniter. my file is not getting uploaded. i dont know where i am doing wrong. please find in below code
Html:
<form method="post" enctype="multipart/form-data" action="<?php echo base_url(); ?>assign_user/addStartPopup">
<div class="col-lg-6">
<div class="form-group">
<label for="image">
<input type="radio" id="image" name="start_img" onclick="rightfilefunction(1);" checked> <label for="image"> <span style="top: -2px;position: relative;">Image upload</span></label>
<label for="video" class="green">
<input type="radio" id="video" name="start_img" onclick="rightfilefunction(2);">
<span style="top: -2px;position: relative;">Video</span>
</label>
</div>
<div class="form-group" id="imageId">
<input type="file" name="imageupload" class="form-control">
</div>
<div class="form-group" id="videoId" style="display:none">
<input type="text" name="video_upload" class="form-control">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary"> Save </button>
</div>
</div>
</form>
Model:
public function startPopup(){
$createdOn = date('Y-m-d H:i:s');
if($_FILES['imageupload']['size'] != 0)
{
$files = $_FILES;
$config = array();
$config['upload_path'] = "startpage/";
$config['allowed_types'] = "png|jpg|gif";
$config['max_size'] = "5000";
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('imageupload')){
$imgdata = $this->upload->data();
$image_config=array();
$image_config["image_library"] = "gd2";
$image_config['overwrite'] = TRUE;
$image_config["source_image"] = $imgdata["full_path"];
$image_config['create_thumb'] = FALSE;
$image_config['maintain_ratio'] = TRUE;
$image_config['new_image'] = $imgdata["file_path"].$imgdata["file_name"];
$image_config['quality'] = "95%";
$image_config['width'] = 170;
$image_config['height'] = 170;
$this->load->library('image_lib',$image_config);
$this->image_lib->initialize($image_config);
$this->image_lib->resize();
$logo = 'startpage/'.$imgdata["file_name"];
$query = $this->db->query("INSERT INTO `startpop` (content_view, created_on) VALUES ('$logo', '$createdOn')");
if($query){
return 1;
}
}else
{
echo "not uploaded";
}
}else{
$prv = $this->input->post('video_upload');
$query = $this->db->query("INSERT INTO `startpop` (content_view, created_on) VALUES ('$prv', '$createdOn')");
if($query){
return 1;
}
}
}
Controller:
public function addStartPopup(){
$result = $this->model->startPopup();
if($result > 0){
$data['mgs'] = "Added Successfully ..!";
$this->load->view('admin/startPage',$data);
}
}
From this above code, i am getting the error "not uploaded". can any one tell me where i am doing wrong