File upload not working using codeigniter. Have no idea why - php

I am trying to add an, upload an image to a directory in my root. When I hit the submit button for the add image it shows the error in the if statement as if it was false.
I have no idea what I am doing wrong.
To see what I have live visit here: http://travismichael.net/SeniorProject
I have my uploads folder in my root and i made it writable.
Here is my Controller
function do_upload() {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '32';
$config['max_width'] = '200';
$config['max_height'] = '200';
$this->load->library('upload', $config);
if ( !$this->upload->do_upload('userfile'))
{
echo '<p>IMAGE NOT WORKING</p>';
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('partials/upload_success', $data);
}
Here is my View
<!DOCTYPE html>
<?php $this->load->view('partials/page_head'); ?>
<body>
<body class="home">
<div id="container">
<div id="top">
<div class="topcenter">
<h2><a class="addbtn">Add Folder</a></h2>
<h2><a class="deletebtn" href="<?php echo base_url();?>index.php/home/delete">DeleteFolders</a></h2>
</div>
<div class="navdescription"><span>Home</span></div>
</div>
<div class="projectFolders">
<?php foreach($foldername as $row) { ?>
<div class="folder <?php echo $row->folderName; ?>">
<button class="<?php echo $row->folderName; ?>"><?php echo $row->folderName; ?> </button>
</div>
<script>
$(function () {
$('button.<?php echo $row->folderName; ?>').bind('click',
function() { $('.open.<?php echo $row->folderName;?>').show() });
$('.gohome').bind('click',
function() { $('.open.<?php echo $row->folderName;?>').hide() });
});
</script>
<?php } ?>
<?php foreach($foldername as $row) { ?>
<div class="open <?php echo $row->folderName; ?>">
<h1><?php echo $row->folderName;?></h1>
<a class="gohome">Home</a><a class="addimagebtn">Add Image</a>
<div class="edititable" contenteditable="true" focus="true">
Your Content Goes Here
</div>
</div>
<?php } ?>
<div class="uploadimage">
<?php echo form_open_multipart('home/do_upload');?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="Add Image" />
</form>
</div>
</div>
<div id="bottom">
<div class="formWrapper">
<form accept-charset="utf-8" method="post" action="<?php echo base_url(); ?>index.php/home/create" id="cf_form">
<input type="text" name="folderName" placeholder="Enter new Folder" class="required" required/>
<?php echo form_submit('createFolder', 'Create Folder'); ?>
<?php echo form_close(); ?>
<?php echo validation_errors('<p class="error">'); ?>
</div>
</div>
</div><!-- End of container div -->
</body>
</html>

Some reason Codeignitor forgot to update their Documentation.
You need to add this line right above where you call the upload library
$this->upload->initialize($config);

Related

MySQL on PHP need 2 reloads to update the values

I made a message deleter button, but I need 2 reloads to appear the changes...
(The rest of the code work, so it's normal that I don't show you the rest of the code...)
<?php while($r = $replies->fetch()) { ?>
<div class="message" id="<?= $r['id'] ?>">
<div class="profile">
<img class="avatar" src="members/avatars/<?php if(empty(get_avatar($r['id_author']))) { echo "default.png"; } else { echo get_avatar($r['id_author']); } ?>" width="150" height="150">
<h3 style="text-align: center;"><?= get_username($r['id_author']) ?></h3>
</div>
<div class="content">
<div class="date">
<?= date('d F Y - g:iA', strtotime($r['date_hour_post'])) ?>
</div>
<br><br>
<?= htmlspecialchars_decode($r['content']) ?>
<form method="POST"><button name="delete<?= $r['id'] ?>">Test</button></form>
<?php
$test = "delete".$r['id'];
if(isset($_POST[$test])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($r['id']));
$success = "Your message was successfully removed !";
}
?>
</div>
</div>
<br>
<?php } ?>
UPDATE:
I added the deleting code at the top of my php code, and it's working, thanks to Ray Andison
By the way thanks to keidakida too; he helped me to find a solution to my value problem. (And I think he don't know that)
Your form doesn't contain any data (the id to be deleted) or action (page to submit data to)?
<form method="POST" action="thispage.php">
<input id="test" name="test" type="hidden" value="<?= $r['id'] ?>">
<input type="submit">
</form>
UPDATED:
<?
if(isset($_POST[id])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($_POST[id]));
$success = "Your message was successfully removed !";
}
while($r = $replies->fetch()){
echo '
<div class="message" id="'.$r[id].'">
<div class="profile">
<img class="avatar" src="members/avatars/';
if(empty(get_avatar($r[id_author]))){
echo "default.png";
}else{
echo get_avatar($r[id_author]);
}
echo '
" width="150" height="150">
<h3 style="text-align:center;">
'.get_username($r[id_author]).'
</h3>
</div>
<div class="content">
<div class="date">
'.date('d F Y - g:iA', strtotime($r[date_hour_post])).'
</div>
<br>
<br>
'.htmlspecialchars_decode($r[content]).'
<form method="POST" action="thispage.php">
<input id="id" name="id" type="hidden" value="'.$r[id].'">
<input type="submit">
</form>
</div>
</div>';
}
?>
This is how I would code this, you need to change the action="thispage.php" to be the name of itself so it posts to itself, replace with the actual name of your php file
It is because the delete PHP code is at the bottom. Actions such as delete should be at the top of the HTML or while loops before presenting the data. SO try this:
<?php
if(isset($_POST["delete"])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($_POST['delete']));
$success = "Your message was successfully removed !";
}
while($r = $replies->fetch()) { ?>
<div class="message" id="<?= $r['id'] ?>">
<div class="profile">
<img class="avatar" src="members/avatars/<?php if(empty(get_avatar($r['id_author']))) { echo "default.png"; } else { echo get_avatar($r['id_author']); } ?>" width="150" height="150">
<h3 style="text-align: center;"><?= get_username($r['id_author']) ?></h3>
</div>
<div class="content">
<div class="date">
<?= date('d F Y - g:iA', strtotime($r['date_hour_post'])) ?>
</div>
<br><br>
<?= htmlspecialchars_decode($r['content']) ?>
<form method="POST">
<button type="button" name="delete" value="<?php echo $r['id']; ?>">Test</button>
</form>
</div>
</div>
<br>
<?php
}
?>
But you can do the same functionality without any page reload. Check AJAX PHP
Since it would be better and easier with AJAX, this is how it goes:
main.php
<?php
while ($r = $replies->fetch()) { ?>
<div class="message" id="<?= $r['id'] ?>">
<?php echo htmlspecialchars_decode($r['content']) ?>
<button onclick="delete('<?php echo $r['id']; ?>')">Delete</button>
</div>
<br>
<?php } ?>
<script>
function delete(id) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert("Delete successfully");
location.reload();
}
};
xmlhttp.open("POST", "delete.php", true);
// Mandatory for simple POST request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Send id you want to delete
xmlhttp.send("id=" + id);
}
</script>
And make another PHP file name is delete.php like this:
<?php
include 'YOUR_DB_Connect.php';
if(isset($_POST["delete"])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($_POST['delete']));
}
?>

