Check if logged in - php

Hi everyone,
Im trying to figure out why my script keeps redirecting to my login page. So far I haven't found it yet. Could someone explane to me which mistakes I'm making?
This is my code.
functions.php
function redirect_to($location = NULL) {
if ($location != NULL) {
header("Location: {$location}");
exit;
}
}
function include_layout_template($template="") {
include(SITE_ROOT.DS.'public'.DS.'layouts'.DS.$template);
}
index.php
<?php
require_once('../../includes/initialize.php'); ?>
<?php if (!$session->is_logged_in()) { redirect_to("login.php"); } ?>
<?php include_layout_template("admin_header.php"); ?>
Logout
<?php include_layout_template("admin_footer.php"); ?>
session.php
<?php
class Session {
public $logged_in = false;
public $user_id;
public $message;
function __construct() {
session_start();
$this->check_message();
$this->check_login();
if($this->logged_in) {
// actions to take right away if user is logged in
} else {
// actions to take right away if user is not logged in
}
}
public function login_user($user) {
if($user) {
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->logged_in = true;
}
}
public function is_logged_in() {
return $this->logged_in;
}
public function logout() {
unset($_SESSION['user_id']);
unset($this->user_id);
$this->logged_in = false;
}
private function check_login() {
if(isset($_SESSION['user_id'])) {
$this->user_id = $_SESSION['user_id'];
$this->logged_in = true;
} else {
unset($this->user_id);
$this->logged_in = false;
}
}
private function check_message() {
// Is there a message stored in the session?
if(isset($_SESSION['message'])) {
// Add it as an attribute and erase the stored version
$this->message = $_SESSION['message'];
unset($_SESSION['message']);
} else {
$this->message = "";
}
}
}
$session = new Session();
//$message = $session->message();
user.php
<?php
require_once('../../includes/initialize.php');
class Users extends DatabaseQuery
{
protected $tablename = 'users';
protected $db_fields = array('id', 'first_name', 'last_name', 'password', 'username');
public $id;
public $first_name;
public $last_name;
public $password;
public $username;
public static function create_user($first_name, $last_name, $password, $username)
{
global $database;
$sql = "INSERT INTO users (";
$sql .= "first_name, last_name, password, username) ";
$sql .= "VALUES (";
$sql .= "'{$first_name}', '{$last_name}', '{$password}', '{$username}')";
$result = $database->query($sql);
return $result;
}
public static function find_username($username) {
global $database;
$sql = "SELECT * FROM users ";
$sql .= "WHERE username= '{$username}' ";
$sql .= "LIMIT 1";
$result = $database->query($sql);
$admin = mysqli_fetch_assoc($result);
return $admin;
}
public static function find_password($username, $password) {
global $database;
$sql = "SELECT * FROM users ";
$sql .= "WHERE username= '{$username}' ";
$sql .= "And password=".crypt($password) ;
$sql .= " LIMIT 1";
$result = $database->query($sql);
$admin = mysqli_fetch_assoc($result);
return $admin;
}
public static function password_check($password, $existing_hash) {
$hash = crypt($password, $existing_hash);
if ($hash === $existing_hash) {
return true;
} else {
return false;
}
}
public static function login($username, $password) {
$admin = self::find_username($username);
if ($admin) {
// found username, check password.
if (self::password_check($password, $admin['password'])) {
//password matches
return $admin;
} else {
//password does not match
return false;
}
} else {
// admin not found
return false;
}
}
}
$user = new Users();
login.php
<?php
/**
* FIRSTNAME LASTNAME PASSWORD USERNAME
* Coos Wolff secret Admin
* Kevin Doofus password Kevin
*/
include_once("../../includes/initialize.php");
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$login = Users::login($username, $password);
if($login) {
$session->logged_in = true;
redirect_to('index.php');
} else {
redirect_to('login.php');
}
} ?>
<form id='login' action='create_user.php' method='post' accept-charset='UTF-8'>
<fieldset >
<legend>Create User</legend>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<label for='username' >UserName:</label>
<input type='text' name='username' id='username' maxlength="50" />
<label for='password' >Password:</label>
<input type='password' name='password' id='password' maxlength="50" />
<label for='firstName' >FirstName:</label>
<input type='text' name='first_name' id='first_name' maxlength="50" />
<label for='lastName' >LastName:</label>
<input type='text' name='last_name' id='last_name' maxlength="50" />
<input type='submit' name='submit' value='Submit' />
</fieldset>
</form>
<hr /><br /><hr />
<form id='login' action='login.php' method='post' accept-charset='UTF-8'>
<fieldset >
<legend>Login</legend>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<label for='username' >UserName:</label>
<input type='text' name='username' id='username' maxlength="50" VALUE="Kevin"/>
<label for='password' >Password:</label>
<input type='password' name='password' id='password' maxlength="50" />
<label for='firstName' >FirstName:</label>
<input type='text' name='first_name' id='first_name' maxlength="50" value="Kevin" />
<label for='lastName' >LastName:</label>
<input type='text' name='last_name' id='last_name' maxlength="50" value="Doofus"/>
<input type='submit' name='submit' value='Submit' />
</fieldset>
</form>
If I submit the form without the code to check if somebody is logged in the code works fine. But with the checking code it keeps redirecting me to the login page. After submitting the form I set $session->logged_in = true. But still nothing. I have look on google to see what im doing wrong. But I can't figure it out. I tried many different codes but it all ends up the same way. Redirecting me to the login in page. It's probably an easy fix. But I just can't see it. Could somebody tell me what I am doing wrong?
Kind Regards,
Coos

