how to check if username already exists in codeigniter my error - codeigniter

My controler cod is:
function register()
{
if(isset($_POST['register'])){
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('password','Password','required');
//
if($this->form_validation->run () == true){
echo 'Form Validate';
$data = array(
'username'=>$_POST['username'],
'email'=>$_POST['email'],
'password'=>strtoupper(hash('whirlpool',$_POST['password']))
);
$this->db->insert('accounts',$data);
$this->load->model("usuarios_model");
if($this->usuarios_model->check_user_exist($data['username'])){
echo "already user exist";
}{
$this->db->insert('accounts',$data);
redirect("painel/index");
}
}
}
$this->load->view("painel/register");
}
[![enter image description here][2]][2]
It registers an user even though the username already exists.
Where is the mistake?

You can use is_unique rule in your form_validation library.
$this->form_validation->set_rules('username','Username','required|is_unique[table.column]');

You have mistake in your model in where condition it will be small later of username but you used Username.
use this code in your model.
function check_user_exist($username){
$this->db->wehre('username',$username);
$this-db->from('accounts');
$query= $this->db->get();
if($query->num_rows() > 0){
return true;
}else{
return false;
}
}
and also controller data insert after user check:
if($this->usuarios_model->check_user_exist($data['username'])){
echo "already user exist";
}{
$this->db->insert('accounts',$data);
redirect("painel/index");
}

You can easily achieve this using call_back function in validation. From Codeigniter Docs
Controller
function register() {
if ($this->input->post('register')) {
$this->form_validation->set_rules('username','Username','required|callback_checkUserName');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('password','Password','required');
//
if ($this->form_validation->run() == true) {
$data = array(
'username '=> $this->input->post('username'),
'email' => $this->input->post('email'),
'password' => strtoupper(hash('whirlpool', $this->input->post('password')))
);
$this->db->insert('accounts',$data);
echo 'success';
exit();
} else {
echo validation_errors(); die; // check errors
}
}
$this->load->view("painel/register");
}
// call back validate function
function checkUserName($userName){
if ($this->usuarios_model->checkUserexist($userName) == false) {
return true;
} else {
$this->form_validation->set_message('checkUserName', 'This userName already exist!');
return false;
}
}
MODEL
function checkUserexist($userName) {
$this->db->where('username', $userName);
$this-db->from('accounts');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return true;
}
return false;
}

This my code which I used in one of my projects replace the words with your code:
$this->form_validation->set_rules('companyname','Company Name','trim|required|callback_companyname_exist');
Here is above callback function:
function companyname_exist($str) {
$this->db->where('company_name', $str);
$this->db->where('user_type','Shop');
$prod = $this->db->get('grs_user');
if ($prod->row()) {
$this->form_validation->set_message('companyname_exist', 'This Company name is already Available.');
return FALSE;
} else
return TRUE;
}
You can used this for already register email check also.

Related

Multiuser login codeigniter(how to use password_verify method?)

