currently I do a checking function to know email already exist or not in db. If exist then error, if not update data. But if existing user edit their data such as weight. Then it will give error because it detect email already exist. But the user only edit the weight data, not the email. can anyone help me how to solve this problem or have any recommendation to do this part. I'm using a CodeIgniter framework.
This is my controller
if (!empty($this->input->post()))
{
$data["weight"] = $this->input->post("weight");
$data["height"] = $this->input->post("height");
$data["username"] = $this->input->post("username");
$data["email"] = $this->input->post("email");
if (strlen($this->input->post("username")) < 6)
{
$result = $this->Global_model->GenerateOutputMsgArray("0", "Username should be at least 6 alphanumerics, please try again.");
}
elseif (!$this->Profile_model->ValidateEmail($this->input->post()))
{
$result = $this->Global_model->GenerateOutputMsgArray("0", "Email has been taken, please try another.");
} else {
$result["status"] == "1";
$this->Profile_model->UpdateProfile($data["weight"], $data["height"], $data["username"], $data["email"]);
$result = $this->Global_model->GenerateOutputMsgArray("1", "Your profile has been updated.", $data);
}
this is my model (validate email function and update data)
public function ValidateEmail($post)
{
$stat = "0";
$msg = "";
$data = array();
$output = array();
$query = $this->db->get_where("user", array("email" => $post["email"]));
$result = $query->row();
$result = (array)($result);
return ($result) ? false : true;
}
function UpdateProfile($weight, $height,$username, $email)
{
$data= array(
"weight" => $weight,
"height" => $height,
"username" => $username,
"email" => $email
);
$this->db->where("user_id", $this->session->userdata("user_id"));
$this->db->update("user", $data);
}
````````````````
You must be having user_id with email.
Try with this one.
public function ValidateEmail($post)
{
$stat = "0";
$msg = "";
$data = array();
$output = array();
$query = $this->db->get_where("user", array("email" => $post["email"]));
if($query->num_rows() > 0){
$result = $query->row();
if($result->user_id == $this->session->userdata("user_id")){
return false; // force doesn't exist
}else{
return true; // exists
}
}else{
return false; // as there is no row returned. it will return as doesn't exist
}
}
Related
I am trying to create an api which enables login for email id and password or mobile number and password in codeigniter but i was unable to do both i don't know the error. Here is my code of controller
Controller code
public function signin()
{
$this->default_file();
$responseData = array();
if(!empty($_POST['username']))
{
$userData = array();
$get_number = $this->validate_mobile($_POST['username']);
if(!empty($get_number))
{
$userData['usermob'] = $_POST['username'];
}
else
{
$userData['useremail'] = $_POST['username'];
}
$userData['userpass'] = $_POST['userpass'];
$userSignIn = $this->apm->signin($userData);
if((((!empty($userSignIn['id'])) && (!empty($userSignIn['useremail']))) ||((!empty($userSignIn['id'])) && (!empty($userSignIn['usermob'])))))
{
$session_data = array('id'=> $userSignIn['id'], 'logged_in'=> true);
$this->session->set_userdata('userLoggedIn', $session_data);
$userDetails = array();
$userDetails['id'] = $userSignIn['id'];
$getUserDetails = $this->apm->getUserDetails($userDetails);
$responseData['id'] = $getUserDetails['result']['u_id'];
$responseData['username'] = $getUserDetails['result']['username'];
$responseData['useremail'] = $getUserDetails['result']['useremail'];
$responseData['usermob'] = $getUserDetails['result']['usermob'];
$responseData['userlocation'] = $getUserDetails['result']['userlocation'];
$responseData['device_token'] = $getUserDetails['result']['device_token'];
$responseData['device_name'] = $getUserDetails['result']['device_name'];
$responseArray = array(
'apiName' => 'signin',
'version' => '1.0.0',
'responseCode' => 200,
'responseMessage' => 'logged in successfully',
'responseData' => $responseData
);
}
else
{
$responseArray = array(
'apiName' => 'signin',
'version' => '1.0.0',
'responseCode' => 204,
'responseMessage' => "Email or Passwor is incorrect.",
'responseData' => null//$responseData
);
}
}
else
{
$responseArray = array(
'apiName' => 'signin',
'version' => '1.0.0',
'responseCode' => 204,
'responseMessage' => "Sorry, please provide your input details.",
'responseData' => null//$responseData
);
}
echo json_encode($responseArray);
die();
}
My modal Code is here
public function signin($userData)
{
$arrData = array();
if(!empty($userData['useremail']) || !empty($userData['usermob']))
{
if(!empty($userData['useremail']))
{
$where = "useremail='".$userData['useremail']."'";
}
if(!empty($userData['usermob']))
{
$where = "usermob='".$userData['usermob']."'";
}
$this->db->select('*');
$this->db->from('users');
$this->db->where($where);
$result = $this->db->get()->result_array();
if(!empty($result))
{
if(!empty($userData['useremail']))
{
if(($userData['useremail']) && ($userData['userpass']))
{
$where = "useremail='".$userData['useremail']."' AND userpass='".$userData['userpass']."'";
$this->db->select('*');
$this->db->from('users');
$this->db->where($where);
$res = $this->db->get()->result_array();
if(!empty($res))
{
$arrData['id'] = $res[0]['u_id'];
$arrData['useremail'] = $res[0]['useremail'];
}
else
{
$arrData['errorLogin'] = 'Incorrect email or password';
}
}
}
if(!empty($userData['usermob']))
{
if(($userData['usermob']) && ($userData['userpass']))
{
$where = "usermob='".$userData['usermob']."' AND userpass='".$userData['userpass']."'";
$this->db->select('*');
$this->db->from('users');
$this->db->where($where);
$res = $this->db->get()->result_array();
if(!empty($res))
{
$arrData['id'] = $res[0]['u_id'];
$arrData['usermob'] = $res[0]['usermob'];
}
else
{
$arrData['errorLogin'] = 'Incorrect email or password';
}
}
}
}
else
{
$arrData['error'] = 'Please Enter username and password';
}
}
return $arrData;
}
I was trying to login with email and mobile number but my code gives only one access either with email or with mobile. i want help so that i can login with email and mobile number both.
I have tested this code using Postman, hope it can help:
public function signin($userData)
{
//get the data using useremail and userpass
$this->db->where('useremail', $userData['useremail']);
$this->db->where('userpass', $userData['userpass']);
$result = $this->db->get('users')->result_array();
//if there's no result, get the data using usermob and userpass
if (!$result) {
$this->db->where('usermob', $userData['usermob']);
$this->db->where('userpass', $userData['userpass']);
$result = $this->db->get('users')->result_array();
}
//if there's still no result, the username or password was incorect
if (!$result) {
$result = 'Wrong Username or Password';
}
return $result;
}
How I can let user login from android app, using codeigniter api.
JSON response..
I want use password_hash and password_verify method for more security.
I tryed to password_verify in model, but getting error 1 wrong password. If I debug my app I can see it tries to post password what is not encrypted, but I think this password must be checked in Model.
controller:
public function login() {
$response = array("success" => 0, "error" => 0);
if (isset($_POST['email']) && $_POST['email'] != '') {
$device_token = $_POST['device_token'];
$email = $_POST['email'];
$password = $_POST['password'];
$device_type = $_POST['device_type'];
$data = $this->Registration_model->login($email,$password,$device_token,$device_type);
if ($data) {
$user_id = $data['u']->id;
$status_level = $this->Freelancer_model->service_level($user_id);//Bronze,silver..
$discount = $this->Registration_model->discountDetails($user_id);
if (!empty($discount)) {
$discount = $discount;
} else {
$discount ='';
}
if ($data['u']->approve_status == 1) {
$response["error"] = 0;
$response["success"] = 1;
$response["message"] = "success";
$image = base_url().'upload/'.$data['u']->user_image;
$response["data"]["user_id"] = $data['u']->id;
$response["data"]["user_image"] = $image;
$response["data"]["user_type"] = $data['u']->user_type;
$response["data"]["referral_code"] = $data['u']->referral_code;
$response["data"]["device_token"] = $data['u']->device_token;
$response["data"]["company_name"] = $data['u']->company_name;
$response["data"]["reg_no"] = $data['u']->registration_no;
$response["data"]["first_name"] = $data['u']->first_name;
$response["data"]["last_name"] = $data['u']->last_name;
$response["data"]["dob"] = $data['u']->dob;
$response["data"]["address"] = $data['u']->address;
$response["data"]["lat"] = $data['u']->lat;
$response["data"]["long"] = $data['u']->long;
$response["data"]["mobile"] = $data['u']->mobile;
$response["data"]["email"] = $data['u']->email;
$response["data"]["password"] = $data['u']->password;
$response["data"]["gender"] = $data['u']->gender;
$response["data"]["about"] = $data['u']->about;
$response["data"]["address_acceptance"] = $data['u']->address_acceptance;
$response["data"]["availability"] = $data['u']->availability;
$response["data"]["canceling_policy"] = $data['u']->canceling_policy;
$response["data"]["acceptance"] = $data['u']->acceptance;
$response["data"]["seen_status"] = $data['u']->seen_status; // 0=not, 1=yes
$response["data"]["approv_status"] = $data['u']->approve_status;
$response["data"]["complete_serviceLevel"]= $status_level;
$response["account"] = $data['a'];
$response["discount"] = $discount;
echo json_encode($response);
} else {
$response["error"] = 2;
$response["success"] = 0;
$response["message"] = "User is not approved";
echo json_encode($response);
}
} else {
$response["error"] = 1;
$response["success"] = 0;
$response["message"] = "Enter correct email and password";
echo json_encode($response);
}
} else {
$response["error"]=4;
$response["message"]= "Access denied";
echo json_encode($response);
}
}
model:
public function login($email, $password, $device_token, $device_type) {
$r = $this->db->get_where('registration', array('email'=>$email, 'password'=>$password));
$count = $r->num_rows();
if ($count > 1) {
$this->db->select('id,email,user_type');
$this->db->from('registration');
$this->db->where('email',$email);
$cc = $this->db->get()->result();
$response["error"] = 0;
$response["success"] = 1;
$response["message"] = "Success, Which account does you want to login?";
$response["data"] = $cc;
echo json_encode($response);
die();
} else if ($count == 1) {
$r1 = $r->row();
$id = $r1->id;
$this->db->where('id',$id);
$update =$this->db->update('registration',array('device_token' => $device_token,'device_type' => $device_type));
//$id = $r1->id;
$r2 = $this->db->get_where('accountdetails', array('user_id' => $id))->result();
$data= array(
"u" =>$r1,
"a" =>$r2
);
return $data;
} else {
return false;
}
}
I am trying to get results from a MySQL query and then return it as a array but then on top of that I want the other function to "decode" it in to a custom array
GetProfileData Code:
public function getProfileData($username){
$data = TBWebcam::MySQLQuery("SELECT * FROM `new_user` WHERE `user_name` = \"AndrewAubury\";");
if($data =! null){
$userimage = $data["user_image"];
if($userimage =! ""){
$userimage = str_replace("%s","",$userimage);
$userimage = "https://A LINK YOU DONT NEED TO KNOW.net/PF.Base/file/pic/user/".$userimage;
}else{
$userimage = null;
}
$usergender = $data["gender"];
if($usergender == "1"){
$usergender = "Male";
}else{
$usergender = "Female";
}
//echo($data["user_id"]."<br><br><br><br>");
$userData = array(
"id" => $data["user_id"],
"name" => $data["full_name"],
"username" => $data["user_name"],
"image" => $userimage,
"gender" => $usergender,
);
echo("Data: ".$data."<br><br><br>");
return($userData);
}else{
return null;
}
}
MySQLQuery code:
public function MySQLQuery($queryToDo){
$servername = "my server";
$username = "um my username :P";
$password = "why do u need to know";
$dbname = "the one i set it up on";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {return(null);}
$sql = $queryToDo;
$result = $conn->query($sql);
$mehArray = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$mehArray[] = $row;
}
return($mehArray);
} else {
return(null);
}
$conn->close();
}
I am getting the MySQL array the issue is in the getProfileData function
I think it will help you
public function getProfileData($username){
$results = TBWebcam::MySQLQuery("SELECT * FROM `new_user` WHERE `user_name` = \"AndrewAubury\";");
if($results == null){
return null;
}
$data = $results[0];//getting only the first result, if you have more rows the you have use for/foreach loop
$userimage = $data["user_image"];
if($userimage =! ""){
$userimage = str_replace("%s","",$userimage);
$userimage = "https://A LINK YOU DONT NEED TO KNOW.net/PF.Base/file/pic/user/".$userimage;
}else{
$userimage = null;
}
$usergender = $data["gender"];
if($usergender == "1"){
$usergender = "Male";
}else{
$usergender = "Female";
}
//echo($data["user_id"]."<br><br><br><br>");
$userData = array(
"id" => $data["user_id"],
"name" => $data["full_name"],
"username" => $data["user_name"],
"image" => $userimage,
"gender" => $usergender,
);
echo("Data: ".$data."<br><br><br>");
return($userData);
}
The code of $mehArray[] = $row; of the method MySQLQuery() sending two dimensional result set. So you have to fetch the results by looping in the method getProfileData(). I have put here 0 index value, because of you want to take 1 rows, I think.
I am new to Codeigniter i am stuck into a problem, i have searched every where but i did not find solution to it,
My problem is when i hit a particular controller method through a link it works perfectly for eg.
http://localhost/MyProject/indexController/user_login_process
but when i hit that method manually after it renders first time properly, it renders view but following error is there.
Please help me to sort out my issue:
Controller:
public function user_login_process() {
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
if(isset($this->session->userdata['logged_in'])){
$this->load->view('teaching');
}else{
$this->load->view('index');
}
} else {
$username=$this->input->post('username');
$data = array('username' => $this->input->post('username'),'password' => $this->input->post('password'));
$result = $this->login_database->login($data);
if ($result == TRUE) {
$result = $this->login_database->read_user_information($username);
if ($result != false) {
$session_data = array('id'=>$result[0]->id,'username' => $result[0]->email,'password' => $result[0]->password);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->session->set_userdata('user_info', $session_data);
$user_info=$this->session->userdata('user_info');
$u_id=$user_info['id'];
$data['query']=$this->teaching_model->get_all_courses($u_id);
$this->load->view('teaching', $data);
}
}
else
{
$data = array('error_message' => 'Invalid Username or Password');
$this->load->view('index', $data);
}
}
}
Model:
<?php
Class Teaching_model extends CI_Model {
function get_all_courses($u_id)
{
$condition = "u_id =" . "'" . $u_id . "'";
$this->load->database();
$this->db->select("*");
$this->db->from("course");
$this->db->where($condition);
$query=$this->db->get();
return $query->result();
}
}
teaching View:
foreach ($query as $row)
{ ?>
$row->name;
<? } ?>
Try this. All codes are changed. check carefully.
Change your controller name to Home.php and inside Home too. Bcz your URL contain index is something feal bad
In Controller
public function user_login_process() {
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE)
{
# I dont know purpose od this. For now i juts redirct to login
redirect('login');
/* if(isset($this->session->userdata['logged_in']))
{
$this->load->view('teaching');
}
else
{
$this->load->view('index');
}*/
}
else
{
$this->load->database();
$username = $this->input->post('username');
$password = $this->input->post('password');
$result = $this->login_database->login($username,$password);
if ($result == 0) {
echo "Invalid login";
}
elseif ($result == 1) {
echo "Multiple account matched. Contact admin";
}
else{
$session_data = array(
'id' =>$result[0]['id'],
'username' => $result[0]['email'],
'password' => $result[0]['password'],
'logged_in' => TRUE
);
# only set one sesstion
$this->session->set_userdata($session_data);
$id = $result[0]['id']; # logged User ID
$data['query']=$this->teaching_model->get_all_courses($id);
}
if ($result)
{
$result = $this->login_database->read_user_information($username);
if ($result != false)
{
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
$this->session->set_userdata('user_info', $session_data);
$user_info=$this->session->userdata('user_info');
$u_id=$user_info['id'];
$result2 = $this->teaching_model->get_all_courses($u_id);
if($result2 == 0){
echo "No Courses Found";
}
else{
$data['query'] = $result2;
$this->load->view('teaching', $data);
}
}
}
else
{
$data = array('error_message' => 'Invalid Username or Password');
$this->load->view('index', $data);
}
}
}
In Model*(login_database)*
public function login($username,$password)
{
$query = $this->db->query("SELECT * FROM table_name WHERE username = '$username' AND password= '$password' ");
$result = $query->result_array();
$count = count($result);
if (empty($count)) {
return 0;
}
elseif ($count) >1) {
return 1;
}
else{
return $result;
}
}
In Model*(Teaching_model)*
Class Teaching_model extends CI_Model {
function get_all_courses($id)
{
$query = $this->db->query("SELECT * FROM course WHERE u_id = $id");
$result = $query->result_array();
$count = count($result);
if (empty($count)) {
return 0;
}
else{
return $result;
}
}
}
if it is an issue with session, try using database for managing sessions:
config.php
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_sessions';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
For MySQL:
Create a table named 'ci_sessions' in your database, all the sessions will be managed using this table, and it will help you when you are hosting the website / application , may avoid some possible errors with the session variables and the permissions :
CREATE TABLE IF NOT EXISTS `ci_sessions` (
`id` varchar(40) NOT NULL,
`ip_address` varchar(45) NOT NULL,
`timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
`data` blob NOT NULL,
KEY `ci_sessions_timestamp` (`timestamp`)
);
**For Validating the users against their password **
public function validate_admin($username,$password)
{
// grab user input
if(isset($_POST['username']) AND $_POST['username'] !='')
{
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
}
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->having("rec_status != 'C' ");
// Run the query
$query = $this->db->get('employee');
// Let's check if there are any results
if($query->num_rows() == 1)
{
// If there is a user, then create session data
$row = $query->row();
$data = array(
'id_admin' => $row->id,
'first_name' => $row->first_name,
'last_name' => $row->last_name,
'email_admin' => $row->email,
'phone_admin' => $row->phone,
'acc_status_admin' => $row->rec_status,
'acc_type_admin' => $row->emp_role,
'validated_admin' => true
);
$this->session->set_userdata($data);
return true;
}
// If the previous process did not validate
// then return false.
return false;
}
I have the following PHP function that attempts to register a user in a database with a temporary password when they post an email adress via a form:
public function registerNewUser() {
$temp_pass = '';
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$random_string_length=8;
for ($i = 0; $i < $random_string_length; $i++) {
$temp_pass .= $characters[rand(0, strlen($characters) - 1)];
}
if (empty($_POST['user_email'])) {
$this->errors[] = FEEDBACK_EMAIL_FIELD_EMPTY;
} elseif (strlen($_POST['user_email']) > 64) {
$this->errors[] = FEEDBACK_EMAIL_TOO_LONG;
} elseif (!filter_var($_POST['user_email'], FILTER_VALIDATE_EMAIL)) {
$this->errors[] = FEEDBACK_EMAIL_DOES_NOT_FIT_PATTERN;
} elseif (!empty($_POST['user_email'])
&& strlen($_POST['user_email']) <= 64
&& filter_var($_POST['user_email'], FILTER_VALIDATE_EMAIL)) {
$this->user_email = htmlentities($_POST['user_email'], ENT_QUOTES);
$this->user_password = $temp_pass;
$this->hash_cost_factor = (defined('HASH_COST_FACTOR') ? HASH_COST_FACTOR : null);
$this->user_password_hash = password_hash($this->user_password, PASSWORD_DEFAULT, array('cost' => $this->hash_cost_factor));
$sth = $this->db->prepare("SELECT * FROM users WHERE user_email = :user_email ;");
$sth->execute(array(':user_email' => $this->user_email));
$count = $sth->rowCount();
if ($count == 1) {
$this->errors[] = FEEDBACK_USEREMAIL_ALREADY_TAKEN;
} else {
$this->user_activation_hash = sha1(uniqid(mt_rand(), true));
$sth = $this->db->prepare("INSERT INTO users (user_email, user_password_hash, user_activation_hash) VALUES(:user_email, :user_password_hash, :user_activation_hash) ;");
$sth->execute(array(':user_email' => $this->user_email, ':user_password_hash' => $this->user_password_hash, ':user_activation_hash' => $this->user_activation_hash));
$count = $sth->rowCount();
if ($count == 1) {
$this->user_id = $this->db->lastInsertId();
// send a verification email
if ($this->sendVerificationEmail()) {
// when mail has been send successfully
$this->messages[] = FEEDBACK_ACCOUNT_SUCCESSFULLY_CREATED;
$this->registration_successful = true;
return true;
} else {
$sth = $this->db->prepare("DELETE FROM users WHERE user_id = :last_inserted_id ;");
$sth->execute(array(':last_inserted_id' => $this->db->lastInsertId() ));
$this->errors[] = FEEDBACK_VERIFICATION_MAIL_SENDING_FAILED;
}
} else {
$this->errors[] = FEEDBACK_ACCOUNT_CREATION_FAILED;
}
}
} else {
$this->errors[] = FEEDBACK_UNKNOWN_ERROR;
}
// standard return. returns only true of really successful (see above)
return false;
}
I keep tripping the FEEDBACK_ACCOUNT_CREATION_FAILED error, but can't figure out why. Any ideas?
Have you dumped "$sth" after it does the insert?
What does that give you?
If you are using mysql you can turn the general_log (http://dev.mysql.com/doc/refman/5.1/en/query-log.html) to see the mysql query that gets executed.
This way you can see if the query is getting created properly.
Turning on mysql logging can be very useful if you are not sure whats happening at the other end.