PHP form only returning empty array - php

I am working on a code segment that is a messaging function next to a list of names. On the page there is an envelope and when you click it a pop-up window appears with a text area inside of it. I would like to be able to fill that textarea with characters and send it as a message using my already functioning sendMessage function. I know my sendMessage function works and I've isolated the issue to the return given by the submit button. How do I get my submit button to POST the textarea to the page (keep in mind there are 2+ forms on this page). The code looks like this:
if (empty($_POST) === false) {
print_r($_POST);
$blah = $_POST;
echo "<script>window.top.location='asd.$blah'</script>";
}
if (empty($_POST['Send']) === false) {
echo "<script>window.top.location='../hidden/PNMasdd.php?gpa=$var1&year=$var2&major=$var3&sport=$var4'</script>";
echo 'YOU ARE IN THE SENDING MESSAGE FIELD';
if( empty ($_POST['message_full']))
{
$errors[] = 'All fields must be filled in!';
//print_r($errors);
}
if(empty($_POST) === false && empty($errors) === true)
{
$receiver_id = $temp_user['id'];
$sender_id = $user_data['id'];
$type = 0;
if(empty($is_Convo))
{
$is_Convo = 0;
}
$blahVar = $user_data['id'] . ',';
$message = str_replace("\r\n", "<br>", $_POST['message_full']);
$message_data = array(
'sender_id' => $user_data['id'],
'receiver_id' => $receiver_id,
'message_full' => $message,
'is_opened' => $blahVar,
'isConvo' => $is_Convo,
'type' => $type
);
//Put data limit code here
send_message($message_data);
$my_exten = "Messages/messages.php";
$noti_data = array(
'id_receive' => $receiver_id,
'id_sent' => $user_data['id'],
'type' => 1,
'exten' => $my_exten
);
notify($noti_data);
echo '<center>';
echo '<div class="alert alert-info">
<strong>It sent!</strong> You have sent a message successfully!
</div>
';
echo '</center>';
}
else{
echo output_errors($errors);
}
}
?>
<form id="wow" name="wow" action="" method="POST">
<div class="row">
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<center>
<textarea maxlength="100000" data-msg-required="Please enter your message." rows="10" cols="100%" class="form-control" name="message_full" id="message_full"></textarea>
</center>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<table width=90%><td width=45%><button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button></td><td width=45%>
<button type="submit" value="Send Message" name="Send" onclick="document.getElementById('wow').submit()" class="btn btn-primary">Send</button>

As pointed out in the comments, the buttons need to be inside your form.
Your setup is a bit odd for my taste, but try this out.. it will mostlikely need some tweaks and i'm not sure about the cancel button..
<form id="wow" name="wow" action="" method="post" >
<div class="form-group required">
<div class="col-md-12">
<textarea name="message_full" id="message_full" rows="10" cols="100%" class="form-control" maxlength="10000" placeholder="Please enter your message." autocomplete="off"></textarea>
</div>
</div>
<div class="buttons"> <!-- add css for this or change the class to yours.. -->
<input class="btn btn-default" data-dismiss="modal" value="Cancel" />
<input class="btn btn-primary" type="submit" value="Send Message" />
</div>
</form>

As #Barmar just said, you don't have any field named 'Send'. You should change:
if (empty($_POST['Send']) === false)
to:
if (empty($_POST['message_full']) === false)
(Edit)
Only the fields inside your form will get to $_POST superglobal, the submit button will not get there

Related

Breaking login flow if already logged in with another session