Please help guys, I have encrypted successfully my password with password_hash but is there any solution how to check login and password using PHP password_verify for multiuser login?
here's my controller:
public function index()
{
$this->form_validation->set_rules('email','Email address','required');
$this->form_validation->set_rules('password','Password','required');
if($this->form_validation->run() == FALSE)
{
$this->load->view('view_login');
} else {
$this->load->model('Model_members');
$valid_user = $this->Model_members->check_credential();
if($valid_user == FALSE)
{
$this->session->set_flashdata('error','');
redirect("login");
} else {
$this->session->set_userdata('email', $valid_user->email);
if($this->session->userdata('groups') == '1')
{
redirect('home');
}
elseif($this->session->userdata('groups') == '2')
{
redirect('homepage');
}
elseif($this->session->userdata('groups') == '0')
{
redirect('test1');
}
}
}
}
This is my model:
public function check_credential()
{
$email = set_value('email');
$password = set_value('password');
$hasil3 = $this->db->where('email', $email)
->where('password', $password)
->limit(1)
->get('users');
if($hasil3->num_rows() > 0)
{
return $hasil3->row();
} else {
return array();
}
}
Very appreciate for the help !!
Please find below mentioned solution, It will help you.
In Controller
$userData['email'] = $this->input->post('email');
$userData['password'] = $this->input->post('password');
$valid_user = $this->Model_members->check_credential($userData);
In Model your function will look like below.
public function check_credential($param) {
$hasil3 = $this->db->where('email', $param['email'])
->where('password', password_hash($param['password'], PASSWORD_DEFAULT, ['cost' => 10]))
->limit(1)
->get('users');
if ($hasil3->num_rows() > 0) {
return $hasil3->row();
} else {
return array();
}
}
Let me know if it not work.
Controller
//create array to pass data to model
$data = [
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
];
//check model to see if user exists and if correct password
$user = $this->name_of_model->check_credential($data);
if(isset($user['error])){
//return error message in some form
}
Model:
You want to break you process in two, in order to make error reporting better. First check if user exists, then check if password is correct
public function check_credential($data) {
//see if user exists first
$user = $this->db->where('email', $data['email'])
->get('users')->row_array();
if($user){
$success = (password_verify($data['password'],$user['password']));
return ($success) ? $user : ['error'=>'Incorrect Password']
}
else{
return ['error'=>'User doesn't exist'];
}
}

resetting password in codeigniter

i'm new to codeigniter, and i am attempting to create a password reset system
this is my controller:
public function changePassword(){
if($this->session->userdata('loginuser'))
{
$session_data = $this->session->userdata('loginuser');
$email = $this->session->userdata('email');
$data['email'] = $email;
$data['title'] = 'Change my Password | Watch Stop';
$this->load->view('template/header', $data);
$this->load->view('watch_stop/vpassword', $data);
$this->load->view('template/footer');
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
public function reset_password(){
if($this->session->userdata('loginuser'))
{
$session_data = $this->session->userdata('loginuser');
$email = $this->session->userdata('email');
$data['email'] = $email;
//validating form
$this->form_validation->set_rules('old_password','Old Password','trim|required|min_length[5]|md5');
$this->form_validation->set_rules('new_password','New Password','trim|required|min_length[5]|matches[cnew_password]|md5');
$this->form_validation->set_rules('cnew_password','Confirm Password','trim|required||md5');
if ($this->form_validation->run() == FALSE)
{
$this->changePassword();
//$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Failed to update password</div>');
}else {
$query=$this->customer_model->change_password();
$data = array( "main_content" => 'includes/memberadmin/memberadmin_cpass_process',
"query" => $query
);
$this->load->view('includes/memberadmin/template',$data);
}
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
this is my model:
function change_password(){
$this->db->select('id');
$this->db->where('email',$this->session->userdata('email'));
$this->db->where('password',$this->input->post('old_password'));
$query=$this->db->get('user');
if ($query->num_rows() > 0)
{
$row = $query->row();
if($row->email===$this->session->userdata('email'))
{
$data = array(
'new_password' => $this->input->post('new_password')
);
$this->db->where('email',$this->session->userdata('email'));
$this->db->where('new_password',$this->input->post('old_password'));
if($this->db->update('user', $data))
{
return "Password Changed Successfully";
}else{
return "Something Went Wrong, Password Not Changed";
}
}else{
return "Something Went Wrong, Password Not Changed";
}
}else{
return "Wrong Old Password";
}
}
When i click on the update button in my reset password page, i am getting the following error for my new password confirmation field: Unable to access an error message corresponding to your field name Confirm Password.()
please help!
1) there are two pipe signs near required||md5
$this->form_validation->set_rules('cnew_password','Confirm Password','trim|required||md5');
change it to
$this->form_validation->set_rules('cnew_password','Confirm Password','trim|required|md5');
2) changing input to md5 at this stage is not good.
You have to use password_hash function.
Read More >> http://php.net/manual/en/function.password-hash.php
3) You forgot to load model. $this->load->model('customer_model');

CodeIgniter login system using md5()

I am new in CodeIgniter and using CodeIgniter_2.1.3. I am following NETTUTS CodeIgniter tutorial. I want to develop a login system with codeIgniter which works well without md5() function [without encrypted password] . Then I create new table with encrypted password using md5() function. Then login code doesn't work. My code is ::
view/login_form.php
<?php
// form design
echo form_open("login/validate") . "<br/>";
echo form_input("username", "Username") . "<br/> <br/>";
echo form_password("password", "password") . "<br/> <br/>";
echo form_submit("submit", "Login") . "<Br/> <Br/>";
echo anchor("login/sign_up", "Create Account");
?>
controllers/login.php
<?php
class Login extends CI_Controller {
function index() { // function of loading login page
$data['main_content'] = "login_form"; // name of login page
$this->load->view("includes/templet", $data);
}
function validate() { // form validation
$this->load->model("membership_model"); // load "membership_model"
$query = $this->membership_model->validate_user(); // check validation
if( $query ) { // if data found
$data = array( // value which is to be inserted into session
"username" => $this->input->post("username"),
"is_logged_in" => true
);
$this->session->set_userdata($data); // insert value into session
redirect("site/members_area"); // go to predefined page
}
else {
// if data not found then go to login_form page
$this->index();
}
}
// create account
function sign_up() {
$data['main_content'] = "sign_up";
$this->load->view("includes/templet", $data);
}
// insert data into database
function create_member() {
$this->load->library("form_validation"); // load form_validation library
$this->form_validation->set_rules("username", "Username", "trim|required");
$this->form_validation->set_rules("password", "Enter Password", "trim|required|min_length[4]|max_length[32]");
$this->form_validation->set_rules("re_password", "Confirm password", "trim|required|matches[password]");
$this->form_validation->set_rules("email", "Email Address", "trim|required|valid_email");
if( $this->form_validation->run() == FALSE ) {
$this->load->view("sign_up");
}
else {
$this->load->model("membership_model");
if( $query = $this->membership_model->create_member() ) {
// redirect("site/members_area");
$data['main_content'] = "signup_success";
$this->load->view("includes/templet", $data);
}
else {
$this->load->view("sign_up");
}
}
}
}
?>
model/membership_model
<?php
class Membership_model extends CI_Model {
function validate_user() {
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get("user");
if( $query->num_rows == 1 ) {
return true;
}
}
function create_member() {
$new_member_insert_data = array(
'username' => $this->input->post("username"),
'password' => md5($this->input->post("password")),
'email' => $this->input->post("email")
);
$insert = $this->db->insert("user", $new_member_insert_data);
return true;
}
}
?>
I think the column "Password" in your table is less than varchar(32), md5 requires 32 varchar type.
For md5 password
check the data base field, because md5 generate 32 charactors.. so change the table field to varchar(32)
$data=array(
'password' => md5($this->input->post('password')),
);
Just change this statement from
if( $query->num_rows == 1 )
to
if( $query->num_rows() == 1 )
that row() in your
model/membership_model.php
It works

Codeigniter database check

i am currently working on a project where users can save note snippets in there own little user area.
I was wondering how would i check if the id of an item exists for example if a user visits
http://mysite.com/view/1 and there is a note snippet of 1 it will display all the data relating to the id of one. Now if the user was to change the url to lets say 1000, that id doesnt exist and the view just errors.
i want to be able to redirect them back to a certain page with a error message "snippet does not exist" etc.
heres what i have so far ( i currently already have a conditional statement in here to check if the snippet is private, then if it is redirect back to /publicsnippets)
Controller:
class Publicsnippets extends CI_Controller {
function __construct()
{
parent::__construct();
if (!$this->tank_auth->is_logged_in()) {
redirect('/login/');
}
$this->load->model('dashboard_model');
$this->data['user_id'] = $this->tank_auth->get_user_id();
$this->data['username']= $this->tank_auth->get_username();
}
public function index()
{
$this->data['public_snippets'] = $this->dashboard_model->public_snippets();
$this->load->view('dashboard/public_snippets', $this->data);
}
public function view($snippet_id)
{
$snippet = $this->dashboard_model->get_snippet($snippet_id);
if ($snippet['state'] === 'private')
{
$this->session->set_flashdata('message', "<b style=\"color:red;\">You are not allowed to view this snippet!</b>");
redirect('/publicsnippets');
} else {
$this->data['snippet'] = $snippet;
}
$this->load->view('dashboard/view_public_snippet', $this->data);
}
}
Model:
class Dashboard_model extends CI_Model {
public function public_snippets()
{
$this->db->select('id, title, description, tags, author, date_submitted');
$query = $this->db->get_where('snippets', array('state' => 'public'));
return $query->result_array();
}
public function private_snippets()
{
$this->db->select('id, title, description, tags, author, date_submitted');
$query = $this->db->get_where('snippets', array('user_id' => $this->tank_auth->get_user_id()));
return $query->result_array();
}
public function add_snippet($data)
{
$this->db->insert('snippets', $data);
$id = $this->db->insert_id();
return (isset($id)) ? $id : FALSE;
}
public function get_snippet($snippet_id) {
$query = $this->db->get_where('snippets', array('id' => $snippet_id));
return $query->row_array();
}
public function update_snippet($snippet_id, $data)
{
$this->db->where('id', $snippet_id);
$this->db->update('snippets', $data);
}
public function delete_snippet($snippet_id)
{
$this->db->where('id', $snippet_id);
$this->db->delete('snippets');
}
}
View:
<h3>Description</h3>
<p><?php echo $snippet['description']; ?></p>
<h3>Tags</h3>
<p><?php echo $snippet['tags']; ?></p>
<h3>Date Submitted</h3>
<p><?php echo $snippet['date_submitted']; ?></p>
<h3>Snippet</h3></pre>
<pre class="prettyprint"><?php echo $snippet['code_snippet']; ?></pre>
You work is fine just add a check like this in your view method
Controller
public function view($snippet_id)
{
$snippet = $this->dashboard_model->get_snippet($snippet_id);
if($snippet){
if ($snippet['state'] === 'private')
{
$this->session->set_flashdata('message', "<b style=\"color:red;\">You are not allowed to view this snippet!</b>");
redirect('/publicsnippets');
} else {
$this->data['snippet'] = $snippet;
}
$this->load->view('dashboard/view_public_snippet', $this->data);
}else{
$this->session->set_flashdata('message', "<b style=\"color:red;\">snippet does not exist</b>");
redirect('/publicsnippets');
}
}
if no row is found in get_snippet method the $snippet will contain false or null
and the second block of condition will run.
In your model change get_snippet() to check for rows:
public function get_snippet($snippet_id) {
$query = $this->db->get_where('snippets', array('id' => $snippet_id));
if ($query->num_rows() > 0) {
return $query->row_array();
} else {
return false;
}
}
Then in your controller:
if ($snippet = $this->dashboard_model->get_snippet($snippet_id)) {
// code if snippet exists
} else {
// code if snippet doesn't exist
}
OR
$snippet = $this->dashboard_model->get_snippet($snippet_id);
if ($snippet) {
// etc...

validate email value in joomla 1.7?

I am developing component and I want to know how to validate email value entered by user using joomla 1.7?
JHTML::_('behavior.formvalidation') without using this method.
Try this,
function validate()
{
jimport('joomla.mail.helper');
$valid = true;
if ($this->_data->email && !JMailHelper::isEmailAddress($this->_data->email))
{
$this->_app->enqueueMessage(JText::_('Invalid Email Address'),'error');
$valid = false;
}
return $valid;
}
function validate($email)
{
jimport('joomla.mail.helper');
$error = false;
if (! $email || ! JMailHelper::isEmailAddress($email))
{
$error = JText::sprintf('Email Corect', $email);
JError::raiseWarning(0, $error);
}
return $error;
}

Resources