compress the image on upload codeigniter

this is controller.php ie college_panel
public function college_logo($collg_id = '')
{
$this->data['active'] = 'manage_logo';
if ($this->session->userdata("user_login")) {
if ($this->input->post()) {
$config['upload_path'] = './uploads/college_logo';
$config['allowed_types'] = 'jpg|png|jpeg';
$data1['img_name'] = $_FILES['logo_img']['name'];
$this->load->library('upload', $config);
if (!$this->upload->do_upload('logo_img')) {
$upload_error = array('error' => $this->upload->display_errors());
} else {
echo "<script>alert('College Logo upload successfully...');</script>";
$this->session->set_flashdata('College Logo upload successfully', 'updated');
}
$data['collg_id'] = $this->input->post('collg_id');
$data['logo_img'] = $data1['img_name'];
$row = 0;
if ($row == 0) {
$result1 = $this->front->update_table('tbl_college', array('collg_id' => $collg_id), $data);
}
}
$result = $this->front->get_data_where('tbl_college', array('collg_id' => $collg_id));
$data['result'] = $result;
$data['email'] = $this->input->post('email');
$data['password'] = $this->input->post('password');
$data['isactive'] = 1;
$old_data = $this->front->get_data_where('tbl_login', array('isactive' => 1));
$data['old_data'] = $old_data;
$record = $this->front->get_data_where('tbl_college', array('collg_id' => $collg_id));
$data['record'] = $record[0];
$this->load->view('collg_admin/header', $data, $this->data);
$this->load->view('collg_admin/logo', $data);
} else {
redirect(base_url() . 'login');
}
}
this is view code ie logo.php
<div class="container">
<div class="panel panel-default upload">
<div class="panel-heading text-center">
<h2>College Logo</h2>
</div>
<br><br>
<div class="panel-body">
<div class="row">
<center>
<div class="col-md-12">
<?php if (isset($result[0]->logo_img) && !empty($result[0]->logo_img)) {?>
<img class=" img-circle" src="<?php echo base_url(); ?>uploads/college_logo/<?php echo $result[0]->logo_img; ?>" height="200" width="200"><br>
<?php } else {?>
<img style="" src="<?php echo base_url(); ?>assets/images/default_logo.png" height="200" width="600"><br>
<!-- <p>College Logo are not available.</p>-->
<?php }?>
</div>
</center>
<div class="col-md-offset-2 col-md-7">
<form action="<?php echo base_url(); ?>access/college_panel/college_logo/<?php echo $result[0]->collg_id; ?>" method="post" enctype="multipart/form-data" role="form">
<div class="form-group">
<!-- <?php //print_r($result);?>-->
<input type="hidden" name="collg_id" id="id_hh" value="<?php echo $result[0]->collg_id; ?>" autofocus="" class="form-control" style="width: 100px;">
<br><br>
<input class="form-control" type="file" accept="image/*" name="logo_img" value="<?php echo $result[0]->logo_img; ?> " required /><br>
<div class="col-md-offset-2 col-md-8 text-center">
<button class="btn btn-info" onclick="">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
I want to compress image on upload using codeigniter .when i m trying to upload more then 200 kb image size or mor then 200 then it hsould compress the image size on upload image in codeigniter.how to compress the image on upload of image. i just want to compress the image of the file using codeigniter if need more code will help you