I am working on a codeigniter 3 app and ive recently implemented a session checker that deletes a user session if they're already logged in. Now we want a modal box to pop up if the user is already logged in with another session. I am able to get a modal box to pop up using a button but i want to implement it into the original flow of the login system. As it is the login form takes you straight to the validate login system. This is the login form now:
<form action="<?php echo site_url('login/validate_login/user'); ?>" method="post">
<div class="content-box">
<div class="basic-group">
<div class="form-group">
<label for="login-email"><span class="input-field-icon"><i class="fas fa-envelope"></i></span> <?php echo get_phrase('email'); ?>:</label>
<input type="email" class="form-control" name = "email" id="login-email" placeholder="<?php echo get_phrase('email'); ?>" value="" required>
</div>
<div class="form-group">
<label for="login-password"><span class="input-field-icon"><i class="fas fa-lock"></i></span> <?php echo get_phrase('password'); ?>:</label>
<input type="password" class="form-control" name = "password" placeholder="<?php echo get_phrase('password'); ?>" value="" required>
</div>
</div>
</div>
<div class="content-update-box">
<button type="submit" class="btn"><?php echo get_phrase('login'); ?></button>
</div>
<!-- Modal -->
<div class="modal fade" id="login" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">You are already logged in</h4>
</div>
<div class="modal-body">
<p>You are currently logged in on a different session on the site. Please note that if you continue, the existing session will be terminated. Please change your password if you suspect that your account has been conpromised.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel Login</button>
<button type="submit" class="btn"><?php echo get_phrase('login'); ?></button>
</div>
</div>
</div>
</div>
<div class="forgot-pass text-center">
<span><?php echo get_phrase('or'); ?></span>
<?php echo get_phrase('forgot_password'); ?>
</div>
<div class="account-have text-center">
<?php echo get_phrase('do_not_have_an_account'); ?>? <?php echo get_phrase('sign_up'); ?>
</div>
</form>
The button at the moment goes straight to this login function:
public function validate_login($from = "") {
$email = $this->input->post('email');
$password = $this->input->post('password');
$credential = array('email' => $email, 'password' => sha1($password), 'status' => 1);
// Checking login credential for admin
$query = $this->db->get_where('users', $credential);
if ($query->num_rows() > 0) {
$row = $query->row();
$this->session->set_userdata('user_id', $row->id);
$this->session->set_userdata('role_id', $row->role_id);
$this->session->set_userdata('role', get_user_role('user_role', $row->id));
$this->session->set_userdata('name', $row->first_name.' '.$row->last_name);
$this->delete_session_user_id();
$this->session->set_flashdata('flash_message', get_phrase('welcome').' '.$row->first_name.' '.$row->last_name);
if ($row->role_id == 1) {
$this->session->set_userdata('admin_login', '1');
redirect(site_url('admin/dashboard'), 'refresh');
}else if($row->role_id == 2){
$this->session->set_userdata('user_login', '1');
$this->set_session_user_id();
redirect(site_url('home/my_courses'), 'refresh');
}
}else {
$this->session->set_flashdata('error_message',get_phrase('invalid_login_credentials'));
redirect(site_url('home/login'), 'refresh');
}
}
I created this function to pull the user id from the emails:
public function get_user_id($user_email = "") {
$this->db->select('id');
$this->db->where('email', $user_email);
$user_id=$this->db->get('users');
return $user_id;
}
This function can get the user id based on the email supplied.
Then I use this function to check if there is a session and return false if there are 0 results and true if there is a session with that user id. So if its false they should be able to log in and the modal pop-up shouldnt open but if its true it should open.
public function user_has_session($user_id=''){
$this->db->where('user_id',$user_id);
$this->db->from('ci_sessions');
$total=$this->db->count_all_results();
if($total<0)
return false;
else
return true;
}
I think this is the best approach without having to redo the entire login flow. Perhaps someone can advise if this is the best approach or if in fact i should change the entire flow.
Thanks
Here is the previous problem I had which I have answered myself
https://stackoverflow.com/questions/62458226/codeigniter-3-stop-multiple-logins-using-ci-sessions-database
UPDATE Added to clarify my problem
Well the problem is when a login is attempted from another device it should logout the other active session. So if o logged in on my desktop in a new browser or even my phone with the same user ID the active session should end, at the moment it does so without warning the user. So I want to have a modal pop up warning the user that there is an active session currently running with this user id
You need to implement an Ajax call which will check whether the user is already logged in or not. If the user is not logged In than you can proceed to login otherwise trigger your popup open to display the message.
Here the user has choices to log in or not, If users choose to login then you can unbind the event on submit and let the user go ahead.
I have made some changes to your HTML file. Please check below -
Your HTML template
<form action="<?php echo site_url('login/validate_login/user'); ?>" id="login-form" onSubmit="return checkUserSession();" method="post">
<div class="content-box">
<div class="basic-group">
<div class="form-group">
<label for="login-email"><span class="input-field-icon"><i class="fas fa-envelope"></i></span> <?php echo get_phrase('email'); ?>:</label>
<input type="email" class="form-control" name = "email" id="login-email" placeholder="<?php echo get_phrase('email'); ?>" value="" required>
</div>
<div class="form-group">
<label for="login-password"><span class="input-field-icon"><i class="fas fa-lock"></i></span> <?php echo get_phrase('password'); ?>:</label>
<input type="password" class="form-control" name = "password" placeholder="<?php echo get_phrase('password'); ?>" value="" required>
</div>
</div>
</div>
<div class="content-update-box">
<button type="submit" class="btn"><?php echo get_phrase('login'); ?></button>
</div>
<!-- Modal -->
<div class="modal fade" id="login" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">You are already logged in</h4>
</div>
<div class="modal-body">
<p>You are currently logged in on a different session on the site. Please note that if you continue, the existing session will be terminated. Please change your password if you suspect that your account has been conpromised.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel Login</button>
<button type="button" id="modal-submit-button" class="btn"><?php echo get_phrase('login'); ?></button>
</div>
</div>
</div>
</div>
<div class="forgot-pass text-center">
<span><?php echo get_phrase('or'); ?></span>
<?php echo get_phrase('forgot_password'); ?>
</div>
<div class="account-have text-center">
<?php echo get_phrase('do_not_have_an_account'); ?>? <?php echo get_phrase('sign_up'); ?>
</div>
</form>
<script>
/** Trigger function on form submit whether to check user logged in */
function checkUserSession(){
var email = $("#login-email").val();
$.ajax({
url: "<?php echo site_url('login/checkUserSession'); ?>",
type: 'POST',
data: { 'email': email},
success: function(status){
if(status == true) { // User is already logged in somewhere, display the messege.
$("#login").modal();
return false;
} else { // User is not logged in, submit the form
return true;
}
}
});
}
/** Allow user to log in with exception */
$("#modal-submit-button").on("click", function(){
$("#login").modal('hide'); // hide the modal
$("#login-form").attr("onSubmit", ""); // unbind the function
$("#login-form").submit(); // submit login form
})
</script>
Controller -
<?php
/** Function to check user logged in or not */
public function checkUserSession() {
$user_email = $this->input->post('email');
$userId = $this->get_user_id($user_email);
$response = $this->user_has_session($userId);
echo $response;
}
public function get_user_id($user_email = "") {
$this->db->select('id');
$this->db->where('email', $user_email);
$user_id=$this->db->get('users');
return $user_id;
}
public function user_has_session($user_id=''){
$this->db->where('user_id',$user_id);
$this->db->from('ci_sessions');
$total=$this->db->count_all_results();
if($total<0)
return false;
else
return true;
}
?>

