I am getting Undefined Variable email under Controllers.
Controller : login.php
public function index() {
$this->load->view('bootstrap/header');
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->load->model('Login_db');
$is_exist = $this->Login_db->isEmailExist($email);
if ($is_exist) {
$this->form_validation->set_message('isEmailExist', 'Email Address Already Exists!');
return FALSE;
} else {
return TRUE;
}
$this->load->view('bootstrap/footer');
}
Model : login_db.php
public function isEmailExist($email) {
$this->db->select('user_id');
$this->db->where('email', $email);
$query = $this->db->get('login');
if ($query->num_rows() > 0) {
return TRUE;
} else {
return FALSE;
}
}
I have to check whether email exists are not.
before
$is_exist = $this->Login_db->isEmailExist($email);
add this (in case of a POST request)
$email = $this->input->post('email');
or this ((in case of a GET request)
$email = $this->input->get('email');
by checking your code i came to assume that you want to allow only the emails which is already not in table ? why have not you validated with is_unique like
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[login.email]');
or you can change the line as
$this->Login_db->isEmailExist($this->input->post('email'));
or you should define $email before passing it / calling the function
$email=$this->input->post('email');
for custom massaging :
$this->form_validation->set_rules( 'email', 'Email', 'required|valid_email|is_unique[login.email]', array( 'is_unique' => 'Email already exists' ) );
better you go through the manual
https://www.codeigniter.com/user_guide/libraries/form_validation.html
the var $email used here
$is_exist = $this->Login_db->isEmailExist($email); line 5 of index
is never isntanciate. You should instantiate it to avoir error.
Related
I have recently starting following some coding tutorials for PHP CodeIgniter and I have run into a bit of a snag for my login and registration system. The registration works perfectly, accessing the database and creating accounts but there is a problem with my login code that I can not work my head around.
I receive the following error:
A PHP Error was encountered Severity: Notice
Message: Trying to get property 'email' of non-object
Filename: controllers/Auth.php
Line Number: 23
Backtrace:
File: /opt/lampp/htdocs/application/controllers/Auth.php Line: 23
Function: _error_handler
File: /opt/lampp/htdocs/index.php Line: 315 Function: require_once
The code for the following is:
<?php
class Auth extends CI_Controller{
public function login()
{
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
if($this->form_validation->run() == TRUE) {
$username = $_POST['username'];
$password = md5($_POST['password']);
//check user in db
$this->db->select('*');
$this->db->from('users');
$this->db->where(array('username'=>$username, 'password'=>$password));
$query = $this->db->get();
$user = $query->row();
if ($user->email){
$this->session->set_flashdata("success", "You are logged in.");
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $user->username;
//redirect to profile page
redirect("user/profile", "refresh");
} else {
$this->session->set_flashdata("error", "NO such account exists");
//redirect("auth/login", "refresh");
}
}
$this->load->view('login');
}
public 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|min_length[5]');
$this->form_validation->set_rules('password', 'Confirm Password', 'required|min_length[5]|matches[password]');
if($this->form_validation->run() == TRUE) {
//echo 'form validated';
//add user in database
$data = array(
'username'=>$_POST['username'],
'email'=>$_POST['email'],
'password'=> md5($_POST['password'])
);
$this->db->insert('users', $data);
$this->session->set_flashdata("success", "Your account has been registered");
redirect("auth/register", "refresh");
}
}
$this->load->view('register');
}
}
?>
Any help would be appreciated and if anymore code that I have used for this tutorial is needed for a solution, just let me know.
Thank you.
You will get that kindof error when the result object from the database is returning no rows hence an empty stdClass and thus you will not be able to access any properties. The correct way of doing this is to check that num_rows() is equal to 1 (e.g. there should only be one user with that name and password).
public function login() {
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
if ($this->form_validation->run() == TRUE) {
$username = $_POST['username'];
/**
* Do not md5 your passwords!
* Use password_hash and password_verify!!
*/
$password = md5($_POST['password']); // DO NOT MD5 your passwords!
//check user in db
// this should be in a model!
$this->db->select('*');
$this->db->from('users');
$this->db->where(array('username' => $username, 'password' => $password));
$query = $this->db->get();
if ($query->num_rows() == 1) {
$user = $query->row();
$this->session->set_flashdata("success", "You are logged in.");
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $user->username;
//redirect to profile page
redirect("user/profile", "refresh");
} else {
$this->session->set_flashdata("error", "NO such account exists");
//redirect("auth/login", "refresh");
}
}
$this->load->view('login');
}
Generally you should get into the habit of checking if num_rows() > 0 before ever using result() row() .etc. because you can never be 100% sure that the data will be returned.
For example:
//model
function get_users() {
$query = $this->db->get('users');
if ($query->num_rows() == 0) {
return null;
}
return $query->result();
}
// controller
function something() {
$users = $this->model->get_users();
if (is_null($users)) {
exit('no users');
}
print_r($users);
}
# table name is users#
## model name is user_model##
### controller name is get_password ###
issue - no change on the password , remain as old
> model(user_model)
public function updatePassword($email,$data)
{
$data1=array('password'=>$data);
$this->db->where('email','$email');
$this->db->update('users','password');
$success = $this->db->affected_rows();
if(!$success){
error_log('Unable to updatePassword');
return false;
}
return true;
}
> controller(get_password)
public function index($rs=FALSE)
{
$this->load->database();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->model('user_model');
$this->load->library('session');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'password', 'required');
$this->form_validation->set_rules('passconf', 'password Confirmation', 'required|matches[password]');
if ($this->form_validation->run() == FALSE)
{
echo form_open();
$this->load->view('users/fpre');
}
else
{
$data = array(
'password' => md5($this->input->post('password')),
);
$email =array(
'email' =>$this->input->post('email')
);
$this->user_model->updatePassword($data,$email);
echo "Congratulations!";
}
}
it shows no error but the password is not updated remain same at users table..i can't find the problem is, please help me to find it out ..
Controller (get_password):
public function index() {
$this->load->database();
$this->load->helper(array('form', 'url'));
$this->load->library(array('form_validation', 'session'));
$this->load->model('user_model');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'Current password', 'required');
$this->form_validation->set_rules('newpassword', 'password', 'required');
$this->form_validation->set_rules('newpassconf', 'password Confirmation', 'required|matches[newpassword]');
$email = $this->input->post('email');
$success = false;
$msg = '';
if ($this->form_validation->run() !== FALSE) {
$password = md5($this->input->post('password'));
if ($this->user_model->checkPassword($email, $password)){
$newpassword = md5($this->input->post('newpassword'));
if ($this->user_model->updatePassword($email, $newpassword)){
$success = true;
}else{
$msg = 'Unable to updatePassword';
}
}else{
$msg = 'Incorrect password';
}
}
if ($success){
echo 'Congratulations!';
}else{
$this->load->view('users/fpre', array(
'email'=>$email,
'msg'=>$msg
));
}
}
Model (user_model):
public function checkPassword($email, $password) {
$users = $this->db->get_where('users', array('email'=>$email))->row();
return $users->password === $password;
}
public function updatePassword($email, $newpassword) {
$data = array('password' => $newpassword);
$this->db->where('email', $email)
->update('users', $data);
$success = $this->db->affected_rows();
if (!$success) {
error_log('Unable to updatePassword');
}
return $success;
}
View (users/fpre):
if ($msg){
echo 'Message: '.$msg;
}
echo form_open();
echo form_input('email', $email);
echo form_password('password');
echo form_password('newpassword');
echo form_password('newpassconf');
echo form_submit('', 'Enviar');
echo form_close();
Changes to compare:
Your model function shows the parameters are expected to be email and then password, but your controller is passing them through be other way around.
$this->user_model->updatePassword($data,$email);
Should be:
$this->user_model->updatePassword($email,$data);
I also believe the data needs to be passed differently. The where() function expects either where(field_name, value) or where(array(field_name => value)). Looking at your code, you seem to be mixing both of those.
Using set() should help with this too, so instead of
$data1=array('password'=>$data);
$this->db->where('email','$email');
$this->db->update('users','password');
Use:
$this->db->set($data);
$this->db->where($email);
$this->db->update('users');
Note: code untested.
I believe this line $this->db->update('users','password'); should be $this->db->update('users', $data);.
Right now you are not passing the password to the update function. You are passing the string "password".
Here Is My COde I m checking username is already exist or not in datbase
when i validate and submit the form duplicate entry entered in database i want that if already exist it show validation error
My Controller
public function index()
{
if($this->input->post('submit')) {
$this->form_validation->set_rules('name', 'User Name', 'callback_checkuser');
$this->form_validation->set_rules('role', 'Role', 'trim|required');
$this->form_validation->set_rules('pass', 'Password', 'trim|required');
if($this->form_validation->run()==TRUE)
{
$user['u_name'] = $this->input->post('name');
$user['role'] = $this->input->post('role');
$user['password']= md5($this->input->post('pass'));
$u_id = $this->custom_model->add_user($user);
if($u_id){
$data['msg'] = 'Successfully Created!!!!';
}
}
}
$this->load->template('add_user', $data);
}
function checkuser($name) {
if($this->custom_model->check_name($name) == false) {
false;
}else {
$this->form_validation->set_message('checkuser', 'This user already exist');
return true;
}
}
Here is My Model
public function check_name($name) {
$sql = "SELECT * FROM users WHERE u_name='".$name."' ";
$query = $this->db->query($sql);
$res = $query->row_array();
if (is_array($res) && count($res) > 0){
return $res;
}
return false;
}
There is a return statement missing in the function checkuser, but more importantly, you should invert the value you return. According to the example in the docs, when you set a validation message because of a validation error, you should return false, and return true when the validation passes.
So add a return, and change the boolean values. BTW, you don't really need an else clause and the word "exist" needs an additional "s":
function checkuser($name) {
if ($this->custom_model->check_name($name) == false) {
return true; // the user does not yet exist, so all is OK
}
$this->form_validation->set_message('checkuser', 'This user already exists');
return false; // this is a duplicate user name: not OK
}
Use this:
$this->form_validation->set_rules('name', 'User Name', 'trim|required|is_unique[users.u_name]');// trim and required added too
Docs.
I've this registration function and the related callback to check if an username already exists in the database. It works all perfectly, but I have problems with flashdata message
Here's the code:
/*
* Checks registration
*/
public function verify(){
$this->form_validation->set_rules('nome', 'Nome', 'trim|required|min_length[2]|xss_clean');
$this->form_validation->set_rules('cognome', 'Cognome', 'trim|required|min_length[2]|xss_clean');
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]|xss_clean|callback_check_username');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('password_conf', 'Password Confirmation', 'trim|required|matches[password]');
if($this->form_validation->run() == FALSE)
{
$this->session->set_flashdata('error_reg', 'Something goes wrong, please check your registration form');
redirect('registration');
}
else
{
$this->registration_m->add_user();
$this->session->set_flashdata('success_reg', 'Registration Successful!');
redirect('registration');
}
}
public function check_username($username){
$result = $this->registration_m->check_username_m($username);
if ($result) {
$this->session->set_flashdata('username', 'Username già in uso, riprovare.');
return false;
} else {
return true;
}
}
As you can see there's a redirect on the function verify(), and the flashdata before is correctly shown in case of errors.
My Question is: is there a way to show (in case of error) the flashdata inside the callback function without changing the logic of this piece of code?
Hope I was clear at all, cheers.
Modify your code as below
public function check_username($username){
$result = $this->registration_m->check_username_m($username);
if ($result) {
$this->form_validation->set_message('check_username', 'The %s field can not be the empty');
return false;
} else {
return true;
}
}
See differences in code
$this->session->set_flashdata('username', 'Username già in uso, riprovare.');
$this->form_validation->set_message('check_username', 'The %s field can not be the empty');
I have a form on my website header where i allow the user to log in with his username/password... then i POST to /signin page and check if the username exists to allow the user to log in.. if there is a problem upon login i output these errors...
i tried using the following code to show a custom error but with no luck
if ($this->form_validation->run() == false){
$this->load->view("login/index", $data);
}else{
$return = $this->_submitLogin();
if ($return == true){
//success
}else{
$this->form_validation->set_message('new_error', 'error goes here');
//error
}
$this->load->view("login/index", $data);
}
how does set_message work and if this is the wrong method, which one allow me to show a custom error in this case?
EDIT :
validation rules:
private $validation_rules = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|required|callback__check_valid_username|min_length[6]|max_length[20]|xss_clean'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|min_length[6]|max_length[32]'
),
);
The set_message method allows you to set your own error messages on the fly. But one thing you should notice is that the key name has to match the function name that it corresponds to.
If you need to modify your custom rule, which is _check_valid_username, you can do so by perform set_message within this function:
function _check_valid_username($str)
{
// Your validation code
// ...
// Put this in condition where you want to return FALSE
$this->form_validation->set_message('_check_valid_username', 'Error Message');
//
}
If you want to change the default error message for a specific rule, you can do so by invoking set_message with the first parameter as the rule name and the second parameter as your custom error. E.g., if you want to change the required error :
$this->form_validation->set_message('required', 'Oops this %s is required');
If by any chance you need to change the language instead of the error statement itself, create your own form_validation_lang.php and put it into the proper language folder inside your system language directory.
As you can see here, you can display the custom error in your view in the following way:
<?php echo form_error('new_error'); ?>
PS: If this isn't your problem, post your corresponding view code and any other error message that you're getting.
The problem is that your form is already validated in your IF part! You can fix the problem by this way:
if ($this->form_validation->run() == false){
$this->load->view("login/index", $data);
}else{
$return = $this->_submitLogin();
if ($return == true){
//success
}else{
$data['error'] = 'Your error message here';
//error
}
$this->load->view("login/index", $data);
}
In the view:
echo $error;
The CI way to check user credentials is to use callbacks:
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
...
public function username_check($str) {
// your code here
}
I recommend you to read CI documentation: http://codeigniter.com/user_guide/libraries/form_validation.html
The way I did this was to add another validation rule and run the validation again. That way, I could keep the validation error display in the view consistent.
The following code is an edited excerpt from my working code.
public function login() {
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$data['content'] = 'login';
if($this->form_validation->run()) {
$sql = "select * from users where email = ? and password = ?";
$query = $this->db->query($sql, array($this->input->post('email'), $this->input->post('password')));
if($query->num_rows()==0) {
// user not found
$this->form_validation->set_rules('account', 'Account', 'callback__noaccount');
$this->form_validation->run();
$this->load->view('template', $data);
} else {
$this->session->set_userdata('userid', $query->id);
redirect('/home');
}
} else {
$this->load->view('template', $data);
}
}
public function _noaccount() {
$this->form_validation->set_message('_noaccount', 'Account must exist');
return FALSE;
}
Require Codeigniter 3.0
Using callback_ method;
class My_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->form_validation->set_message('date_control', '%s Date Special Error');
}
public function date_control($val, $field) { // for special validate
if (preg_match("/^[0-9]{2}.[0-9]{2}.[0-9]{4}$/", $val)) {
return true;
} else {
return false;
}
}
public function my_controller_test() {
if ($this->input->post()) {
$this->form_validation->set_rules('date_field', 'Date Field', 'trim|callback_date_control[date_field]|xss_clean');
if ($this->form_validation->run() == FALSE) {
$data['errors']=validation_errors();
$this->load->view('my_view',$data);
}
}
}
}
Result:
if date = '14.07.2017' no error
if date = '14-7-2017' Date Field Date Special Error