You are going to laugh when I tell you this. According to the documentation:
If the return is omitted the value NULL will be returned.
public function is_logged_in() {
// Add the return statement
return $this->logged_in;
}
It is returning NULL, which is a "falsy" value so your check thinks it's not logged in.

Related

Verify custom table in magento for custom module

I have made the redirect from the question i have posted here
Now i have another form in the redirected page where i need to enter name and mobile number and if it matches in my db table helloworld it will go to one page or else to another
<p>You have successfully registered</p>
<div>
<label>Login</label>
</div>
<div>
<form action="" method="post">
<label> Username </label>
<strong>:</strong>
<input class="input-text required-entry" type="text" name="fname" maxlength="20">
<label>Mobile No</label>
<strong>:</strong>
<input class="required-entry" type="number" maxlength="10" name="mobileno">
<input type="submit" name="login" value="Login">
<input type="button" name="cancel" value="Cancel">
</form>
</div>
Can any one help me how no i can verify it with existing data in db and make this work ? Shall I start it with using index controller or is there any magento way?
Update:
this is my Indexcontroler.php after below answer update
<?php
class MyCustom_Helloworld_IndexController extends Mage_Core_Controller_Front_Action
{
/*
* this method privides default action.
*/
public function indexAction()
{
if($this->getRequest()->getParams()) {
$param = $this->getRequest()->getParams();
echo $firstname = $param['fname'];
$lastname = $param['lname'];
$address = $param['address'];
$state = $param['state'];
$city = $param['city'];
$mobile = $param['mobileno'];
$model = Mage::getModel('helloworld/helloworld');
// $model->setTitle($title);
$model->setFirstname($firstname);
$model->setLastname($lastname);
$model->setAddress($address);
$model->setState($state);
$model->setCity($city);
$model->setMobileno($mobile);
$model->save();
$this->_redirect('helloworld/index/login');
// $this->_redirectReferer();
}else {
/*
* Initialization of Mage_Core_Model_Layout model
*/
$this->loadLayout();
/*
* Building page according to layout confuration
*/
$this->renderLayout();
}
}
public function loginAction()
{
$this->loadLayout();
$this->renderLayout();
}
public function loginnAction()
{
if($this->getRequest()->getParams()) {
$param = $this->getRequest()->getParams();
$username = $param['fname'];
$mobile = $param['mobileno'];
$check = Mage::getModel('helloworld/helloworld')
->AddFieldToFilter('mobileno', array('eq' => $mobile))
->AddFieldToFilter('fname', array('eq' => $username));
if(count($check)==1) {
$this->_redirectReferer();
}else {
$this->_redirect('helloworld/index/login');
}
}
}
}
you can add check like that
public function loginAction()
{
if($this->getRequest()->getParams()) {
$param = $this->getRequest()->getParams();
$username = $param['fname'];
$mobile = $param['mobile'];
$connectionresource = Mage::getSingleton('core/resource');
$readconnection = $connectionresource->getConnection('core_read');
$table = $connectionresource->getTableName('helloworld/helloworld');
$allrecord = $readconnection->select()->from(array('helloworld'=>$table))->where('helloworld.mobileno=?', $mobileno)
->where('helloworld.fname=?', $username);
$alldata =$readconnection->fetchAll($allrecord);
if(count($alldata)==1) {
$this->_redirect('home');
}else {
$this->_redirect('customer/account');
}
}

CodeIgniter 3.0.2 does not login with old code

User_log.php (This is controller File)
<?php
class User_log extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('user_data');
}
public function index($msg = NULL)
{
$data['msg'] = $msg;
$data['title'] = "My Real Title";
$data['heading'] = "My Real Heading";
$data['attribute'] = array('name' => 'process');
$data['data'] = array(
'name' => 'username',
'id' => 'username',
);
$data['pass'] = array(
'name' => 'password',
'id' => 'password',
);
$this->load->view('login', $data);
}
public function process()
{
// Load the model
$this->load->model('user_data');
// Validate the user can login
$result = $this->user_data->validate();
// Now we verify the result
if(! $result){
// If user did not validate, then show them login page again
$msg = '<font color=red>Invalid username and/or password.</font><br />';
$this->index($msg);
}else{
// If user did validate,
// Send them to members area
redirect('success');
}
}
}
User_data.php (This is model file)
<?php
class User_data extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function validate()
{
$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);
$query = $this->db->get('user');
if($query->num_rows == 1)
{
// If there is a user, then create session data
$row = $query->row();
$data = array(
'id' => $row->id,
'username' => $row->username,
'validated' => true
);
$this->session->set_userdata($data);
return true;
}
return false;
}
}
login.php (This is view file)
<head>
<title>Jotorres Login Screen | Welcome </title>
</head>
<body>
<div id='login_form'>
<form action='<?php echo base_url();?>index.php/blog/process' method='post' name='process'>
<h2>User Login</h2>
<br />
<label for='username'>Username</label>
<input type='text' name='username' id='username' size='25' /><br />
<label for='password'>Password</label>
<input type='password' name='password' id='password' size='25' /><br />
<input type='Submit' value='Login' />
</form>
</div>
</body>
</html>
Where is the problem of this code? Is not working properly in CodeIgniter version 3.0.
According to the code provided, your form action is wrong.
<form action='<?php echo base_url();?>index.php/blog/process' method='post' name='process'>
^ ^
This should be
<form action='<?php echo base_url();?>index.php/user_log/process' method='post' name='process'>
^ ^
Instead of blog, it should be user_log.
Also you are not echoing the error message in login page.
Add this some where in your login.php may be after your <form> tag.
<?= $msg ?>
Step 1:
Change from blog to user_blog in your view
<form action='<?php echo base_url();?>index.php/user_log/process' method='post' name='process'>
Step 2:
Modify also this function in your model
public function process()
{
// Load the model
$this->load->model('user_data');
// Validate the user can login
$result = $this->user_data->validate();
// Now we verify the result
if(! $result){
// If user did not validate, then show them login page again
$msg = '<font color="red">Invalid username and/or password.</font><br />';
$this->index($msg);
}else{
// If user did validate,
// Send them to members area
redirect('success');
}
}

