codeigniter upload 2 files (images and video ) in separate field - codeigniter

Hi i am new in codeigniter , I want to upload image and video in same form with different field. i did but it store either one. last one is stored like video.
<div id="file-upload" class="form-fields">
<div class="new_Btn"><i title="Upload Image" class="fa fa-cloud-upload" aria-hidden="true"></i><span>Upload Image</span></div>
<input id="html_btn" type="file" id="fileToUpload" name="fileToUpload" />
</div>
<div id="file-upload" class="form-fields">
<div class="new_Btn"><i title="Upload Image" class="fa fa-cloud-upload" aria-hidden="true"></i><span>Upload Video</span></div>
<input id="html_btn" type="file" id="videoToUpload" name="videoToUpload" />
</div>
And my controller is
public function videoupdate() {
$data['user_data'] = $this->session->userdata('user_logged_in');
if (($this->session->flashdata('success')))
$data['success'] = $this->session->flashdata('success');
else
$data['error'] = $this->session->flashdata('error');
if (!empty($data['user_data']['user_id'])) {
$title = $_POST['title'];
$description = htmlentities($_POST['description']);
$target_dir = './cms/uploads/blog/video3/';
$temp = explode('.', $_FILES['fileToUpload']['name']);
$video = explode('.', $_FILES['videoToUpload']['name']);
if (!empty($_FILES['fileToUpload']['name'])) {
$newfilename = round(microtime(true)) . '.' . end($temp);
} else {
$newfilename = "";
}
if (!empty($_FILES['videoToUpload']['name'])) {
$videofilename = round(microtime(true)) . '.' . end($video);
} else {
$videofilename = "";
}
move_uploaded_file($_FILES['fileToUpload']['tmp_name'], './cms/uploads/blog/video3/' . $newfilename);
move_uploaded_file($_FILES['videoToUpload']['tmp_name'], './cms/uploads/blog/video3/' . $videofilename);
$createddate = date('Y-m-d H:i:s');
$ipaddress = $_SERVER['REMOTE_ADDR'];
$status = $this->microblog_model->insertBlogvideo($title, $description, $newfilename, $videofilename, $data['user_data']['user_id'], $createddate, $ipaddress);

I found your code for upload files is working fine. As I check it in separate php file:
<pre>
<?php
if(isset($_POST)){
$temp = explode('.', $_FILES['fileToUpload']['name']);
$video = explode('.', $_FILES['videoToUpload']['name']);
try{
//upload image
if (!empty($_FILES['fileToUpload']['name'])) {
$newfilename = round(microtime(true)) . '.' . end($temp);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], './uploads/' . $newfilename)){
echo "Image Uploaded<br/>";
}
}
//upload video
if (!empty($_FILES['videoToUpload']['name'])) {
$videofilename = round(microtime(true)) . '.' . end($video);
if(move_uploaded_file($_FILES['videoToUpload']['tmp_name'], './uploads/' . $videofilename)){
echo "Video Uploaded<br/>";
}
}
}catch(Exception $e){
print_r($e);
}
}
?>
</pre>
<form method="post" enctype="multipart/form-data">
<div id="file-upload" class="form-fields">
<div class="new_Btn"><i title="Upload Image" class="fa fa-cloud-upload" aria-hidden="true"></i><span>Upload Image</span></div>
<input id="html_btn" type="file" id="fileToUpload" name="fileToUpload" />
</div>
<div id="file-upload" class="form-fields">
<div class="new_Btn"><i title="Upload Image" class="fa fa-cloud-upload" aria-hidden="true"></i><span>Upload Video</span></div>
<input id="html_btn" type="file" id="videoToUpload" name="videoToUpload" />
</div>
<input type="submit" name="submit">
</form>
You should check the size of video you are trying to upload and the maximum upload size allowed. I hope this will help. Because I checked it multiple times with many images and videos and found it is working fine.

Related

multiple image upload to aws in laravel