Passing value to database through if else statement

My Form Look like this, here i wanted to send grade of Nepali subject database by taking and converting numeric marks from form mepali_th_num but what ever input numeric mark are it only send 'E' Grade to database after conversion of grade. What is wrong in this code mainly in if else part.
<form class="form-horizontal" method="post">
<div class="box-body">
<div class="form-group">
<label for="nepali_th_num" class="col-sm-2 control-label">Nepali(TH)
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="nepali_th_num"
name="nepali_th_num" step="any" min="0">
</div>
</div>
<div class="box-footer">
<button type="submit" name="btnSave" class="btn btn-
primary">Submit</button>
<button type="reset" class="btn btn-info">Reset</button>
</div>
</form>
my php look like this:
if (isset($_POST['btnSave'])){
$marksdetails = new Marksdetails();
$marksdetails->set('nepali_th_num', $_POST['nepali_th_num']);
$nep_per=((('nepali_th_num')*100)/75);
if($nep_per>=90){
$nepali_th_grade='A+';
}elseif ($nep_per>=80 && $nep_per<90) {
$nepali_th_grade='A';
}elseif ($nep_per>=70 && $nep_per<80){
$nepali_th_grade='B+';
}elseif($nep_per>=60 && $nep_per<70) {
$nepali_th_grade='B';
}elseif($nep_per>=50 && $nep_per<60){
$nepali_th_grade='C+';
}elseif($nep_per>=40 && $nep_per<50){
$nepali_th_grade='C';
}elseif($nep_per>=30 or $nep_per<40){
$nepali_th_grade='D+';
}elseif($nep_per>=20 or $nep_per<30){
$nepali_th_grade='D';
}else{
$nepali_th_grade='E';
}
$marksdetails->set('nepali_th_grade', $nepali_th_grade);
$marksdetails->set('symbol_number', $symbolnumber);
$marksdetails->set('student_name', $studentname);
$status=$marksdetails->checkDuplicate(); //to check duplicate and sql part
is in this
}
nepali_th_num in this line
$nep_per=((('nepali_th_num')*100)/75);
is just a string, its not a variable containing something useful
Try
$nep_per=((($_POST['nepali_th_num'])*100)/75);