PHP - Login Page

We both thought it was working but I tested it and it doesnt output anything. It checks if theres sessions e.t.c and if not then its meant to output a form but it doesnt can anyone enlighten me on my error?
Code:
<?php
session_start();
//Include Database Config.
include('../cdn/global/db.php');
//PDO Settings.
$opt = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION );
$dsn = "mysql:host=$host;dbname=$dbname";
//Create a PDO Session.
$DBH = new PDO($dsn, $username, $password, $opt);
//Session Attributes.
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$loginForm = "
<form method='POST' action='' class='pure-form' style='color: #000;'>
<fieldset class='pure-group'>
<input type='text' name='username' style='display: inline-block;' class='pure-input-1-2' placeholder='Username'><br>
</fieldset>
<fieldset class='pure-group'>
<input type='password' name='password' style='display: inline-block;' class='pure-input-1-2' placeholder='Password'><br>
</fieldset>
<fieldset class='pure-group'>
<button type='submit' style='display: inline-block;' class='pure-button pure-input-1-2 pure-button-primary'>Login</button>'
</fieldset>
</form>";
if(isset($_POST['username']) && isset($_POST['password'])){
echo $_POST['username'].'is trying to login with password'.$_POST['password'];
$st = $DBH->prepare("SELECT :username FROM users WHERE username = :username AND password = :password");
$st->bindParam(':password', $_POST['password']);
$st->bindParam(':username', $_POST['username']);
$st->execute();
if($st->rowCount()){
$row = $st->fetch(PDO::FETCH_OBJ);
$_SESSION['username'] = $row->username;
echo $_SESSION['username'];
return true;
}
} else if(!isset($_SESSION['username'])) {
echo $loginForm;
}
?>
I think your problem will be resolved if you remove the isset from the first two lines so your first lines should look as follow:
if(!$_SESSION['username'] && ! $_POST['username'] && ! $_POST['password']) {
echo $loginForm;
} elseif(isset($_SESSION['username']) && isset($_POST['username']) && isset($_POST['password'])) {
$grantAccess = login(); //after some serious validation or validate inside
if(!$grantAccess) {
echo 'Test 2';
}
}
Personally, I try to separate tasks so I can keep things straight. Here is basically what I do. Note, all the functions would be on their own files included as needed into any pages that require them. I have notated areas of interest:
<?php
session_start();
// This would be better as a static class so as not to create new connections all the time
// You can populate all the false values here with actual database info
// If you do it here, then the function will not need arguments when you go
// To use it. The only time you would populate the args after this point is if
// you need to connect to multiple databases on the same page.
function Connect($host = false,$username = false,$password = false,$dbname = false)
{
try {
//Create a PDO Session.
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password,array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ));
//Session Attributes.
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $e) {
echo "<code><pre>".print_r($e)."</pre></code>";
$con = false;
}
return $con;
}
// Since you are just assigning a variable some html, may as well make it a bit flexible in a function (just incase)
function LoginForm($settings = false)
{
$method = (!empty($settings['method']))? $settings['method']:"post";
$action = (!empty($settings['action']))? $settings['action']:"";
$id = (!empty($settings['id']))? ' id="'.$settings['id'].'"':"";
$class = (!empty($settings['class']))? $settings['class']:"pure-form";
ob_start();
?>
<form method='<?php echo $method; ?>' action='<?php echo $action; ?>' class='<?php echo $class; ?>' style='color: #000;'<?php echo $id; ?>>
<fieldset class='pure-group'>
<input type='text' name='username' style='display: inline-block;' class='pure-input-1-2' placeholder='Username'><br>
</fieldset>
<fieldset class='pure-group'>
<input type='password' name='password' style='display: inline-block;' class='pure-input-1-2' placeholder='Password'><br>
</fieldset>
<fieldset class='pure-group'>
<button type='submit' style='display: inline-block;' class='pure-button pure-input-1-2 pure-button-primary'>Login</button>
</fieldset>
</form>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
}
function fetch($sql = false,$bind = false,$obj = false)
{
if(empty($sql))
return 0;
$query = Connect()->prepare($sql);
if(!$query)
return 0;
$query->execute($bind);
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
$row[] = $result;
}
if(!empty($row))
$row = ($obj)? (object) $row : $row;
else
$row = 0;
return $row;
}
function user_login($username = false, $password = false)
{
$st = fetch("SELECT username,password FROM users WHERE username = :username",array(":username"=>$username));
$valid = false;
if($st != 0) {
if($st[0]['password'] == $password) {
$_SESSION['username'] = $row[0]['username'];
$valid = true;
}
}
return $valid;
}
function user_logout($location = 'loggedout.php')
{
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'logout') {
session_destroy();
header("Location: ".$location);
exit;
}
}
// Include Database Config.
// If you just have $username,$password,$host,$dbname here,
// you can skip this if you just add those values into the Connect()
// function as default arguements
include('../cdn/global/db.php');
//Add static function that listens for logout
user_logout();
// If username set (password is also going to be set)
if(!empty($_POST['username']))
// Get true/false for user hit
echo (user_login($_POST['username'],$_POST['password']))? "Welcome ".htmlspecialchars($_SESSION['username']) : "Invalid username and/or password!";
// If there is no session username, show login form
echo (empty($_SESSION['username']))? LoginForm() : 'Log Out';
?>
EDIT: How I would do it in this scenario (in a general sense)
/functions/functions.php
<?php
function Connect($host = false,$username = false,$password = false,$dbname = false)
{
try {
//Create a PDO Session.
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password,array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ));
//Session Attributes.
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $e) {
echo "<code><pre>".print_r($e)."</pre></code>";
$con = false;
}
return $con;
}
// Since you are just assigning a variable some html, may as well make it a bit flexible in a function (just incase)
function LoginForm($settings = false)
{
$method = (!empty($settings['method']))? $settings['method']:"post";
$action = (!empty($settings['action']))? $settings['action']:"";
$id = (!empty($settings['id']))? ' id="'.$settings['id'].'"':"";
$class = (!empty($settings['class']))? $settings['class']:"pure-form";
ob_start();
?>
<form method='<?php echo $method; ?>' action='<?php echo $action; ?>' class='<?php echo $class; ?>' style='color: #000;'<?php echo $id; ?>>
<fieldset class='pure-group'>
<input type='text' name='username' style='display: inline-block;' class='pure-input-1-2' placeholder='Username'><br>
</fieldset>
<fieldset class='pure-group'>
<input type='password' name='password' style='display: inline-block;' class='pure-input-1-2' placeholder='Password'><br>
</fieldset>
<fieldset class='pure-group'>
<button type='submit' style='display: inline-block;' class='pure-button pure-input-1-2 pure-button-primary'>Login</button>
</fieldset>
</form>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
}
function fetch($sql = false,$bind = false,$obj = false)
{
if(empty($sql))
return 0;
$query = Connect()->prepare($sql);
if(!$query)
return 0;
$query->execute($bind);
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
$row[] = $result;
}
if(!empty($row))
$row = ($obj)? (object) $row : $row;
else
$row = 0;
return $row;
}
function user_login($username = false, $password = false)
{
$st = fetch("SELECT username,password FROM users WHERE username = :username",array(":username"=>$username));
$valid = false;
if($st != 0) {
if($st[0]['password'] == $password) {
$_SESSION['username'] = $row[0]['username'];
$valid = true;
}
}
return $valid;
}
function user_logout($location = 'loggedout.php')
{
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'logout') {
session_destroy();
header("Location: ".$location);
exit;
}
}
?>
login.php
session_start();
include_once(__DIR__.'/functions/functions.php');
user_logout();
?><html>
<head>
</head>
<body>
<?php
if(!empty($_POST['username']))
echo (user_login($_POST['username'],$_POST['password']))? "Welcome ".htmlspecialchars($_SESSION['username']) : "Invalid username and/or password!";
echo (empty($_SESSION['username']))? LoginForm() : 'Log Out';
?>
</body>
</html>
You can also create a class to manager your users. Let's create db.php class.
<?php
class Db {
private static $_dbase = 'data';
private static $_username = 'root';
private static $_passwd = '';
private static $_host = 'localhost';
private static $_options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
private static $_dsn;
private static $_db;
function __construct() {
}
public static function getDB() {
if (!isset(self::$_db)) {
try {
self::$_dsn = 'mysql:host=' . self::$_host . ';dbname=' . self::$_dbase;
self::$_db = new PDO(self::$_dsn, self::$_username, self::$_passwd, self::$_options);
} catch (PDOException $exc) {
echo $exc->getMessage();
}
}
return self::$_db;
}
}
And now let's create User.php class
<?php
session_start();
require_once 'db.php';
class USER {
private $db;
function __construct() {
$this->db = Db::getDb();
}
public function register($uname, $umail, $upass) {
try {
$new_password = password_hash($upass, PASSWORD_DEFAULT);
//create the activasion code
$activation = md5(uniqid(rand(), true));
$stmt = $this->db->prepare("INSERT INTO users(user_name,user_email,user_pass,active)
VALUES(:uname, :umail, :upass,:active)");
$stmt->bindparam(":uname", $uname);
$stmt->bindparam(":umail", $umail);
$stmt->bindparam(":upass", $new_password);
$stmt->bindparam(":active", $activation);
$stmt->execute();
$id = $this->db->lastInsertId('memberID');
$this->sendMail($id, $activation);
$this->redirect('sign-up.php?joined');
return $stmt;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
public function login($uname, $umail, $upass) {
try {
$stmt = $this->db->prepare("SELECT * FROM `users` WHERE `user_name` = :uname AND `user_email` = :umail LIMIT 1");
$stmt->execute(array(':uname' => $uname, ':umail' => $umail));
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if ($stmt->rowCount() > 0) {
//verifying user.
if (password_verify($upass, $userRow['user_pass']) && $userRow['active'] === 'Yes') {
$_SESSION['user_session'] = $userRow['user_id'];
return true;
} else {
return false;
}
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}
private function sendMail($email,$id, $activation) {
//send email to the user for account activation.
$to = $email;
$subject = "Registration Confirmation";
$body = "Thank you for registering at demo site.\n\n To activate your account, please click on this link:\n\n " . DIR . "activate.php?x=$id&y=$activation\n\n Regards Site Admin \n\n";
$additionalheaders = "From: <" . SITEEMAIL . ">\r\n";
$additionalheaders .= "Reply-To: " . SITEEMAIL . "";
mail($to, $subject, $body, $additionalheaders);
}
//check if the user is logged in
public function is_loggedin() {
if (isset($_SESSION['user_session'])) {
return true;
}
}
// redirect the user.
public function redirect($url) {
header("Location: $url");
}
//user log out
public function logout() {
session_destroy();
unset($_SESSION['user_session']);
return true;
}
//display login form
public function display_login_form() {
return "
<form method='POST' action='' class='pure-form' style='color: #000;'>
<fieldset class='pure-group'>
<input type='text' name='username' style='display: inline-block;' class='pure-input-1-2' placeholder='Username'><br>
</fieldset>
<fieldset class='pure-group'>
<input type='password' name='password' style='display: inline-block;' class='pure-input-1-2' placeholder='Password'><br>
</fieldset>
<fieldset class='pure-group'>
<button type='submit' style='display: inline-block;' class='pure-button pure-input-1-2 pure-button-primary'>Login</button>'
</fieldset>
</form>";
}
}
We are going to check if the user is logged in and if not display the login form.
<?php
require_once 'User.php';
$User = new User();
$form = '';
if($User->is_loggedin()){
$User->redirect('private.php');
}else{
$form = $User->display_login_form();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div><?php echo $form; ?></div>
</body>

Php registration error validation

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
}
}

Class not writing to database PDO

I have a class setup to write some data to a mysql database that doesn't seem to be actually writing the data. I believe the issue lies in the PDO statements somewhere. I double checked the query and the database connection on other scripts on the site and they work fine. Any ideas?
Here is my form:
<?php
$navsection = 'addClass';
$dir = $_SERVER['DOCUMENT_ROOT'] . "/grades/";
// load php-login components
require_once $dir . 'php-login.php';
$classes = new Classes();
// load head file
require_once $dir . 'includes/head.php';
?>
<h1>Add a Class</h1>
<?php
// show negative messages
if ($classes->errors) {
foreach ($classes->errors as $error) {
echo $error;
}
}
// show positive messages
if ($classes->messages) {
foreach ($classes->messages as $message) {
echo $message;
}
}
?>
<br />
<form method='post' action='<?php $siteurl; ?>/grades/pages/addClass.php' name='addClass_form'>
<label for='className'>Class Name:</label>
<input id='className' type='text' name='className' required /><br />
<label for='classProfessor'>Professor's Name:</label>
<input id='classProfessor' type='text' name='classProfessor' /><br />
<label for='classPeriod'>Class Period:</label>
<select id='classPeriod' name='classPeriod'>
<option value='Spring 2014'>Spring 2014</option>
<option value='Fall 2013'>Fall 2013</option>
</select><br />
<label for='classStartDate'>Class Start Date:</label>
<input id='classStartDate' type='date' name='classStartDate' /><br />
<label for='classEndDate'>Class End Date:</label>
<input id='classEndDate' type='date' name='classEndDate' /><br />
<input type='submit' name='addClass' value='Submit' />
</form>
<?php
//load footer file
require_once $dir . 'includes/footer.php';
?>
Here is my class:
<?php
class Classes
{
private $db_connection = null;
public $classAdd_successful = false;
public $classDelete_successful = false;
public $classEdit_successful = false;
public $errors = array();
public $messages = array();
public function __construct()
{
session_start();
if (isset($_POST["addClass"])) {
$this->addNewClass($_POST['className'], $_POST['classProfessor'], $_POST['classPeriod'], $_POST['classStartDate'], $_POST['classEndDate']);
}
}
private function databaseConnection()
{
if ($this->db_connection != null) {
return true;
} else {
try {
$this->db_connection = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
return true;
} catch (PDOException $e) {
$this->errors[] = "Database error";
return false;
}
}
}
private function addNewClass ($className, $classProfessor, $classPeriod, $classStart, $classEnd)
{
if(empty($className)) {
$this->errors[] = "Please enter a class name.";
} elseif(empty($classProfessor)) {
$this->errors[] = "Please enter a class professor.";
} elseif(empty($classPeriod)) {
$this->errors[] = "Please select a class period";
} elseif(empty($classStart)) {
$this->errors[] = "Please enter a class start date.";
} elseif(empty($classEnd)) {
$this->errors[] = "Please enter a class end date.";
}
if ($this->databaseConnection() == true) {
//Write data to database
$query_new_class_insert = $this->db_connection->prepare('INSERT INTO classes (class_name, user_id, professor_name, class_start, class_end, school_period) VALUES(:className, :userID, :professorName, :classStart, :classEnd, :schoolPeriod)');
$query_new_class_insert->bindvalue(':className', $className, PDO::PARAM_STR);
$query_new_class_insert->bindvalue(':userID', $_SESSION['user_id'], PDO::PARAM_INT);
$query_new_class_insert->bindvalue(':professorName', $classProfessor, PDO::PARAM_STR);
$query_new_class_insert->bindvalue(':classStart', $classStart, PDO::PARAM_STR);
$query_new_class_insert->bindvalue(':classEnd', $classEnd, PDO::PARAM_STR);
$query_new_class_insert->bindvalue(':schoolPeriod', $schoolPeriod, PDO::PARAM_STR);
$query_new_class_insert->execute();
$this->classAdd_successful = true;
} else {
$this->errors[] = "Database write error";
}
}
}
?>

Categories