This is laravel project and I want to upload multiple images to aws s3 server
This is blade code.
<div class="col-12">
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Add Multiple image...</span>
<input type="file" multiple="multiple" accept="image/*" class="imageupload1" name="uploadfile2[]" /><br/>
</span>
</div>
And these are the Controller code.
if($request->hasfile($file_name))
{
$file = $request->file($file_name);
$originalFileName = time().$file->getClientOriginalName();
$filePath = $defaultPath.'/'.$originalFileName;
$this->deleteimage($profile->thumb_img);
$this->uploadimage($request, $file_name, $filePath);
}
public function uploadimage($request, $file_name, $defaultPath){
$this->validate($request, [$file_name => 'required|image']);
if($request->hasfile($file_name))
{
$file = $request->file($file_name);
\Storage::disk('s3')->put($defaultPath, file_get_contents($file));
}
}
Try like below.
And let me know.
if($request->hasfile($multi_file_name))
$files = $request->file($multi_file_name);
foreach($files as $imgfile) {
$originalFileName = time().$imgfile->getClientOriginalName();
$multi_filePath = $multi_defaultPath.'/'.$originalFileName;
\Storage::disk('s3')->put($multi_filePath, file_get_contents($imgfile));
}
}
Since the request is coming through as an array, you need to loop through each iterance.
foreach ( $request->file($file_name) as $file )
{
$originalFileName = time().$file->getClientOriginalName();
$filePath = $defaultPath.'/'.$originalFileName;
$this->deleteimage($profile->thumb_img);
$this->uploadimage($request, $file_name, $filePath);
}

[Codeigniter]Multiple upload cant insert to database and not uploading to directory