How to insert zero rows in codeigniter

I'm click my submit button freely without enter values in the form..then in my database a row inserted that columns contain zeros
controller
function submit_expense()
{
$exp_date=$this->input->post('expense_date');
$expense_ids= $this->input->post('expense');
$expense_ids=substr($expense_ids,0,strlen($expense_ids)-1);
$expense_id_array = explode(',',$expense_ids);
$id=$this->session->userdata('userid');
for($i=0;$i<count($expense_id_array);$i++)
{
$required_id = TRIM($expense_id_array[$i]);
$this->form_validation->set_error_delimiters('<div style="color:#B94A48">', '</div>');
$this->form_validation->set_rules('exp_amount_'.$required_id, 'Expense Amount', 'required|numeric');
$this->form_validation->set_rules('comment_'.$required_id, 'Comments', 'required|alpha');
if ( $this -> form_validation -> run() === FALSE )
{
$this->index();
}
else
{
$amount= $this->input->post('exp_amount_'.$required_id);
$comment=$this->input->post('comment_'.$required_id);
$expense_data=array(
'expense_id'=>$required_id,
'expense_amount'=>$amount,
'user_id'=>$id,
'date'=>$exp_date,
'comments'=>$comment,
);
$this->home_model->insert_expense($expense_data);
$this->session->set_flashdata('message', 'Successfully submitted.');
redirect(base_url().'home/index');
}
}
}
And also my validation is not working
footer_view
var new_String ='<div class="form-group" id="ex_'+unqid1+'">'
+'<label for="exampleInputPassword1">'+name+'</label> </br>'
+'<input name="exp_amount_'+unqid1+'" id="id_'+unqid1+'" type="text" '+
'class="form-control" placeholder="Enter '+name+' expense amount" style="margin-right:20px;" required>'
+'<input name="comment_'+unqid1+'" type="text" id="comment" class="form-con" placeholder="Comments" style="margin-right:20px;" required ></div >' ;
$("#create_exp").append(new_String);
view
this is my view use the id create_exp in my footer
<form role="form" action="<?echo base_url()?>home/submit_expense" method="post">
<?$todays_date=date('Y-m-d');?>
<input id="expense_date" name="expense_date" value="<?echo $todays_date;?>" type="hidden" />
<div class="red">
<? echo $this->session->flashdata('message'); ?>
</div>
<div class="box-body" id="create_exp">
<?php echo validation_errors(); ?>
<span>Choose from the right which all you need to enter for today</span>
<!--here goes the input boxes-->
<!-- /.input boxes -->
</div><!-- /.box-body -->
<span id="errmsg1"></span>
<input id="expenseVal" name="expense" type="hidden" class="form-control">
<div class="box-footer" id="button_id">
<button type="submit" class="btn btn-primary" >Submit</button>
</div>
</form>
As the OP Wants to show the all the Errors inside a div
<div id="error">
<?php echo validation_errors(); ?>
</div>
As the OP Wants some additional info,
To include a view or common page
$this->load->view('yourownpage');
Then you should have yourownpage.php inside your views folder
To have pagination, Have this in your controller's function
$this->load->library('pagination');
$config['base_url'] = 'yourownpage';
$config['total_rows'] = 200;
$config['per_page'] = 20;
$this->pagination->initialize($config);
echo $this->pagination->create_links();
Note :
Make sure to place the error div in the place that didn't hurt your textbox