I want to pass o/p of following line into controller ie <?php echo $module[$i]->im_name; ?>

This is my code :
if (count($template) >=1) { ?>
<div class="mdl-cell mdl-cell--4-col" id="select">
<div class="mdl-card mdl-shadow--4dp">
<div class="mdl-card__title">
<h2 class="mdl-card__title-text">select <?php echo $module[$i]->im_name; ?> Template</h2>
</div>
<div class="mdl-card__media">
<?php echo $template[0]->iut_tempname; ?>
</div>
<a href="<?php echo base_url("Account/template_list/"); ?>" class="btn btn-info btn-lg">
<span class="glyphicon glyphicon-cog"></span>
</a>
</div>
</div>
<?php
}
I want to pass o/p of this im_name; ?> to controller .
Hope this will help you :
Create a folder uploads in your views folder and use VIEWPATH for the upload_path like this :
$config['upload_path'] = VIEWPATH.'uploads/';
Your code should be like this :
if (isset($_FILES["image_file"]["name"]))
{
$config['upload_path'] = VIEWPATH.'uploads/';
$config['allowed_types']= 'txt|php|html';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('image_file'))
{
echo $this->upload->display_errors();
}
else
{
$data = $this->upload->data();
echo '<img src="'.base_url().'uploads/'.$data["file_name"].'" />';
}
}
For more : https://www.codeigniter.com/user_guide/general/reserved_names.html

Posting Comments to PHP Using Ajax