How to upload multiple images with Codeigniter 4.x ?
I tried to loop the do_upload function in my model but it's not working, and I tried another code that I got from GitHub but still, none of it works.
This is my view:
<div class="section-body">
<h2 class="section-title">Entry Group Passanger</h2>
<div class="row">
<div class="col-md-12">
<form action="<?= base_url('passanger/addgroup') ?>" method="POST" enctype="multipart/form-data">
<?php for($i=1;$i<=$pax['pax'];$i++) : ?>
<h5>Passanger ke-<?= $i ?></h5>
<div class="form-row">
<div class="col-md-6">
<label for="fullname">Fullname</label>
<input type="text" class="form-control" name="name[]">
<?= form_error('name', '<small class="text-danger pl-3">', '</small>'); ?>
</div>
<div class="col-md-6">
<label for="gender">Gender</label>
<select class="form-control select2-input" name="gender">
<option>-- Select Gender --</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>
<?= form_error('gender', '<small class="text-danger pl-3">', '</small>'); ?>
</div>
</div>
<div class="form-row">
<div class="col-md-12 mb-4 mt-2">
<label for="">Upload Passport</label>
<input type="file" name="upload_passport[]" id="input-file-now" class="dropify" />
</div>
</div>
this is my model :
public function addGroup()
{
$user = $this->db->get_where('user', ['username' => $this->session->userdata('username')])->row_array();
$pax = $this->getPaxById();
date_default_timezone_set('Asia/Jakarta');
$upload_image = $_FILES['upload_passport[]']['name'];
if ($upload_image) {
$config['upload_path'] = './assets/img/uploads/passport';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
for($i=0;$i<$pax['pax'];$i++) {
if ($this->upload->do_upload('upload_passport[$i]')) {
$new_image = $this->upload->data('file_name');
} else {
echo $this->upload->display_errors();
}
}
}
$name = $this->input->post("name[]");
$gender = $this->input->post("gender[]");
$birthdate = $this->input->post("birthdate[]");
$no_passport = $this->input->post("no_passport[]");
$expire_passport = $this->input->post("expire_passport[]");
$destination = $this->input->post("destination[]");
$date = $this->input->post("date[]");
$dp1 = "0";
$dp2 = "0";
$lunas = "0";
$type = "Group";
$status = "Not Complete";
$permission = "0";
$upload_passport = $new_image;
$upload_dp1 = "default.png";
$upload_dp2 = "default.png";
$date_created = date('d/m/Y H:i:s');
$data = [];
$jumlah = $pax['pax'];
for($x=0;$x<$jumlah;$x++) {
array_push($data, [
'name'=>$this->input->post("name[$x]"),
'id_user'=> $user['id_user'],
'gender'=>$this->input->post("gender[$x]"),
'birthdate'=>$this->input->post("birthdate[$x]"),
'no_passport'=> $this->input->post("no_passport[$x]"),
'expire_passport'=> $this->input->post("expire_passport[$x]"),
'destination'=> $this->input->post("destination[$x]"),
'date'=> $this->input->post("date[$x]"),
'dp1'=> $dp1,
'dp2'=> $dp2,
'lunas'=> $lunas,
'pax'=> $pax['pax'],
'type'=> $type,
'status'=> $status,
'permission'=> $permission,
'upload_passport'=> $new_image,
'upload_dp1'=> $upload_dp1,
'upload_dp2'=> $upload_dp2,
'date_created'=> $date_created
]);
var_dump($data); die;
}
$this->db->insert_batch("passanger", $data);
}
What I want to get is:
array('','','upload_image'), array('','','upload_image')
When insert it to database but when I do it the upload just gets output null and it's not even uploaded to my uploads directory. I would really appreciate it if you help me, I've been stuck on this for 3 days. Thank you.
for ($i=0; $i < sizeof($_FILES['image']['name']) ; $i++) {
$_FILES['file']['name'] = $_FILES['image']['name'][$i];
$_FILES['file']['type'] = $_FILES['image']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['image']['tmp_name'[$i];
$_FILES['file']['error'] = $_FILES['image']['error'][$i];
$_FILES['file']['size'] = $_FILES['image']['size'][$i];
$config['upload_path'] = PRODUCT_IMAGE_UPLOAD_PATH;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if ($this->upload->do_upload('file')){
$images[] = $this->upload->data('file_name');
}else {
echo $this->upload->display_errors();
}
}
Try this in Codeigniter 4
in your controller add this
$image_model = new App\Models\Images(); // Your model name that is load your model
if($imagefiles = $this->request->getFiles())
{
foreach($imagefiles['uploadImages'] as $img)
{
if ($img->isValid() && ! $img->hasMoved())
{
$image_name = $img->getRandomName(); // This is applicable if you want to change the name of the images
if($image_model->save_images($image_name))
{
$img->move(WRITEPATH.'uploads/images/ads', $image_name); // WRITEPATH.'uploads/images/ads' is the part you wish to save you file to
}
}
}
}
In your Model e.g Image model i have a method call save_images()as this
use Codeigniter\Model
class Images extends Model{
public function save_images($image = '')
{
// We set the column 'name' to be allow for data entry into the db. note this is mandatory for now.
// hope it will change in feature. 'name' is the column in database table where you will save the image name
// this command the CI4 db to select only the image column in the database table
$this->allowedFields = ['name'];
return $this->db->table('images')->insert(['name' => $image]);
// echo $sql = $this->db->getLastQuery();
}
}
Then in your html file input, do this
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="file" name="uploadImages[]" multiple>
</div>
</form>
I hope this will work for you

Laravel checkbox implementation for updating database

I've been trying to make an attendance management system in Laravel.
In the attendance view,when a checkbox is checked ,the controller function is supposed to increment the appropriate database column.
I've been having some issues.Here's my code:
views:
<div class="container">
<!--<div class="row">-->
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Take Attendance</div>
<h4><center>Teacher: {{ auth()->user()->name}}</center></h4>
<div class="form-inline">
#foreach ($second as $sec)
<br>
<div class = "form-group">
{{$sec->Roll }}
&nbsp&nbsp&nbsp&nbsp
{{ $sec->Name}}
</div>
<div class = "form-group">
<!--{{Form::checkbox('agree') }}-->
<input tabindex="1" type="checkbox" value="{{$sec->Roll}}" name="" />
</div>
#endforeach
</div>
<br>
<form action ="report_generate&<?php echo $name ?>" method = "post" enctype = "multipart/form-data" >
<!--<input type = "hidden" name = "_token" value = "{{{ csrf_token() }}}"/>-->
<div class = "form-group">
<input type="submit" value= "Submit">
<center>Report</center>
</div>
</form>
</div>
</div>
</div>
Controller(for submit button):
public function report_generate($tabu)
{
$year = DB::table('sub')->select('Year')-
>where('sub.Subject_Name','=',$tabu)->get();
$sub_id = DB::table('sub')->select('Subject_Id')-
>where('sub.Subject_Name','=',$tabu)->get();
ob_start();
echo $year;
$output=ob_get_contents();
ob_end_clean();
if ( $output=='[{"Year":1}]')
{
$req = "first";
}
elseif ( $output=='[{"Year":2}]')
{
$req = "second";
}
elseif ( $output=='[{"Year":3}]')
{
$req = "third";
}
elseif ( $output=='[{"Year":4}]')
{
$req = "fourth";
}
$final = DB::table($req)->get();
//dd($final);
//$columns = Schema::getColumnListing($req);
//dd($sub_id);
ob_start();
echo $sub_id;
//dd($sub_id);
$va=ob_get_clean();
$va = stripslashes($va);
$txt = rtrim($va,"}]");
$txt = ltrim($txt,"[{Subject_Id:");
$txt = ltrim($txt,"Subject_Id:");
$txt = explode(":",$txt);
$txt = str_replace('"','', $txt);
//dd($txt[1]);
$columns = Schema::getColumnListing($req);
//dd($columns);
//dd($txt);
foreach ($columns as $col)
{
//dd("Y");
if($col == $txt[1])
{
$got=DB::table($req)->select($col)->get();
//dd($got);
foreach($got as $g)
{
//want to increment that cell value
}
}
}
}
Looks like your checkboxs are outside of the form divs which is an issue. You also seem to be skipping over the Laravel features, for example having a Sub Model you can call on, or using the Request facade. Also not sure why you're using ob for those string comparisons (might actually want to look at Switch for that long elseif block) Lastly, you might want to to use a raw DB statement to do the increments within a SQL query
DB::statement("UPDATE " . $table . " set " . $column . " to " . $column . " + 1 WHERE id IN (" implode(', ', $ids) . ')")

File (picture) Upload not working

Okay so I just basically got this code online.
It works locally (to upload a file), but it doesn't wanna work on the website.
(I've already put the permissions at 0777, for the folder, but it still won't upload.
<header>
<?php
function UploadOne($fname)
{
$uploaddir = 'pictures/';
if (is_uploaded_file($fname['tmp_name']))
{
$filname = basename($fname['name']);
$uploadfile = $uploaddir . basename($fname['name']);
if (move_uploaded_file ($fname['tmp_name'], $uploadfile))
$res = "File " . $filname . " was successfully uploaded and stored.<br>";
else
$res = "Could not move ".$fname['tmp_name']." to ".$uploadfile."<br>";
}
else
$res = "File ".$fname['name']." failed to upload.";
return ($res);
}
?> </header>
<body>
<?php
if ($_FILES['picture']['name'] != "")
{
$res = UploadOne($_FILES['picture']);
$filname = $_FILES['picture']['name'];
echo ($res);
}
?>
<h1>UPLOADING FILES</h1>
<form name="fupload" enctype="multipart/form-data" action="upfiles.php" method="post">
<input type="file" name="picture" />
<input type="submit" value="Submit" />
</form>
</body>

How do i get the actual image to show on my page rather than the text?

<?php
require 'db.php';
include_once("header.php");
include_once("functions.php");
if(isset($_POST['search_term'])){
$search_term = mysql_real_escape_string(htmlentities ($_POST['search_term']));
if(!empty($search_term)){
$search = mysql_query("SELECT users.username, users.id, tbl_image.photo, tbl_image.userid FROM users LEFT OUTER JOIN tbl_image ON users.id=tbl_image.userid WHERE users.username LIKE '%$search_term%' and users.business <> 'business'");
$result_count = mysql_num_rows($search);
$suffix = ($result_count != 1) ? 's' : '';
echo '<div data-theme="a">Your search for <strong>' , $search_term ,'</strong> returned <strong>', $result_count,' </strong> record', $suffix, '</div>';
while($results_row = mysql_fetch_assoc($search)){
echo '<div data-theme="a"><strong>',$results_row['photo'], $results_row['username'], '</strong></div>';
$following = following($_SESSION['userid']);
if (in_array($key,$following)){
echo ' <div action= "action.php" method="GET" data-theme="a">
<input type="hidden" name="id" value="$key"/>
<input type="submit" name="do" value="follow" data-theme="a"/>
</div>';
}else{
echo " <div action='action.php' method='GET' data-theme='a'>
<input type='hidden' name='id' value='$key'/>
<input type='submit' name='do' value='follow' data-theme='a'/>
</div>";
}
}
}
}
?>
How do i get the actual image to show on the page rather than the name of the image. I have the images in the file system under a folder called image. How do I echo that image on screen or if echo is not the right way to do it how would you do it?
You mean like this?
echo '<img src="'.$results_row['photo'].'" width="80">';

Resources