I want to validate form register and I created class UserValidator and I try to check if the username field exists. In my opinion everything is correct, but show me 2 errors
Warning: array_key_exists() expects parameter 2 to be array, null given in C:\xampp\htdocs\class\index.php on line 22
Notice: username is not present in data in C:\xampp\htdocs\class\index.php on line 24.
<?php
if(isset($_POST['submit']))
{
$validation = new UserValidator($_POST);
$errors =$validation->validateForm();
}
<?php
class UserValidator
{
private $data;
private $errors =[];
private static $fields =['username', 'email'];
public function _construct($post_data)
{
$this->data = $post_data;
}
public function validateForm()
{
foreach(self::$fields as $field)
{
if(!array_key_exists($field, $this->data))
{
trigger_error("$field is not present in data");
return;
}
}
$this->validateUsername();
return $this->errors;
}
private function validateUsername()
{
$val = trim($this->data['username']);
if(empty($val))
$this->addError('username', 'username cannot be empty');
else
{
if(!preg_match('/^[a-zA-Z-0-9]{6,12}$/', $val))
{
$this->addError('username', 'username must me 6-12 characters');
}
}
}
private function addError($key, $val)
{
$this->errors[$key] = $val;
}
}
?>
<div id="register">
<h1>REJESTRACJA</h1>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<div class="row">
<div class="col-25">
<label for="loginRe">Login</label>
</div>
<div class="col-75">
<input type="text" name="username" placeholder="Login...">
<div class="error">
<?php echo $errors['username'] ?? '' ?>
</div>
</div>
</div>
<div class="row">
<div class="col-25">
<label for="email">Email</label>
</div>
<div class="col-75">
<input type="text" name="email" placeholder="Email...">
</div>
</div>
<div class="button">
<input type="submit" name="submit" value="Utwórz konto">
</div>
<div class="displayCenter">
<div class="display">
</div>
</div>
</form>
</div>
$this->data is NULL, it is not filled by constructor, the constructor declaration has a typo, missing one _
public function __construct($post_data)
{
$this->data = $post_data;
}
Constructor declaration has a typo, please rectify
Related
I make a form validation and I want to that function display errors below input. Now the function display errors in top site. I don't know where is problem. Errors should display after click submit button.
class UserValidation{
private $data;
private $errors = '';
public function __construct($data)
{
$this->data = $data;
}
public function validateName()
{
$val = trim($this->data['first_name']);
if(empty($val))
{
return $this->errors = "Empty field";
}
else if(!preg_match('/^[a-zA-Z-0-9]{3,12}$/', $val))
{
return $this->errors = "Wrong first name";
}
}
if(isset($_POST['submit'])){
$validation = new UserValidation($_POST);
$error = $validation->validate_First_Name();
}
">
<div class="row">
<div class="form-group col-xl-12 text-light">
<label>Login</label>
<input type="text" name="first_name" class="form-control">
<div class="error">
<?php echo $error ?? '' ?>
</div>
</div>
</div>
</form>
There are a ton of different ways to do form validation. What you're doing is overly complicated, and as #El_Vanja stated, you shouldn't be throwing exceptions unless something important happens, and incorrectly entering info into a form is extremely common and is to be expected. When validating a form, all you really need to return is the error message.
Edit: this is definitely not production ready as there are plenty of missing parts; this is just an example to give you some ideas regarding validation.
This also puts your error messages below the submit button; which I don't recommend doing as they could be missed if out of the viewport.
<?php
class UserValidation {
public function __construct()
{
# define our errors array
$this->errors = [];
}
# returns any error messages in the errors array
public function errors() {
return $this->errors;
}
public function validate($key, $value)
{
# 'clean' the input
$val = strip_tags(trim($value));
# only validate if it's not the submit button
if($key == 'submit')
{
if($val == '') {
$this->errors[$key] = $key . ' can not be empty';
}
# this is a bad idea as people have apostrophes, etc. in their names
if(!preg_match('/^[a-zA-Z-0-9]{3,12}$/', $val)) {
$this->errors[$key] = $key . ' can only contain letters and numbers';
}
# perform other validation rules here...
}
return $value;
}
}
$v = new UserValidation();
# check if the form was posted using $_SERVER['REQUEST_METHOD']
if($_SERVER['REQUEST_METHOD'] == 'POST') {
# loop through the $_POST array
foreach($_POST as $key => $value) {
# run each form field through the validate function
$v->validate($key, $value);
}
}
?>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<form action="index.php" method="post">
<div class="row">
<div class="form-group">
<label>Login</label>
<input type="text" name="first_name" class="form-control">
</div>
</div>
<div class="row">
<button type="submit" name="submit">Submit</button>
</div>
<div class="row">
<?php
# loop through the errors array and print each error
foreach($v->errors() as $error) {
echo '<span class="text-danger">'.$error.'</span><br>';
}
?>
</div>
</form>
</div>
</body>
</html>
I'm trying to create some admin login. I think my code is correct because when I input wrong email and password the error message appears on login page. However, when I input correct data of my DB, it also shows error message.
Please help me. I appreciate any answer.
my controller (Admin.php):
public function index()
{
$this->admindashboard();
}
public function admindashboard()
{
$data = array();
/* $data['main_content'] = $this->load->view('admin_main', '', TRUE); */
$this->load->view('admin/admin_main', $data);
}
public function admin_regst()
{
$data = array();
$data['main_content'] = $this->load->view('admin-regist', '', TRUE);
$this->load->view('admin/admin_main', $data);
}
My other controller (Login_admin.php):
public function index()
{
$this->load->view('login');
}
public function adminchecklogin()
{
$data = array();
$adminemail = $this->input->post('admin_email', TRUE);
$adminpassword = $this->input->post('admin_psw', TRUE);
$this->load->model('M_login_admin');
$admindetails = $this->M_login_admin->admin_login_check($adminemail);
if (password_verify($adminpassword, $admindetails->admin_psw)) {
if ($admindetails->admin_status == 1) {
$session_data['adminid'] = $admindetails->admin_id;
$session_data['adminemail'] = $admindetails->admin_email;
$session_data['adminusername'] = $admindetails->admin_username;
$session_data['adminstatus'] = $admindetails->admin_status;
$this->session->set_userdata($session_data);
redirect('Admin');
} else {
$data['error_msg'] = "User ini tidak aktif....!!!";
redirect('login', $data);
}
} else {
redirect('error-login', $data);
}
}
public function login_error()
{
$data['error_msg'] = "Email atau Password Anda Salah....!!!";
$this->load->view('login', $data);
}
my model (M_login_admin.php):
public function admin_login_check($adminemail)
{
$admin_details = $this->db->select('*')
->from('admin')
->where('admin_email', $adminemail)
->get()
->row();
return $admin_details;
}
my view(login.php):
<body>
<section class="hero is-fullheight">
<div class="hero-body container has-text-centered">
<div class="login">
<img src="https://logoipsum.com/logo/logo-1.svg" width="325px" />
<p>
<?php
if (isset($success_msg)) {
echo $success_msg;
}
?>
</p>
<p>
<?php
if (isset($error_msg)) {
echo $error_msg;
}
?>
</p>
<form action="<?= base_url(); ?>Login_admin/adminchecklogin" method="POST">
<div class="box">
<div class="field">
<div class="control">
<input class="input is-medium is-rounded" type="email" placeholder="hello#example.com" autocomplete="username" name="admin_email" required />
</div>
</div>
<div class="field">
<div class="control">
<input class="input is-medium is-rounded" type="password" placeholder="**********" autocomplete="current-password" name="admin_psw" required />
</div>
</div>
<div class="field has-text-left ml-3 mt-5">
<label class="checkbox">
<input type="checkbox">
Remember me
</label>
</div>
</div>
<button class="button is-block is-fullwidth is-primary is-medium is-rounded" type="submit">
Login
</button>
</form>
<br>
</div>
</div>
</section>
My route
DB Column
DB Data
Interface
Your database has the admin_psw in plain text that would explain why the password_verify() is failing.
In order to use password_verify(), you have to have hashed the password using password_hash() This would normally be done when the user first registers or any time the user changes their password
Check the documentation for password_hash() in the PHP manual
Once the user login into site unable to fetch the data from database getting blank page if i write foreach condition here is my code.Fetching username and login verification is workig fine.
Controller:
public function index()
{
if($this->session->userdata('admin_logged_in')){
$data['admin_details'] = $this->session->userdata('admin_logged_in');
$data['records']= $this->profile_model->getprofiledata($this->uri->segment(3));
$data['mainpage']='profile';
$this->load->view('templates/template',$data);
}
else{
$this->load->view('welcome');
}
}
Model:
function getprofiledata($id)
{
$this->db->select('profile_details.*');
$this->db->from('profile_details');
$this->db->where(array('profile_details.profile_id'=>$id));
$q=$this->db->get();
if($q->num_rows()>0)
{
return $q->result();
}
else
{
return false;
}
}
View:
<div id="legend">
<legend class="">Profile Information</legend>
</div>
<?php if(isset($records) && is_array($records) && count($records)>0): ?>
<?php foreach($records as $r):?>
<form action="<?php echo base_url();?>profile/updateprofile" role="form" class="form-horizontal" id="location" method="post" accept-charset="utf-8">
<?php
echo form_hidden('profile_id',$r->profile_id);
?>
<div class="form-group">
<label class="control-label col-sm-2 " for="name">Name:</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="name" placeholder="Enter name" value="<?php echo $r->first_name;?>" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 " for="profilename">Profile Name:</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="profile_name" placeholder="Enter Profile name">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 " for="designation">Designation:</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="designation" placeholder="Enter Designation">
</div>
</div>
<button type="submit" class="btn">Submit</button>
</form>
<?php endforeach;endif;?>
You chose the wrong segment number on line $data['records']= $this->profile_model->getprofiledata($this->uri->segment(3));.
Take notice that segment counting starts with zero, so segment no 3 is actually the 4th one in the uri.
If you keep the user id inside your session, you should replace $data['records']= $this->profile_model->getprofiledata($this->uri->segment(3)); with $records = $this->profile_model->getprofiledata($this->session->userdata('profile_id'));. And you're done.
add a new session when you login process like bellow in your login model :
<?php
public function login_user($user_name = '', $password=''){
$userdetails = array(
'email' => $user_name,
'password' => md5($password),
'status'=>1,
);
$this->db->where($userdetails);
$query = $this->db->get('profile_details');
if($query->num_rows()):
$user = $query->result();
$sess_arry = array(
'profile_id' => $user[0]->profile_id, // add new session profile_id
'first_name' => $user[0]->first_name
);
$this->session->set_userdata('admin_logged_in', $sess_arry); //add admin details to session
return true;
else:
return false;
endif;
}
?>
And some change your index method like bellow :
<?php
public function index()
{
if($this->session->userdata('admin_logged_in')){
$data['admin_details'] = $this->session->userdata('admin_logged_in');
$data['country'] = $this->signup_model->getcountry();
$data['states'] = $this->profile_model->getstates();
$profile_id = $this->session->userdata('profile_id');
$records = $this->profile_model->getprofiledata($profile_id);
$data['records']= $records;
$data['mainpage']='profile';
$this->load->view('templates/template',$data);
$this->load->view('templates/sidebar',$data);
}
else{
$this->load->view('welcome');
}
}
?>
I have added new 3 line because i thinks you are no getting profile id properly in $this->uri->segment(3)
So,
$profile_id = $this->session->userdata('profile_id');
$records = $this->profile_model->getprofiledata($profile_id);
$data['records']= $records;
I'm working on a custom CMS using PHP OOP and this is actually my first project ever which is made with object oriented programming so I don't have that much of experience with it. Basically I have a class called Site.class.php which retrieves data from one of the tables in MySQL database and goes like this:
<?php
class Site
{
public $id,$site_name,$site_title,$site_url,$site_tags,$site_desc;
public function __construct()
{
$this->db = new Connection();
$this->db = $this->db->dbConnect();
}
public function getSite($name)
{
if(!empty($name))
{
$site = $this->db->prepare("select * from admins where site_name = ?");
$site->bindParam(1,$name);
$site->execute();
while($row = $site->fetch())
{
$this->id = $row['id'];
$this->site_name = $row['site_name'];
$this->site_title = $row['site_title'];
$this->site_url = $row['site_url'];
$this->site_tags = $row['site_tags'];
$this->site_desc = $row['site_desc'];
}
}
else
{
header("Location: maint/php/includes/errors/005.php");
exit();
}
}
public function getID()
{
return $this->id;
}
public function getSiteName()
{
return $this->site_name;
}
public function getSiteTitle()
{
return $this->site_title;
}
public function getSiteUrl()
{
return $this->site_url;
}
public function getSiteTags()
{
return $this->site_tags;
}
public function getSiteDesc()
{
return $this->site_desc;
}
}
?>
I have included this file at another file which is called settings.php and called it in this way:
$siteSet = new Site();
$siteSet->getSite("Daygostar");
Then I tried echoing out the variables like this:
<div class="box-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="usr">Site Name:</label>
<input type="text" class="form-control" id="usr" disabled='disabled' value="<?php echo $siteSet->getSiteName; ?>">
</div>
<div class="form-group">
<label for="usr">User URL:</label>
<input type="text" class="form-control" id="usr" disabled='disabled' value="<?php echo $siteSet->getSiteUrl; ?>">
</div>
</div>
</div>
</div>
But the problem is that whenever I call this file ,I receive this error message:
Undefined property: Site::$getSiteName
Undefined property: Site::$getSiteUrl
I don't know what's really going wrong because I have coded everything correctly! So if you know how to solve this question please let me know, I really appreciate that.. Thanks in advance.
Those are both methods. You need to add the () to the end of them to invoke the method.
<div class="box-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="usr">Site Name:</label>
<input type="text" class="form-control" id="usr" disabled='disabled' value="<?php echo $siteSet->getSiteName(); ?>">
</div>
<div class="form-group">
<label for="usr">User URL:</label>
<input type="text" class="form-control" id="usr" disabled='disabled' value="<?php echo $siteSet->getSiteUrl(); ?>">
</div>
</div>
</div>
</div>
I'm using codeigniter for a login form validation. The code was previously working fine, but when I made some modifications, it just do not work now.
When I try to type in wrong or leave blank for password or username, the error message is shown as normal, but when I type in the correct username and password, $this->form_validation->run() just give me FALSE with an empty validation_errors() string.
I've tried to restore my old working controller php, but this error resists.
Full code related is available at
User Controller http://pastebin.com/nt2SDVnv
Login View http://pastebin.com/9hEc0EJB
User Model http://pastebin.com/p1z0zLM8
Only related code are pasted below:
Controller:
<?php
class User extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->load->model('user_model');
$this->load->helper('url');
$this->load->helper('form');
$this->load->helper('cookie');
}
function login(){
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|callback_username_check');
$this->form_validation->set_rules('password', 'Password', 'trim|required|md5|callback_password_check');
$this->_username = $this->input->post('username'); //用户名
$remember_me = $this->input->post('remember_me');
$json_string = $this->input->cookie('userinfo');
$userinfo_json = json_decode($json_string);
if(isset($userinfo_json->username)){
if ($this->username_check($userinfo_json->username)){
$this->user_model->login($userinfo);
redirect('admin/dashboard');
}
}
if ($this->form_validation->run() == FALSE){
$this->load->view('account/login');
} else {
$userinfo=$this->user_model->get_by_username($this->_username);
$this->user_model->login($userinfo);
if($remember_me=="on"){$this->user_model->write_session($userinfo);}
redirect('admin/dashboard');
}
}
function username_check($username){
if ($this->user_model->get_by_username($username)){
return TRUE;
}else{
$this->form_validation->set_message('username_check', 'User name not exist.');
return FALSE;
}
}
function password_check($password) {
$password = md5($password);
if ($this->user_model->password_check($this->_username, $password)){
return TRUE;
}else{
$this->form_validation->set_message('password_check', 'Incorrect username or paswsword.');
return FALSE;
}
}
}
View:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login - <?=$this->admin_model->get_title();?></title>
<?php $this->load->view('gy/head');?>
</head>
<body>
<?php $this->load->view('gy/header');?>
<div class="hero-unit header">
<div class="container">
<div style="text-align:center;">
<h1>Sign in</h1>
<p class="lead">Log into <?=$this->admin_model->get_title();?>.</p>
</div>
</div>
</div>
<div class="container">
<div class="span5 offset3">
<?php if(validation_errors() !== '' || #(!$err_message == '')){ ?>
<div class="alert alert-error fade in">
×
<strong>Error!</strong> <?=validation_errors('<span>','</span>');?> <?=#$err_message?>
</div>
<?php } ?>
<?php if(#$message!=''){ ?>
<div class="alert fade in alert-success">
×
<strong>Success!</strong> <?=$message?>
</div>
<?php } ?>
<?php echo form_open('login',array('class'=>'form-horizontal')); ?>
<div class="control-group">
<label class="control-label" for="username">User name</label>
<div class="controls">
<input type="text" id="username" name="username" placeholder="User name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" id="password" name="password" placeholder="Password">
</div>
</div>
<label for="remember_me" class="checkbox">
<input type="checkbox" id="remember_me" name="remember_me"> Remember me (30 days)
</label>
<div style="text-align:center;">
<input type="submit" name="submit" value="Log in" class="btn btn-primary">
</div>
</Form>
</div>
</div>
<?php $this->load->view('gy/footer');?>
</body>
</html>
Model:
<?php
class user_model extends CI_Model {
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->library('session');
}
function login($userinfo)
{
$data = array('username'=>$userinfo->username,
'user_id'=>$userinfo->id,
'role'=>$userinfo->role,
'logged_in'=>TRUE);
$this->session->set_userdata($data);
}
function write_session($userinfo)
{
$user_json = json_encode($userinfo);
$cookie = array(
'name' => 'userinfo',
'value' => $user_json,
'expire' => '2592000',
'secure' => TRUE
);
$this->input->set_cookie($cookie);
}
function get_by_username($username)
{
$this->db->where('username', $username);
$query = $this->db->get('users');
if ($query->num_rows() == 1)
{
return $query->row();
}
else
{
return FALSE;
}
}
function password_check($username, $password)
{
if($user = $this->get_by_username($username))
{
return $user->password == $password ? TRUE : FALSE;
}
return FALSE;
}
}
I suspect the trim rule. It doesn't return a Boolean and I suppose you haven't set any error message for that rule. trim() should be run on the username and password, after the validation runs successful. If you just wanna check if the input has blank spaces You could add a rule to check with the strpos() but again in a custom callback. Just remember to use the Identical opperator '===' instead of the equal '==' .
Controller :
$this->form_validation->set_rules('username','Username','callback_space_check|required|xss_clean|callback_username_check');
function space_check($input){
if(strpos(' ',$input)===false){
return TRUE;
}else{
$this->form_validation->set_message('space_check', '%s contains space.');
return FALSE;
}
}