I'm having this comment form. this comment form works but not correctly whenever I post comment it works on 1 post and on another it refreshes the page and data is also not inserted all the post are fetch by while loop
JS:
< script type = "text/javascript" >
$(function() {
$("#submit").click(function() {
var mcomment = $("input#mcomment").val(); // define the name variable
var mesgid = $("input#mesgid").val();
if (mcomment == '') // if name field is empty
{
alert("Write Comment Please."); // alert an error mesaage
} else {
$.ajax({ // JQuery ajax function
type: "POST", // ajax submit method
url: "status/savecomment.php",
data: 'mcomment=' + mcomment + '&mesgid=' + mesgid, // data sent to php file
cache: false,
success: function(html) { // if the result returns success
$("#comment_display").after(html);
}
});
}
return false;
});
});
< /script>
HTML:
<form method="POST" id="commentform">
<div class="panel-footer p15">
<div class="admin-form">
<img src="image.png">
<label for="reply1" >
<input name="mesgid" id="mesgid" type="hidden" value="
<?php echo $id ?>">
<input name="mcomment" id="mcomment" placeholder="Respond with a
comment." type="text" style="width:130%;">
</label>
<button type="submit" id="submit" class="button
btn-primary submit-btn" name="" style="width:90px; margin-
left:50px;">Comment</button>
</div>
</div>
</form>
here is all new edited code
<?php
$msql=mysql_query("SELECT * from `messages` ORDER BY `msg_id` DESC LIMIT
$post_limit");
while($messagecount=mysql_fetch_array($msql))
{
$id=$messagecount['msg_id'];
$msgcontent=$messagecount['message'];
$usermsg=$messagecount['username'];
$userimg=$messagecount['image'];
$userimg1=$messagecount['user_img'];
$usertime=$messagecount['time'];
?>
<i class="pointer" id="pagination-<?php echo $id;?>"></i>
<div style="display: block;" class="timeline-item" id="clone-3">
<div class="panel">
<div class="panel-heading">
<span class="panel-title" style="color:#000;"><?php echo
ucfirst($usermsg); ?> Updated a </span><a href="post.php?id=<?php echo
$id;?>">Post</a>
<span class="panel-date pull-right mr10 text-muted fs12">
<?php echo timeAgo($messagecount['time']);?> via Web</span>
</div>
<div class="panel-body">
<p><img src="image.php/<?php echo $userimg1;?>?width=60&
height=70&nocache&quality=100&image=http://localhost/niftians/profile
/upload/<?php echo $userimg1;?>" /> <?php echo
parse_smileys(make_clickable(nl2br(stripslashes($msgcontent))),
$smiley_folder); ?><br><br><?php if(!empty($messagecount['image'])) { ?>
<img src="status/image.php/<?php echo
$messagecount['image'];?>?width=350&nocache&quality=100&
image=http://localhost/niftians/profile/upload/<?php echo
$messagecount['image'];?>" style="margin-left:10%;">
<?php } ?></p>
</div>
</div>
</div>
<?php
$sql=mysql_query("select * from comments where msg_id_fk='$id' order by
com_id");
$comment_count=mysql_num_rows($sql);
if($comment_count>2)
{
$second_count=$comment_count-2;
?><div class="comment_ui" id="view<?php echo $id; ?>">
<div>
<a href="#" class="view_comments" id="<?php echo $id; ?>">View all <?php
echo $comment_count; ?> comments</a>
</div>
</div>
<?php
}
else
{
$second_count=0;
}
?>
<div id="view_comments<?php echo $id; ?>"></div>
<div id="two_comments<?php echo $id; ?>">
<?php
$listsql=mysql_query("select * from comments where msg_id_fk='$id' order
by com_id limit $second_count,2 ");
while($rowsmall=mysql_fetch_array($listsql))
{
$c_id=$rowsmall['com_id'];
$comment=$rowsmall['comments'];
$userid3=$rowsmall['username'];
$userimg5=$rowsmall['user_img'];
$usercom=$rowsmall['time'];
?> <div id="comment_display"></div>
<div class="media mt15" id="aniket">
<a class="pull-left" href="#"> <img class="media-
object thumbnail thumbnail-sm rounded mw40" src="image.php/<?php echo
$userimg5;?>?width=60&height=60&nocache&quality=100&
image=http://localhost
/niftians/profile/upload/<?php echo $userimg5;?>" alt="..."> </a>
<div class="media-body mb5">
<h5 class="media-heading mbn"><a href="<?php echo
$userid3; ?>"><?php echo ucfirst($userid3); ?></a>
<small> -<?php echo timeAgo($rowsmall['time']);?>
</small>
</h5>
<p><?php echo
parse_smileys(make_clickable(nl2br(stripslashes($comment))),
$smiley_folder); ?></p>
</div>
</div>
<?php } ?>
</div>
<form method="POST" id="commentform">
<div class="panel-footer p15">
<div class="admin-form">
<img src="image.php/<?php echo $info->img;?>?width=45&nocache&
quality=100&image=http://localhost/niftians/profile/upload/<?php echo
$info->img;?>">
<label for="reply1" >
<input name="mesgid" id="mesgid" type="hidden" value="<?php echo $id ?>">
<input name="mcomment" id="mcomment" placeholder="Respond with a
comment." type="text" style="width:130%;">
</label>
<button type="submit" id="submit" class="button
btn-primary submit-btn" name="" style="width:90px; margin-
left:50px;">Comment</button>
</div>
</div>
</form>
<br>
<?php
}
?>
What you need to do is
Remove Submit Button and add <input type="button">
2nd create a div in your page named as <div id="comment_display"></div>
And if this does not solve problem, post your While loop.
Replace this line
$("#submit").click(function() {
with
$("#submit").on('.submit','click',function(e) {
e.preventDefault();
Note: Your submit can work too, but you would have to stop its default behavior using jquery

CodeIgniter - last else if statement fail to meet the condition

I think it's just a simple mistake I've made, but until now I still can't get the solution why my last else if {} statement does not execute when it meets the condition.
It's my form. I have 3 form elements as options for users to enter value. They can choose either to upload which are text, photo, or movie. Here is my PHP:
if ( $this->input->post('text') !== '') {
//this executes fine when it meets the condition
} else if ( $this->input->post('photo') !== '' ) {
// this also works fine
} else if ( $this->input->post('video') !== '' ) {
/* however, I can't get to this condition when
the user chooses to upload the movie.
It always go the second condition.
*/
}
Edit:
Here's my view:
<form action="<?php echo base_url()?>action/post" method="post" enctype="multipart/form-data">
<ul class="nav nav-tabs">
<li class="active">
Update Status
</li>
<li>
Post Photos
</li>
<li>
Post Videos
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="status">
<textarea name="text"></textarea>
</div>
<div class="tab-pane" id="photos">
<input type="file" name="photo" class="input" />
<input type="text" name="photos-detail" placeholder="description" />
</div>
<div class="tab-pane" id="videos">
<input type="file" name="video" class="input" />
<input type="text" name="videos-detail" placeholder="description" />
</div>
</div>
<button type="submit" class="btn btn-primary" name="post">Post</button>
</form>
Any idea would be really appreciated.
You cant check file inputs reliably like that. I usually check the file size to see if anything has been uploaded, so you could do something like this (should work):
if ( $this->input->post('text') !== '') {
//code
} else if((isset($_FILES["photo"]["size"])) && ($_FILES["photo"]["size"] > 0)){
// code 2
} else if((isset($_FILES["video"]["size"])) && ($_FILES["video"]["size"] > 0)){
// code 3
}
NOTE
You can't just check the file size or you will get undefined index error - hence the isset()
If I use the same code the result that I get is that my view show me the entire code line.
if ( $usuario->party !== '') {
<img src="<?php echo base_url('assets/img/link/sprite1_13.png') ?>">
} else {
<img src="<?php echo base_url('assets/img/link/party.png') ?>">
}
If I don´t use my code works fine:
<?php foreach ($usuarios->result() as $usuario) { ?>
<div id="cuerpo" class="cuerpoMyPerfil">
<div id="columna1">
<div id="contenColumn1" class="corner">
<div class="myFoto">
<img src="<?php echo base_url('assets/img/testimonials/user.jpg') ?>" width="100%" height="auto" alt="nombre" /> </div>
<div class="myNombre">
<?php
echo $usuario->nombre . "<br/>";
echo $usuario->apellidos;
?>
</div>
<div class="myDescripcion">
<?php echo $usuario->acerca; ?>
</div>
if ( $usuario->party !== '') {
<img src="<?php echo base_url('assets/img/link/sprite1_13.png') ?>">
} else {
<img src="<?php echo base_url('assets/img/link/party.png') ?>">
}
<dl class="dl-vertical">
<!-- Verificar que tenga valores en la tabla vincular
Si lo trae, poner el ícono prendido, de lo contrario el apagado-->
<dt>
<img class="pull-right" src="<?php echo base_url('assets/img/link/love.png') ?>"></dt>
<dt><img src="<?php echo base_url('assets/img/link/network.png') ?>">
<img class="pull-right" src="<?php echo base_url('assets/img/link/friends.png') ?>"></dt>
</dl>
</div>
<div class='myTextInvi'>
<div class='textInvitacionActual floatL'>Tienes Invitaciones disponibles</div>
<div class='numInvitacionActual floatL' ><?php echo $usuario->disponibles; ?></div>
</div>
<div class='myBtnInvi'>
<a href="<?php echo base_url('oneperfil/invite') ?>">
<div class='textBtnInvitacion'>ENVIAR INVITACIÓN</div>
</a>
</div>
</div>
</div>
<?php } ?>

Categories