CodeIgniter Button does not Trigger Action

I have been searching through various questions on the site with no luck. The closest I got to an answer, as far as I can tell, was through the following question: CodeIgniter's form action is not working properly.
The problem is that when I press the login button nothing happens so the action property in the HTML form is not being triggered. I have looked at my routes as well with no luck.
The HTML code is in my view folder and is the following:
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-body">
<form role="form" method="post" action="<?php echo base_url() ?>index.php/login">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Username" name="username" type="username" required>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" required>
</div>
<a type="submit" id="login-button" style="navy" class="btn btn-lg btn-success btn-block">Login</a>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
My controller is called pages.php, and it's function, login is the following:
public function login()
{
$this->load->helper('form');
$username = $this->input->post('username');
$password = $this->input->post('password');
if ($username != false && $password != false)
{
$loginDetails = $this->pages_model->retrieveLoginDetails($username, $password);
if ($loginDetails != false)
{
if ($loginDetails['username'] == $username && $loginDetails['password'] == $password)
{
$this->load->view ('home');
}
else
{
$this->view();
echo "details dont match";
}
}
else
{
$this->view();
echo "nothing received from db";
}
}
else
{
$this->view();
echo "no details entered";
}
}
I am only concerned with going to the home page. By calling the view function I am just returning to the login screen. I will adjust the naming appropriately once I can get this to work. The pages model contains the following function to retrieve the login data from the database:
public function retrieveLoginDetails ($username, $password)
{
$loginDetails['username'] = $this->db->get_where('user_details', $username);
if (! empty ($loginDetails['username']))
{
$loginDetails['password'] = $this->db->get_where('user_details', $password);
return $loginDetails;
}
return false;
}
Any help would be greatly appreciated. Thanks.
Use
<input type="submit" value="Login" class="btn btn-lg btn-success btn-block" />
In place of
<a type="submit" id="login-button" style="navy" class="btn btn-lg btn-success btn-block">Login</a>
To know more check out this : http://www.w3schools.com/tags/tag_a.asp
I don't know direct anwser, but did you check what exactly is your server returning and where are data beeing sent. LiteBug FTW ;)
If there isn't any data beeing sent, you should probally check your .js files.

Codeigniter multi forms on one page validation errors

