I have been practicing with PHP and mongodb. I am developing a simple web application but using OOP.
I created a class called user which has my methods to do with user like addUser, deleteUser etc. For add user, I would like for the form to carry out some simple validation tasks, but i am not sure how. Here is the class to add a new user:
function createUser($username, $name, $email, $password){
$user = array(
'username' => $username,
'name' => $name,
'email' => $email,
'password' => $password
);
if ($this->db->count(array('username' => $username)) == 0) {
$this->db->insert($user);
return true;
} else {
echo 'username taken';
}
}
And the html:
<?php
session_start();
include_once 'user.php';
include './templates/header.php';
if (isset($_POST['register']) && ($_POST['register']) == ($_POST["register"])) {
$user = new User();
$return = $user->createUser(
$_POST['username'],
$_POST['name'],
$_POST['email'],
$_POST['password'],
$_POST['password2']);
}
if ($return == true) {
echo 'you have successfully registered';
} else {
echo '</br>' . 'sorry, try again';
}
?>
<div class="container">
<div class="jumbotron">
<form method="post" action="">
<label>Username: </label><br>
<input name="username" type="text" ><br><br>
<label>Name: </label><br>
<input name="name" type="text"><br><br>
<label>Email: </label><br>
<input name="email" type="email" ><br><br>
<label>Password: </label><br>
<input name="password" type="password" ><br><br><br>
<label>Repeat Password: </label><br>
<input name="password2" type="password" ><br><br><br>
<input name="register" class="btn btn-primary btn-lg" type="submit" value="Register"><br>
</form>
</div>
</div>
Please feel free to correct me on other mistakes you may notice. I know there is bound to be some.
i wrote a simple example for you its simple and useful
class validation {
public $currentValue;
public $values = array();
public $errors = array();
public function __construct() {
parent::__construct();
// echo "burasi model sayfasi ";
}
public function post($key){
if(isset($_POST[$key])){
$this->values[$key] = $_POST[$key];
$this->currentValue = $key;
return $this;
}else{ die("hi boo boo ! your form values are empty");}
}
public function isEmpty(){
if(empty($this->values[$this->currentValue])){
$message='the form is emppty';
$this->errors[$this->currentValue]['empty'] =''.$message.'';
}
return $this;
}
public function submit(){
if(empty($this->errors)){
return true;
}else{
return false;
}
}
}
this is an example so how can you use it ?
firstly you need yo call the class
$form = new validation ();
$form->post("all you need just write post name here ")
->isEmpty();
if($form->submit()){
//everyting is ok !
you cann add delet or update data
}else{
$data["error"] = $form->errors; // and we sett the errorr mesages to the array now you can show the user the errormesages ! well done
}
}
Related
I want to Login whenever I click the submit button, I get all information on username and password to log in and can get in into the dashboard. can somebody help me?
but I got an error like this
Undefined property: App\Controllers\Admin::$user
this is my code:
public function __construct()
{
$this->user = new UserModel();
$this->sponsor = new SponsorModel();
$this->auditorium = new auditoriumModel();
}
public function index()
{
$user = $this->user->findAll();
$audVid = $this->auditorium->findAll();
$sponsorData = $this->sponsor->findAll();
$data = [
'user' => $user,
'sponsorData' => $sponsorData,
'audvid' => $audVid
];
// dd($sponsorData);
echo view('templates/header');
echo view('login', $data);
echo view('templates/footer');
}
public function doLogin()
{
$email
= $this->request->getVar('email');
$password =
$this->request->getVar('password');
$userData = $this->user->where('email', $email)
->where('password', $password)
->findAll();
if ($userData == null) {
return redirect()->to('/admin');
} else {
$_SESSION['logonUser'] = 'aktif';
return redirect()->to('/adminDashboard', $userData);
}
}
}
this is my login view
<form id="login-form" class="form" action="/admin/doLogin" method="post">
<h3 class="text-center text-info">Login Admin</h3>
<div class="form-group">
<label for="username" class="text-info">Username:</label><br>
<input type="text" name="username" id="username" class="form-control">
</div>
<div class="form-group">
<label for="password" class="text-info">Password:</label><br>
<input type="text" name="password" id="password" class="form-control">
</div>
<div class="form-group">
<labezl for="remember-me" class="text-info"><span>Remember me</span> <span><input id="remember-me" name="remember-me" type="checkbox"></span></labezl><br>
<input type="submit" class="btn btn-info btn-md" value="submit" href="/adminDashboard">
</div>
<div id="register-link" class="text-right">
Register here
</div>
</form>
can somebody help me to solve my code?
thanks
$userData = $this->user->where('email', $email)
->where('password', $password)
->findAll();
findAll() will get you an array of rows that applies to your criteria. In your case will try to find all users where email and password are correct, but it will still return you an array of them, not just one. You need to be using find() instead.
Guys Im new to php and codeigniitor. Im trying to make a post application but it's not working please help.
here is my controller function
public function status(){
$this->load->library('form_validation');
$this->form_validation->set_rules('post', 'Post Something', 'required');
if ($this->form_validation->run() == FALSE) {
$user = $this->session->userdata('user');
$data1['user'] = $user;
$this->load->view('pages/panel',$data1);
}
else{
$this->load->model('reg_model');
$formArray1 = array();
$formArray1['post'] = $this->input->post('post');
$formArray1['posted_by'] = $user['ID'];
$this->reg_model->create1($formArray);
$this->session->set_flashdata('msg', 'Your account is created successfully');
redirect(base_url().'index.php/Registration/panel');
}
here is my form
<?php echo validation_errors();?>
<form action = " <?php echo base_url()?>registration/status" name= "registrationForm1" id="registrationForm1" method = "post">
<label class =" form-control" for="post">Post Something</label></br>
<textarea style =" width:100%" class="form-control" rows="3" id="post" placeholder="Your message..."></textarea>
<p class ="invalid-feedback"><?php echo form_error('posts');?></p></br>
<button type="submit" class="btn btn-primary btn-block">Post</button>
</form>
my model:
public function create1($formArray1)
{
$this->db->insert('posts', $formArray1);
}
You should use $formArray1 not $formArray
$formArray1 = array();
$formArray1['post'] = $this->input->post('post');
$formArray1['posted_by'] = $user['ID'];
$this->reg_model->create1($formArray1);
and in Model:-
public function create1($formArray1)
{
$this->db->insert('users', $formArray1);
}
please help me... My controller for registration and login is not working. Whenever I input the data in either login or register it will back to register and login view and not the index/home nor the data that I input enter mysql.
I create it like when I success in inputting the data on register it will direct to login then when you login it will direct to home. Other is login, when I login it will direct to home if it can login.
Controller: Member.php
class Member extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library(array('session', 'form_validation'));
$this->load->helper(array('url', 'form'));
$this->load->model("Member_model");
}
public function index() {
$this->load->view('front/login');
}
public function Login() {
$this->load->view('front/login');
}
public function Register() {
$this->load->view('front/register');
}
public function profile() {
if ($_SESSION['user_logged'] == FALSE) {
$this->session->set_flashdata("error","Please login first to view");
redirect('Member/Login');
}
$this->load->view('front/home');
}
}
Controller: Register.php
class Register extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library(array('session', 'form_validation'));
$this->load->helper(array('url', 'form'));
$this->load->model("Member_model");
}
public function registerMember() {
//validate the data taken through the register form
$this->form_validation->set_rules('username','Username','required|is_unique[member.username]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required|md5|min_length[6]');
$this->form_validation->set_rules('conf_password', 'Confirm Password', 'trim|required|min_length[6]|matches[password]');
if ($this->form_validation->run() == TRUE) {
//load the model to connect to the db
$this->load->model('Member_model');
$this->Member_model->insertMember();
//set message to be shown when registration is completed
$this->session->set_flashdata('success','You are registered!');
redirect('Member/Login');
} else {
$this->load->view('front/register');
}
}
}
Controller: Login.php
class Login extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library(array('session', 'form_validation'));
$this->load->helper(array('url', 'form'));
$this->load->model("Member_model");
}
public function loginMember() {
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('front/login');
} else {
$this->load->model('Member_model');
$reslt = $this->Member_model->checkLogin();
if ($reslt != false) {
//set session
$username = $_POST['username'];
$password = sha1($_POST['password']);
//fetch from databse
$this->db->select('*');
$this->db->from('member');
$this->db->where(array('username' => $username , 'password' => $password));
$query = $this->db->get();
$member = $query->row();
//if use exists
if ($member->username) {
//login message
$this->session->set_flashdata("success","You are logged in");
//set session variables
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $member->username;
//redirect
redirect('Member/profile','refresh');
}
} else {
//wrong credentials
$this->session->set_flashdata('error','Username or Password invalid!');
redirect('Member/Login');
}
}
}
//logging out of a user
public function logoutMember() {
unset($_SESSION);
redirect('Member/Login');
}
}
Model: Member_model.php
class Member_model extends CI_Model {
public function insertMember () {
//insert data
$data = array(
//assign data into array elements
'username' => $this->input->post('username'),
'email' =>$this->input->post('email'),
'password' => sha1($this->input->post('password'))
);
//insert data to the database
$this->db->insert('member',$data);
}
public function checkLogin() {
//enter username and password
$username = $this->input->post('username',TRUE);
$password = sha1($this->input->post('password',TRUE));
//fetch data from database
$this->db->where('username',$username);
$this->db->where('password',$password);
$res = $this->db->get('member');
//check if there's a user with the above inputs
if ($res->num_rows() == 1) {
//retrieve the details of the user
return $res->result();
} else {
return false;
}
}}
View:
Register.php
<body class="background-login">
<div class="main-w3layouts wrapper">
<h1> SignUp </h1>
<div class="main-agileinfo">
<div class="agileits-top">
<form method="post" action="<?php echo site_url('register/registerMember'); ?>" >
<input class="text" type="text" id="username" name="username" placeholder="Enter a username">
<input class="text email" type="email" id="email" name="email" placeholder="Enter your email">
<input class="text" type="password" id="password" name="password" placeholder="Enter a password">
<input class="text w3lpass" type="password" id="conf_password" name="conf_password" placeholder="Confirm your password">
<div class="wthree-text">
<label class="anim">
<input type="checkbox" class="checkbox" required="">
<span>I Agree To The Terms & Conditions</span>
</label>
<div class="clear"> </div>
</div>
<input type="submit" value="SignUp">
</form>
<p>Already have an Account? Login Now!</p>
</div>
</div>
Login.php
<body class="background-login">
<div class="main-w3layouts wrapper">
<h1> SignIn </h1>
<div class="main-agileinfo">
<div class="agileits-top">
<form method="post" action="<?php echo site_url('Login/loginMember'); ?>" >
<input class="text" type="text" id="username" name="username" placeholder="Your username"><br>
<input class="text" type="password" id="password" name="password" placeholder="Your password">
<input type="submit" value="Login"/>
</form>
<p>Don't have an Account? SignUp NOW!</p>
</div>
</div>
I even chop my code into part like this, but the problem still the same... Is just like the if form_validation->run is not running and just got cut to else...
So the problem is:
When I input data it will not enter the data or redirect to another page.
*register -> it will direct to register after i submit the data
What I want is when I submit the data it will direct to login.
*login -> it will direct to login after i submit the data
What I want is when I submit the data it will direct to home.
-> result ->
I also had this case . I solved it by passing $this in to run()
if ($this->form_validation->run($this) == TRUE)
You can pass array in where condition in checkLogin function
$where_array = array('username' => $username,'password' => $password);
$this->db->where($where_array);
$res = $this->db->get('member');
Hope it help you too!
You can not use the form_open function and html form tag at the same time, so remove anyone from it and pass the whole path in the action.
If you use form_open function then please add the form_close function.
in your register and login view
<?= form_open() ?>
<form action="#" method="post">
you added this. this is wrong.at a same time you open two form you need to remove a line.and add some action to form for example
<form action="<?= base_url('yourControllerName/YourMethodname')?>" method='post'></form>
and second thing in Member.php Controller you added this line
if ($this->form_validation->run() === FALSE){
Some code
}
this is wrong you need this
if ($this->form_validation->run() == FALSE)
please check and ping me......
Make sure your base_url in config.php is not null.
In register.php remove <?=form_open('member/login')?> and <?= form_close() ?>
Instead add, <form method="post" action="<?php echo site_url('Member/register'); ?>" >
and
</form>
redirect your page:
//login
if ($this->form_validation->run() === TRUE)
{
$username = $this->input->post('username');
$email = $this->input->post('email');
$password = $this->input->post('password');
$user= $this->member_model->create_user();
if($user >0){
redirect('front/home');
} else {
redirect('front/login');
}
}
you can same as in singup
I am following the tutorial in this page http://www.kodingmadesimple.com/2016/06/codeigniter-login-and-registration-tutorial-source-code.html and me and other people had found the same error.
It appers to be something wrong in the login controller because it always shows the "Wrong Email-ID or Password!" message, even when the credentials are fine, but I can not find the mistake (although I had found and solved some others), please help me.
controller:
<?php
class login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form','url','html'));
$this->load->library(array('session', 'form_validation'));
$this->load->database();
$this->load->model('user_model');
}
public function index()
{
// get form input
$email = $this->input->post("email");
$password = $this->input->post("password");
//(This was added later for me, as it was needed)
$this->load->helper('security');
// form validation
$this->form_validation->set_rules("email", "Email-ID", "trim|required|xss_clean");
$this->form_validation->set_rules("password", "Password", "trim|required|xss_clean");
if ($this->form_validation->run() == FALSE)
{
// validation fail
$this->load->view('login_view');
}
else
{
// check for user credentials
$uresult = $this->user_model->get_user($email, $password);
if (count($uresult) > 0)
{
// set session
$sess_data = array('login' => TRUE, 'uname' => $uresult[0]->fname, 'uid' => $uresult[0]->id);
$this->session->set_userdata($sess_data);
redirect("profile/index");
}
else
{
$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Wrong Email-ID or Password!</div>');
redirect('login/index');
}
}
}
}
related part in the view:
<?php $attributes = array("name" => "loginform");
echo form_open("login/index", $attributes);?>
<legend>Login</legend>
<div class="form-group">
<label for="name">Email-ID</label>
<input class="form-control" name="email" placeholder="Enter Email-ID" type="text" value="<?php echo set_value('email'); ?>" />
<span class="text-danger"><?php echo form_error('email'); ?></span>
</div>
<div class="form-group">
<label for="name">Password</label>
<input class="form-control" name="password" placeholder="Password" type="password" value="<?php echo set_value('password'); ?>" />
<span class="text-danger"><?php echo form_error('password'); ?></span>
</div>
<div class="form-group">
<button name="submit" type="submit" class="btn btn-info">Login</button>
<button name="cancel" type="reset" class="btn btn-info">Cancel</button>
</div>
<?php echo form_close(); ?>
<?php echo $this->session->flashdata('msg'); ?>
If i did not explained myself clearly, or if you need to see more code, you can check it directly on the tutorial link.
Your help will be much appreciated, thanks.
EDIT:
This is the function in the model:
function get_user($email, $pwd)
{
$this->db->where('email', $email);
$this->db->where('password', md5($pwd));
$query = $this->db->get('user');
return $query->result();
}
I had already change "pwd" for "password" and removed the md5 as I dont need it,and now its working.
The form is validating OK as you are getting to this line:
$uresult = $this->user_model->get_user($email, $password);
if (count($uresult) > 0)
Check your get_user function to make sure you are returning the result set, ie:
$this->db->where('user_email', $user_email);
$result = $this->db->get('users');
return $result->result();
I have this code that was working initially, but does not work after I restarted my computer.
The error I am getting is:
Warning: Illegal offset type in isset or empty in D:\xampp\htdocs\cookieboylive\classes\Session.php on line 4
There's 3 files on my site - Index, Login, Register. Index page checks if users is logged in, but I don't think it has anything to do with the problem.
Here's the current code:
The main register/login.php page
require_once 'core/init.php';
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array('required' => true),
'password' => array('required' => true)
));
if($validation->passed()) {
$user = new User();
$login = $user->login(Input::get('username'), Input::get('password'));
if($login) {
Redirect::to('index.php');
} else {
echo '<p>Sorry, login failed.</p>';
}
} else {
foreach($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
}
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array(
'required' => true,
'min' => 2,
'max' => 20,
'unique' => 'users'
),
'password' => array(
'required' => true,
'min' => 6
),
'password_again' => array(
'required' => true,
'matches' => 'password'
),
'name' => array(
'required' => true,
'min' => 2,
'max' => 50
)
));
if($validation->passed()) {
$user = new User();
$salt = Hash::salt(32);
try {
$user->create(array(
'username' => Input::get('username'),
'password' => Hash::make(Input::get('password'), $salt),
'salt' => $salt,
'name' => Input::get('name'),
'joined' => date('Y-m-d H:i:s'),
'group' => 1
));
Session::flash('home', 'Register SUCCESS');
Redirect::to('index.php');
} catch(Exception $e) {
die($e->getMessage());
}
} else {
foreach($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="styles/register_login_styles.css">
<link rel="stylesheet" type="text/css" href="styles/animate-custom.css">
</head>
<body>
<div class="container">
<div id="container_demo" >
<a class="hiddenanchor" id="toregister"></a>
<a class="hiddenanchor" id="tologin"></a>
<div id="wrapper">
<div id="login" class="animate form">
<form action="" method="post">
<div class="field">
<h1>Log in</h1>
<p>
<label for="username" class="uname" data-icon="u" >Username </label>
<input id="username" name="username" required="required" type="text" placeholder="Username" autocomplete="off">
</p>
<p>
<label for="password" class="youpasswd" data-icon="p">Password </label>
<input id="password" name="password" required="required" type="password" placeholder="Password">
</p>
<p class="keeplogin">
<input type="checkbox" name="loginkeeping" id="loginkeeping" value="loginkeeping">
<label for="loginkeeping">Keep me logged in</label>
</p>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<p class="login button">
<input type="submit" value="Login">
</p>
<p class="change_link">
Not a member yet ?
Join us
</p>
</form>
</div>
</div>
<div id="register" class="animate form">
<form action="" method="post">
<h1> Sign up </h1>
<p>
<label for="username" class="uname" data-icon="u">Username</label>
<input id="username" value="<?php echo escape(Input::get('username')); ?>" name="username" required="required" type="text" placeholder="Username" autocomplete="off">
</p>
<p>
<label for="password" class="youpasswd" data-icon="p">Your password </label>
<input id="password" name="password" required="required" type="password" placeholder="Password">
</p>
<p>
<label for="password_again" class="youpasswd" data-icon="p">Please confirm your password </label>
<input id="password_again" name="password_again" required="required" type="password" placeholder="Password again">
</p>
<p>
<label for="name" class="youmail" data-icon="n" >Name</label>
<input id="name" name="name" value="<?php echo escape(Input::get('name')); ?>" required="required" type="text" placeholder="Name" autocomplete="off">
</p>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<p class="signin button">
<input type="submit" value="Sign up">
</p>
<p class="change_link">
Already a member ?
Go and log in
</p>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Session.php
<?php
class Session {
public static function exists($name) {
return (isset($_SESSION[$name])) ? true : false;
}
public static function put($name, $value) {
return $_SESSION[$name] = $value;
}
public static function get($name) {
return $_SESSION[$name];
}
public static function delete($name) {
if(self::exists($name)) {
unset($_SESSION[$name]);
}
}
public static function flash($name, $string = '') {
if(self::exists($name)) {
$session = self::get($name);
self::delete($name);
return $session;
} else {
self::put($name, $string);
}
}
}
User.php
<?php
class User {
private $_db,
$_data,
$_sessionName,
$_isLoggedIn;
public function __construct($user = null) {
$this->_db = DB::getInstance();
$this->_sessionName = Config::get('session/session_name');
if(!$user) {
if(Session::exists($this->_sessionName)) {
$user = Session::get($this->_sessionName);
if($this->find($user)) {
$this->_isLoggedIn = true;
} else {
// Pr0cess logout
}
} else {
$this->find($user);
}
}
}
public function create($fields = array()) {
if(!$this->_db->insert('users', $fields)) {
throw new Exception('There was a problem creating an account.');
}
}
public function find($user = null) {
if($user) {
$field = (is_numeric($user)) ? 'id' : 'username';
$data = $this->_db->get('users', array($field, '=', $user));
if($data->count()) {
$this->_data = $data->first();
return true;
}
}
return false;
}
public function login($username = null, $password = null) {
$user = $this->find($username);
if($user) {
if($this->data()->password === Hash::make($password, $this->data()->salt)) {
Session::put($this->_sessionName, $this->data()->id);
return true;
}
}
return false;
}
public function data() {
return $this->_data;
}
public function isLoggedIn() {
return $this->_isLoggedIn;
}
}
I'm getting Fatal error: DEBUG: array ...
That means $name is an array, which is obviously an illegal string offset. $_SESSION[array()] does not work. Make sure you're passing the right value to Session::exists().
I tried most of the solutions suggested above. In actual fact the answer is not in the spelling but is in the fact that, as was pointed out above, the $name variable in the exists function is actually an array.
public static function exists($name) {
return (isset($_SESSION[$name])) ? true : false;
}
The simple fix is to append [0] to [$name] so it becomes [$name][0] which returns the value associated with it and the one you want to see. Works for me. Why it worked in the video, I can't figure out; may be a configuration thing.
I recognize the context you are dealing with, a tutorial PHP login/registration project from Skillfeed. In fact I had the very same error that led me to a google search on the same error - I ended on this stackoverflow thread by You.
I couldn't find the answers very helpful but I looked through the classes of my project and I found the source of my problem in another class than your 3 classes shown in here.
That is in Token.php :
public static function check($token){
$tokenName = Config::get('sesson/token_name');
if(Session::exists($tokenName) && $token === Session::get($tokenName)){
Session::delete($tokenName);
return true;
}
return false;
}
The problem was a simple misspelling , notice the get() function with its string parameter 'sesson/token_name', it should have been 'session/token_name'. Once I fixed this it worked for me!
It simply means the type of the variable (int, bool, array,..) you are passing does not aligns with expected parameter type in empty or isset.
You have not typed the $name variable and that`s should be problem.
Try this which will check also $name variable:
return !empty($name) && is_string($name) && isset($_SESSION[$name]) ? true : false;
Just play with some situations or implement typing into you code.
"Warning: Illegal offset type in isset or empty" may be shown if key-variable is not string. Example:
foreach ($xml->attributes() as $attrname => $attrval)
{
if($attrname == "Name") $Name = $attrval;
if(isset($_GET[$Name])) //catch Warning
...
Because gettype($Name) --> object.
Use type conversion to string:
if(isset((string)$_GET[$Name])) //pass Perfect