I have the following form and controller where it has a image upload, but everything goes smooth except the file not being uploaded to the particular folder.
View
<?php
$this->load->helper('url');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>diluks eCommerce cms - home page</title>
<link href="<?php
echo base_url();
?>Public/scripts/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form action="<?php echo base_url();?>index.php/addproduct_controller" method="post">
<?php
include 'header-adminpanel.php';
?>
<div class="container">
<div class="body-content">
<div class="side-left"><?php
include 'adminproduct_sidebar.php';
?></div>
<div class="side-right">
<br />
<table>
<tr>
<td class="captions">Product Code</td>
<td><input name="txt_pcode" type="text"/></td>
</tr>
<tr>
<td class="captions">Product Name</td>
<td><input name="txt_pname" type="text" size="40" /></td>
</tr>
<tr>
<td class="captions">Product Price</td>
<td><input name="txt_pprice" type="text" /></td>
</tr>
<tr>
<td class="captions">Product Description</td>
<td><textarea name="txt_pdesc" style="width:300px;height:100px;"></textarea></td>
</tr>
<tr>
<td class="captions">Product Image</td>
<td><input type="file" name="userfile" size="20" /></td>
</tr>
<tr>
<td class="captions">Product Options</td>
<td><input name="txt_poptions" size="40" type="text" /><a class="hint"> (Separate by a "," comma)</a></td>
</tr>
<tr><td><input name="btn_add" class="button" type="submit" value="Add" /></td></tr>
</table>
<br />
</div>
</div>
</div>
<div style="clear:both"></div>
<?php
include 'footer.php';
?>
</form>
</body>
</html>
Controller
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Addproduct_controller extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index()
{
if (isset($_POST["btn_logout"])) {
$this->session->sess_destroy();
$this->load->view('welcome_view');
} else if (isset($_POST["btn_home"])) {
$this->load->view('welcome_view');
} else if (isset($_POST["btn_account"])) {
} else if (isset($_POST["btn_add"])) {
$prod_img = 'no image';
$config['upload_path'] = 'Public/uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
// $error = array('error' => $this->upload->display_errors());
//$this->load->view('upload_form', $error);
//return 'error';
} else {
global $prod_img;
$data = array(
'upload_data' => $this->upload->data()
);
$prod_img = $data->file_name;
// $this->load->view('upload_success', $data);
}
$prod_name = $_POST["txt_pname"];
$prod_code = $_POST["txt_pcode"];
$prod_price = $_POST["txt_pprice"];
$prod_desc = $_POST["txt_pdesc"];
$prod_options = $_POST["txt_poptions"];
$this->load->model('product_model');
$addproduct_result = $this->product_model->addProduct($prod_code, $prod_name, $prod_price, $prod_desc, $prod_img);
if ($addproduct_result == true) {
echo "Added Successfully";
} else {
echo "Failed";
}
}
}
}
Then I tried by adding following instead of normal tags.
<?php
$this->load->helper('form');
?>
<?php
echo form_open_multipart(base_url().'index.php/addproduct_controller');
?>
where it gaves me an error
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: controllers/addproduct_controller.php
Line Number: 53
Please help me with this or show me where I have done the mistake.
enctype attribute missing in your from tag.
Add enctype="multipart/form-data" in your form tag
OR
In CI, Use form_open_multipart function to generate form tag
As per discussion in comment, update your code as below.
$data = array(
'upload_data' => $this->upload->data()
);
$prod_img = $data["upload_data"]->file_name;
You have missed out to include form attribute to upload the file
Add enctype="multipart/form-data" in your form tag
You have make the html form but not added file upload tag in your form creation.
add: enctype="multipart/form-data" in your form tag.
<form action="<?php echo base_url();?>index.php/addproduct_controller" method="post" enctype="multipart/form-data" >
Related
I am new to Laravel and trying to add multiple record dynamically with images. If I keep only the image fields the records are getting saved to the database successfully but if I add other fields (subject) the record is not getting saved to database. Please help
UI and Error
Error Messages - Trying to access array offset on value of type null
UI and Error Image
The following is my Welcome.blade.php file
<!-- js -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript">
var i = 0;
$("#dynamic-ar").click(function() {
++i;
$("#dynamicAddRemove").append('<tr><td><input type="text" name="addMoreInputFields[' + i +
'][studentname]" placeholder="Enter your Name" class="form-control" /></td><td><input type="text" name="addMoreInputFields[' +
i +
'][subject]" placeholder="Enter your subject" class="form-control" /></td><td><input type="file" id="image" name="addMoreInputFields[' +
i +
'][image]" placeholder="Enter your image" class="form-control" /></td><td><button type="button" class="btn btn-danger remove-input-field">Remove</button></td></tr>'
);
});
$(document).on('click', '.remove-input-field', function() {
$(this).parents('tr').remove();
});
</script>
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Add Multiple records</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>.container { max-width: 600px;}</style>
</head>
<body>
<div class="container">
<form action="{{ url('store-input-fields') }}" method="POST" enctype="multipart/form-data">
#csrf
#if ($errors->any())
<div class="alert alert-danger" role="alert">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#if (Session::has('success'))
<div class="alert alert-success text-center">
<p>{{ Session::get('success') }}</p>
</div>
#endif
<table class="table table-bordered" id="dynamicAddRemove">
<tr>
<th>studentname</th>
<th>Subject</th>
<th>Image</th>
<th>Action</th>
</tr>
<tr>
<td><input type="text" name="addMoreInputFields[0][studentname]" placeholder="Enter studentname" class="form-control" /></td>
<td><input type="text" name="addMoreInputFields[0][subject]" placeholder="Enter subject" class="form-control" /></td>
<td><input type="file" name="addMoreInputFields[0][image]" placeholder="Enter image" class="form-control" /></td>
<td><button type="button" name="add" id="dynamic-ar" class="btn btn-outline-primary">Add More</button></td>
</tr>
</table>
<button type="submit" class="btn btn-outline-success btn-block">Save</button>
</form>
</div>
</body>
</html>
The controller file code
namespace App\Http\Controllers;
use App\Models\Student;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class StudentController extends Controller
{
public function index()
{
return view('welcome');
}
public function store(Request $request){$request->validate([
'addMoreInputFields.*.studentname' => 'required',
'addMoreInputFields.*.subject' => 'required',
'addMoreInputFields.*.image' =>
'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
foreach ($request->addMoreInputFields as $key => $value) {
if ($files = $request->file('addMoreInputFields.*.image')) {
$destinationPath = public_path('/images/'); // upload path
foreach ($files as $img) {
// Upload Image
$profileImage = uniqid() . '_' . date('d-m-Y') . '_' . microtime(true) . '_' . $img->getClientOriginalName();
try {
if (!Storage::exists('images/' . $profileImage)) {
$img->move($destinationPath, $profileImage);
}
} catch (\Exception$e) {
return $e->getMessage();
}
$imagemodel = new Student();
$imagemodel->image = "$profileImage";
//$imagemodel->subject = "$subject";
//$imagemodel -> subject = $request->input('addMoreInputFields.*.subject.'.$value);
$imagemodel->subject = $request->subject[$value];
$imagemodel->studentname = $destinationPath . $profileImage;
$imagemodel->save();
}
}
}
return back()->with('success', 'New reord has been added.');
}
}
The following is my model file code
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
use HasFactory;
protected $fillable = [
'studentname',
'subject',
'image',
];
}
The migration file
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->string('studentname');
$table->string('subject');
$table->string('image')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('students');
}
};
On my form each row has it's on submit button and you need to check the check box before you can delete it else it should through error.
Question: My checkbox is in_array but if I do not check the box and then press submit it does not through the codeigniter form_validation error. I have used $this->form_validation->set_rules('selected[]', 'Selected', 'required'); But error not showing up.
What is the best solution in making it getting form_validation error to work?
View
<?php echo form_open('admin/design/layout/delete'); ?>
<?php echo validation_errors('<div class="alert alert-danger">', '</div>'); ?>
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<td style="width: 1px;" class="text-center">
<input type="checkbox" onclick="$('input[name*=\'selected\']').prop('checked', this.checked);" />
</td>
<td>Layout Name</td>
<td class="text-right">Action</td>
</tr>
</thead>
<tbody>
<?php if ($layouts) { ?>
<?php foreach ($layouts as $layout) { ?>
<tr>
<td class="text-center"><?php if (in_array($layout['layout_id'], $selected)) { ?>
<input type="checkbox" name="selected[]" value="<?php echo $layout['layout_id']; ?>" checked="checked" />
<?php } else { ?>
<input type="checkbox" name="selected[]" value="<?php echo $layout['layout_id']; ?>" />
<?php } ?>
</td>
<td><?php echo $layout['name']; ?></td>
<td class="text-right">
<button type="submit" class="btn btn-danger">Delete</button>
Edit
</td>
</tr>
<?php } ?>
<?php } else { ?>
<?php } ?>
</tbody>
</table>
</div>
</div>
<?php echo form_close(); ?>
Controller Function
public function delete() {
$this->load->library('form_validation');
$this->form_validation->set_rules('selected[]', 'Selected', 'required');
if ($this->form_validation->run() == FALSE) {
echo "Error";
$this->get_list();
} else {
$selected_post = $this->input->post('selected');
if (isset($selected_post)) {
foreach ($selected_post as $layout_id) {
}
echo "Deleted $layout_id";
$this->get_list();
}
}
}
It won't validate per field. selected[] selector in rules means, when you submit your form, it should be at least one selected item. Now you have submit buttons, which are independently submit the form, no matter where are they in the dom, and which checkboxes are selected.
Currently it the same, as you would have one submit button at the end.
I would add some javascript, and set if the checkbox is not selected, you can disable that field:
<script>
$(function() {
$('input:checkbox').on('change', function() {
if($(this).is(':checked')) {
$(this).closest('tr').find('button:submit').prop('disabled', false);
}
else {
$(this).closest('tr').find('button:submit').prop('disabled', true);
}
})
})
</script>
And add disabled to your submit buttons:
<button type="submit" class="btn btn-danger" disabled>Delete</button>
It's not a server side validation, but you can achieve to prevent push the button next unchecked checkboxes.
This is my controller
function edit_profile() {
// if (isset($_POST['submit']))
//{
$session_data = $this->session->userdata('logged_in');
$id = $session_data['id'];
$name = $session_data['name'];
$uploaddata = null;
$config['upload_path'] = './assets/uploads/userpic';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '10000';
$Img_name= strtotime(date("d-m-y H:i:s")).".jpg";
//$Img_name= strtotime(date("d-m-y H:i:s"));
$config['file_name']= $Img_name ;
$config['overwrite'] = "true";
$this->load->library('upload', $config);
if (!$this->upload->do_upload('documents')) {
$error = array('error' => $this->upload->display_errors());
} else {
$uploaddata = array('upload_data' => $this->upload->data());
}
$upload_data = $this->upload->data();
$file_name = $name;
$filepath1= $config['upload_path'];
if(!is_uploaded_file($_FILES['documents']['tmp_name'])) {
echo 'No upload';
$data = array(
'name' => $this->input->post('firstname'),
'lname' => $this->input->post('lastname')
);
}else
{
echo "file uploaded";
$data = array(
'name' => $this->input->post('firstname'),
'lname' => $this->input->post('lastname'),
'filepath'=> $Img_name,
'filename'=>$file_name
);
}
$this->load->model('update_model');
$this->update_model->update_entry($id, $data); //passing control to update_model
$session_data['name'] = $this->input->post('firstname');
$this->session->set_userdata('logged_in', $session_data); //settting sesssin values
if( $data)
{
$data['message']="Image Uploaded Successfully";
$this->load->view('endusers/endemp_edit_profile_view',$data);
}
//redirect('endusers/end_emp_home');
//}
}
This is my view
<?php echo form_open_multipart('endusers/editprofile/edit_profile');?>
<table width="auto" border="1" style="border-color: #bce8f1;"class="table table-bordered" >
<tbody>
<tr>
<td colspan="2"><input type="text" class="txt-field uname" name="firstname" placeholder="first name" required></td>
</tr>
<! ------ <tr>
<td colspan="2"><input type="text" class="txt-field pass" name="lastname" placeholder="last name" required ></td><br>
</tr>
<tr>
<tr>
<td valign="top">
<label for="curtexp" style="margin-top: 20px;padding-right: 7px;margin-left: 11px;"> Upload a Profile Picture </label> <label class="error" ></label>
<input type="file" name="documents" size="40" / style="margin-left: 9px;" placeholder="Profile Picture"><br><br>
</td>
</tr>
<tr>
<td colspan="8" style="text-align:center">
<br />
<div class="ee">
<input type="submit" class="btn btn-primary" value="Update" class="buttonmy2" / style="float: left; margin-bottom: 17px;">
<input type="Reset" class="btn btn-primary" value="Reset" class="buttonmy2" / style="float: left;margin-left: 10px;">
<?php echo validation_errors(); ?>
</div>
</td>
</tr>
</tbody>
</table>
</form>
This is my code in codeigniter for uploading a profile pic but it takes ma to log out to see the uploaded image .I want tom upload a image without logging out of my account and may be jusr refreshing the page
--This Jquery plugin will solve your problem
--More help http://malsup.com/jquery/form/#getting-started
<script src="http://malsup.github.com/jquery.form.js"></script>
$("#form_id").on('submit', (function (e) {
var options = {
url:'your URL', // target element(s) to be updated with server response
success:function(data){
alert('submitted');
}
$(this).ajaxSubmit(options);
e.preventDefault();
}));
Comment me if you need help...
I am trying this code but it is not working with file upload.
When there is no file uploading field it works fine but with file upload its not working.
Please help me.
form.php
<?php echo validation_errors(); ?>
<?php echo form_open_multipart('emp'); ?>
<form name="ajaxform" id="ajaxform" action="<?php echo base_url().'/emp/operation'?>" method="POST" enctype="multipart/form-data">
<table border="1">
<tr>
<th>Name</th>
<td><input type="text" name="name" value="<?php echo $name; ?>" size="50"/></td>
</tr>
<tr>
<th>Email </th>
<td><input type="text" name="email" value="<?php echo $email; ?>"/></td>
</tr>
<tr>
<th>Address</th>
<td><input type="text" name="address" value="<?php echo $address; ?>" /></td>
</tr>
<tr>
<th>Phone</th>
<td><input type="text" name="phone" value="<?php echo $phone; ?>" /></td>
</tr>
<tr>
<th>Photo</th>
<td><input type="file" name="userfile" /></td>
</tr>
</table>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="hidden" id="btn" value="<?php echo $submit; ?>" name="btn"/>
<input type="submit" id="simple-post" value="<?php echo $submit; ?>" name="simple-post"/>
</form>
</body>
Here is the controller code.
Emp.php
public function index(){
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name','required','callback_username_check');
$this->form_validation->set_rules('email', 'Email', 'required|is_unique[registration.email]');
$this->form_validation->set_rules('address', 'Address', 'required');
$this->form_validation->set_rules('phone', 'Phone', 'required');
if (empty($_FILES['userfile']['name']))
{
$this->form_validation->set_rules('userfile', 'Photo', 'required');
}
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1800';
$config['max_width'] = '1924';
$config['max_height'] = '1924';
$new_name = time().$_FILES['userfile']['name'];
$config['file_name'] = $new_name;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload() OR $this->form_validation->run() == FALSE)
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->emp_model->add_data();
$query['value']=$this->GetAll();
}
}
try this
if (null != ($_FILES['userfile']['tmp_name']))
{
$this->form_validation->set_rules('userfile', 'Photo', 'callback_checkPostedFiles');
}
And this function for validation
public function checkPostedFiles()
{
$file_name = trim(basename(stripslashes($_FILES['userfile']['name'])), ".\x00..\x20");
$file_name = str_replace(" ", "", $file_name);
if (isset($_FILES['userfile']) && !empty($file_name)) {
$allowedExts = array("jpeg", "jpg", "png"); // use as per your requirement
$extension = end(explode(".", $file_name));
if (in_array($extension, $allowedExts)) {
return true;
} else {
$this->form_validation->set_message('checkPostedFiles', "You can upload jpg or png image only");
return false;
}
} else {
$this->form_validation->set_message('checkPostedFiles', "You must upload an image!");
return false;
}
}
Check this sample code for image uploading :
Form :
<form method="post" action="" id="upload_file">
<div class="modal-body">
<div class="box-body">
<div class="form-group">
<label for="exampleInputFile">Profile Picture</label>
<input type="file" id="userfile" accept="image/*" name="userfile">
<p class="help-block">Requested size : 215*215</p>
</div>
</div>
</div>
<div class="modal-footer">
<div class="btn-group">
<button type="button" class="btn btn-default md-close" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" name="submit" value="Save Changes">
</div>
</div>
</form>
Include this js in your view.
Js for form submission
$(function() {
$('#upload_file').submit(function(e) {
e.preventDefault();
$.ajaxFileUpload({
url:'<?php echo base_url(); ?>profile/upload_file',
type: "POST",
fileElementId :'userfile',
success: function() {
alert("file uploaded!");
}
});
return false;
});
});
In controller
$userid = $session_data['id'];
$file_element_name = 'userfile';
$pathToUpload = '/var/www/html/uploads/' . $userid;
if ( ! file_exists($pathToUpload) )
{
$create = mkdir($pathToUpload, 0777);
if (!$create)
return;
}
$config['upload_path'] = $pathToUpload;
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name))
{
$this->upload->display_errors();
}
else
{
$data = $this->upload->data();
//$this->user->insert_file($data['file_name'], $userid);
$data = array(
'userPhoto' => $data['file_name']
);
$this->db->where('user_id', $userid);
$this->db->update('tbl_user_profile', $data);
}
//#unlink($_FILES[$file_element_name]);
I'm trying to add singer information with image. the information can be successfully added without image but if i try to insert data with image, error occurred with "You did not select a file to upload" message.
My controller function is this...
public function add_edit_singer($id = '')
{
if($this->input->post('save_singer_info')){
$post=$this->input->post();
$add=array(
'name'=>$post['sname'],
'bio'=>$post['bio']
);
$img1=$_FILES['photo']['name'];
if($img1){
$config['upload_path'] = 'images/singer/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
if (!$this->upload->do_upload())
{
$error = $this->upload->display_errors();
$this->session->set_flashdata('info',$error);
redirect('admin/singer_manager');
}
$data = array('upload_data' => $this->upload->data());
$image = $data['upload_data']['file_name'];
$add['image']=$image;
}
else{
$add['image']='no_image.jpg';
}
$table='tbl_singer';
if($this->singer_manager->add($add,$table)){
$this->session->set_flashdata('info',"Artist/Band Information Added Successfully.");
redirect('admin/singer_manager');
}
else{
redirect('admin/singer_manager');
}
}
else{
$data['main_content']='admin/singer/add_edit_singer_view';
if($id != '')
$data['editdata'] = $this->common_model->get_where('tbl_singer', array('id' => $id));
$this->load->view('admin/include/template_view',$data);
}
}
my Model function is...
function add($data,$table){
$name = $data['name'];
$res = $this->db->insert($table,$data);
if($res)
{
return true;
}
else
{
return false;
}
}
and my Form is...
<form role="form" enctype="multipart/form-data" action="<?php echo base_url('admin/singer_manager/add_edit_singer/' . $id); ?>"
method="post"
id="user_form">
<table class="table table-hover">
<tr>
<td>Singer Name</td>
<td>
<input type="text" class="form-control required" name="sname"
value="<?php if (isset($name)) {
echo $name;
} ?>"/>
</td>
</tr>
<tr>
<td>Bio</td>
<td>
<textarea class="form-control required" name="bio">
<?php if (isset($bio)) {
echo $bio;
} ?>
</textarea>
</td>
</tr>
<tr>
<td>Image</td>
<td>
<?php if (isset($image)) {?>
<div class="row">
<div class="col-xs-6 col-md-4">
<a href="<?php echo base_url().'images/singer/'.$image;?>" class="thumbnail">
<img src="<?php echo base_url().'images/singer/'.$image;?>" width="120" height="140" id="img_prev" />
</a>
</div>
</div>
<?php
} ?>
<input type="file" name="photo" size="20" />
</td>
</tr>
<tr>
<td colspan="2">
<?php if (isset($id)) { ?><input type="hidden" name="id" value="<?php echo $id; ?>" /><?php } ?>
<input type="submit" class="btn btn-success" id="btn_save" name="save_singer_info"value="Save"/>
<input type="reset" class="btn btn-info" id="reset"/>
<input type="button" class="btn btn-danger" value="Cancel"onclick="history.go(-1)"/>
</td>
</tr>
</table>
</form>
change
$this->upload->do_upload()
to
$this->upload->do_upload('photo')
may be it solve the problem