I have two forms in my page. when I submit either of the form, both of them show the same validation error message. I used
if (isset ($_POST['click_cus_button']))
to check what button is licked in the from seems it does not work for me.
Can anyone tell me why this bit of code isn't working?
this is my controller (admin.php)
function add_users_data()
{
if (isset ($_POST['click_cus_button']))// click_cus_button is set load this validation errors
{
$this->form_validation->set_rules('cus_name', 'Name', 'trim|required|min_length[5]');
// validate name
$this->form_validation->set_rules('cus_email', 'Email', 'trim|required|valid_email');
// validate email
$this->form_validation->set_rules('cus_phone', 'Phone Number', 'trim|required|min_length[10]|max_length[10]');
// validate phone number
$this->form_validation->set_rules('cus_password', 'Password', 'required|matches[cus_passconf]');
// validate password
$this->form_validation->set_rules('cus_passconf', 'Retype Password', 'required');
// validate password
if ($this->form_validation->run() == FALSE)// if from validation failed load following pages from views
{
$this->load->view('admin/admin_add_users.php');
}
else // if from validation success load following pages from views
{
$data = array(
'cus_name' => $this->input->post('cus_name'),
'cus_email' => $this->input->post('cus_email'),
'cus_mobile' => $this->input->post('cus_mobile'),
'cus_phone' => $this->input->post('cus_phone'),
'cus_status' => $this->input->post('cus_status')
//'database_field' => $this->input->post('text_box_name')
);
$this->mod_users->add_record($data);//add a comment
$data['result']="Customer Added Successfully ";
$this->load->view('admin/admin_add_users.php',$data);
}
}
else if (isset ($_POST['click_oper_button']))// click_oper_button is set load this validation errors
{
$this->form_validation->set_rules('oper_firstname', 'Name', 'trim|required|min_length[5]');
// validate name
$this->form_validation->set_rules('oper_lastname', 'Name', 'trim|required|min_length[5]');
// validate name
if ($this->form_validation->run() == FALSE)// if from validation failed load following pages from views
{
$this->load->view('admin/admin_add_users.php');
}
else // if from validation success load following pages from views
{
$data['result']="Customer Added Successfully ";
$this->load->view('admin/admin_add_users.php',$data);
}
}
}
this is my View (admin_add_users.php)
I removed some fields to make the code shorter in the view
<?php echo form_open('admin/add_users_data') ?><!-- start of the form -->
<div class="span8">
<div style="padding-bottom:11px;">
<div class="div add_cus box"><!-- start of the add customer add form -->
<?php echo validation_errors('<div class="notice marker-on-bottom bg-darkRed fg-white" id="bottom_form_error">', '</div>'); ?>
<?php
if(isset($result))
{
echo '<div class="notice marker-on-bottom bg-green fg-white">'.$result.'</div>';
}
?>
<!-- Display Validation error massages -->
<feildset>
<legend><i class="icon-user-2 on-right on-left"></i><strong>Add Customer</strong></legend>
<input name='cus_status' type='hidden' value='disabled'/>
<input type="submit" value="Add Customer" class="info" name="click_cus_button">
</feildset>
</div><!-- END of the add customer add form -->
</div>
<div class="div add_oper box"><!-- start of the add Operator add form -->
<?php echo validation_errors('<div class="notice marker-on-bottom bg-darkRed fg-white" id="bottom_form_error">', '</div>'); ?>
<?php
if(isset($result))
{
echo '<div class="notice marker-on-bottom bg-green fg-white">'.$result.'</div>';
}
?>
<feildset>
<legend><i class="icon-user on-right on-left"></i><strong>Add Operator</strong></legend>
<h6>*All fields marked are required</h6>
<lable>Name*</lable><br>
<div class="input-control text size6" data-role="input-control">
<input type="text" name="oper_firstname" placeholder="First Name">
</div>
<div class="input-control text size6" data-role="input-control">
<input type="text" name="oper_lastname" placeholder="Last Name">
</div>
<br>
<div class="input-control radio default-style" data-role="input-control">
<label>
Gender*<br>
<input type="radio" checked="" name="oper_gender">
<span class="check"></span>
Male
</label>
</div>
<div class="input-control radio default-style" data-role="input-control">
<label>
<input type="radio" name="oper_gender">
<span class="check"></span>
Female
</label>
</div>
<br>
<lable>Date of Birth*</lable>
<div class="input-control text" data-role="input-control">
<input id="datepicker" name="oper_dob" type="text">
</div>
<lable>Address*</lable><br>
<div class="input-control text size1" data-role="input-control">
<input type="text" name="oper_add_no" placeholder="No">
</div>
<input type="submit" value="Add Operator" class="info" name="click_oper_button">
</feildset>
</div><!-- END of the add Operator add form -->
<div class="div add_admin">
RadioButton 3 Selected
</div>
</div>
<?php echo form_close(); ?><!-- END of the form -->

Categories