is isset($_SESSION['admin']) a dangerous way to grant access? - php

If (for argument sake) 'admin-access' was granted in php with:
if (isset($_SESSION['admin'])) // this session would be set
{ // grant access; } // after a successful login
else { //redirect ;}
Would this be a particularly easy thing to bypass and fake, if you knew what the name of the session is (in this case it is admin)?
In other words, can someone easily fake a $_SESSION, if all a script calls for is the session to be 'set'?

Using isset() is not bad for security. It depends on your logic that how you use it. It will be good if you not only check isset() but also its value.
For Example:
if( isset($_SESSION['admin']) && $_SESSION['admin'] == true ) {
// grant access
} else {
//redirect
}
Or something like this:
if( isset($_SESSION['admin']) && $_SESSION['admin'] == '1' ) {
// grant access
} else {
//redirect
}

i prefer a more secure way, like this class i used in my old applications :
class auth {
protected $userID;
protected $password;
protected $username;
protected $remember;
protected $userType;
public function checkAuth($username,$password,$remember=0) {
global $db;
$this->password = sha1($password);
$this->username = strtolower($username);
$this->remember = $remember;
$sth = $db->prepare("SELECT `id`,`username`,`password`,`type` FROM `user` WHERE `username` = :username AND `active` = '1' LIMIT 1");
$sth->execute(array(
':username' => $this->username
));
$result = $sth->fetchAll();
$this->userType = $result[0]['type'];
if (#$result[0]['password'] == $this->password) {
$this->userID = $result[0]['id'];
$this->makeLogin();
return true;
} else {
return false;
exit;
}
}
private function makeLogin() {
$securityInformation = $this->username . '|-|' . $this->password . '|-|' . $this->userID . '|-|' . $this->userType;
$hash = $this->encode($securityInformation);
if ($this->remember) {
setcookie('qdata',$hash,time()+604800,'/');
} else {
$_SESSION['qdata'] = $hash;
}
$this->updateStats();
}
public function isLogin() {
global $db, $ua, $cache;
$data = $this->getUserInfo();
if ($data) {
$sth = $db->prepare('SELECT `password`,`last_login_ip` FROM `user` WHERE `id` = :ID LIMIT 1');
$sth->execute(array(
':ID' => $data['userID']
));
$result = $sth->fetchAll();
if ( ($result[0]['password'] == $data['password']) AND ($result[0]['last_login_ip'] == $ua->getIP()) ) {
return true;
} else {
return false;
}
}
}
public function logout() {
if (#isset($_COOKIE['qdata'])) {
setcookie('qdata','',time()-200, '/');
}
if (#isset($_SESSION['qdata'])) {
unset($_SESSION['qdata']);
}
}
private function parseHash($hash) {
$userData = array();
list($userData['username'],$userData['password'],$userData['userID'],$userData['userType']) = explode('|-|',$this->decode($hash));
return $userData;
}
public function getUserInfo() {
if (#isset($_COOKIE['qdata'])) {
$data = $this->parseHash($_COOKIE['qdata']);
return $data;
} elseif (#isset($_SESSION['qdata'])) {
$data = $this->parseHash($_SESSION['qdata']);
return $data;
} else {
return false;
}
}
private function encode($str) {
$chr = '';
$prt = '';
for($i=0;$i < strlen($str);$i++) {
$prt = (chr(ord(substr($str,$i,1)) + 3)) . chr(ord(substr($str,$i,1)) + 2);
$chr = $prt . $chr;
}
return str_rot13($chr);
}
private function decode($str) {
$chr = '';
$prt = '';
$str = str_rot13($str);
for($i=0;$i < strlen($str);$i++) {
if($i % 2 == 0) {
$prt = (chr(ord(substr($str,$i,1)) - 3));
$chr = $prt . $chr;
}
}
return $chr;
}
}
if you dont like this approach, at least store a special key in admin table and use session with that key in value, also check login is validated every time a page loaded.

Related

Login with roles

I am trying to give access to a user according to their role, I have 2 type one Administrator with id 1 and Client with id 2, so far the valid username and password. so the Client can enter the administrative part, and I want him to only have access to the Client's view
This is my function verify of the model:
public function Verify($usuario, $contrasena) {
try {
$sql = "SELECT * FROM usuarios WHERE usuario = ? AND contrasena = ?" ;
$stm = $this->pdo->prepare($sql);
$stm->execute(array($usuario, $contrasena));
$UsuarioDatos = $stm->fetch(PDO::FETCH_OBJ);
if ($UsuarioDatos == NULL) {
return FALSE;
} else {
return TRUE;
}
} catch (Exception $ex) {
die($ex->getMessage());
}
}
And this is my login.controller:
public function Authenticate() {
$usuario = $_REQUEST['usuario'];
$contrasena = ($_REQUEST[('contrasena')]);
$validar = $this->model->Verify($usuario, $contrasena);
if ($validar) {
$_SESSION['usuario']=$usuario;
$_SESSION['idCategoriaUsu']=$validar['idCategoriaUsu'];
$_SESSION['Iniciada']='true';
if($_SESSION['idCategoriaUsu'] == 1){
header('Location:index.php?c=Home');
}
else {
header('Location:index.php?c=ClienteNormal');
}
} else {
header('Location: index.php?c=Login&error=true');
}
}
Is going directly to this:
else {
header('Location:index.php?c=ClienteNormal');
}
your function "Verify" returns a boolean.
Except here:
$_SESSION['idCategoriaUsu']=$validar['idCategoriaUsu']
you try to access a array.
Quentin Geenens answer is correct,
modify your Verify function:
public function Verify($usuario, $contrasena) {
try {
$sql = "SELECT * FROM usuarios WHERE usuario = ? AND contrasena = ?";
$stm = $this->pdo->prepare($sql);
$stm->execute(array($usuario, $contrasena));
$UsuarioDatos = $stm->fetch(PDO::FETCH_OBJ);
if ($UsuarioDatos == NULL) {
return FALSE;
} else {
return TRUE;
}
} catch (Exception $ex) {
die($ex->getMessage());
}
}
to this:
public function Verify($usuario, $contrasena) {
try {
$sql = "SELECT * FROM usuarios WHERE usuario = ? AND contrasena = ?";
$stm = $this->pdo->prepare($sql);
$stm->execute(array($usuario, $contrasena));
$UsuarioDatos = $stm->fetch(PDO::FETCH_OBJ);
if ($UsuarioDatos == NULL) {
return FALSE;
} else {
return $UsuarioDatos;
}
} catch (Exception $ex) {
die($ex->getMessage());
}
}
if $UsuarioDatos is not NULL it returns the query result.
then modify your Authenticate function:
public function Authenticate() {
$usuario = $_REQUEST['usuario'];
$contrasena = ($_REQUEST[('contrasena')]);
$validar = $this->model->Verify($usuario, $contrasena);
if ($validar) {
$_SESSION['usuario']=$usuario;
$_SESSION['idCategoriaUsu']=$validar['idCategoriaUsu'];
$_SESSION['Iniciada']='true';
if($_SESSION['idCategoriaUsu'] == 1){
header('Location:index.php?c=Home');
}
else {
header('Location:index.php?c=ClienteNormal');
}
} else {
header('Location: index.php?c=Login&error=true');
}
}
to this:
public function Authenticate() {
$usuario = $_REQUEST['usuario'];
$contrasena = ($_REQUEST[('contrasena')]);
$validar = $this->model->Verify($usuario, $contrasena);
if ($validar === FALSE) {
header('Location: index.php?c=Login&error=true');
} else {
$_SESSION['usuario'] = $usuario;
$_SESSION['idCategoriaUsu'] = $validar['idCategoriaUsu'];
$_SESSION['Iniciada']='true';
if($_SESSION['idCategoriaUsu'] == 1){
header('Location:index.php?c=Home');
}
else {
header('Location:index.php?c=ClienteNormal');
}
}
}
I hope this answer helps you

Unable to get data from session after browser restart in php

Am using following lib to manage session, Am storing session values in database, everything works great i can get and set session values.
But after restart i can't get session values.
When i try to set session values i creates new row in database instead of updating.
LIB.php
<?php
/**
* #category Security
* #version 1.0
* #author First Last
* */
class mySessionHandler {
private $_db = NULL;
private $_table_name = 'sessions';
private $_cookie_name = 'session_cookie';
private $_seconds_till_expiration = 43200; // 2 hours
private $_renewal_time = 300; // 5 minutes
private $_expire_on_close = FALSE;
private $_ip_address = FALSE;
private $_user_agent = FALSE;
private $_secure_cookie = FALSE;
private $_session_id = FALSE;
private $_data = array();
public function __construct(array $config) {
$this->_setConfig($config);
if ($this->_read()) {
$this->_update();
} else {
$this->_create();
}
$this->_cleanExpired();
$this->_setCookie();
}
public function regenerateId() {
$old_session_id = $this->_session_id;
$this->_session_id = $this->_generateId();
$stmt = $this->_db->prepare("UPDATE {$this->_table_name} SET time_updated = ?, session_id = ? WHERE session_id = ?");
$stmt->execute(array(time(), $this->_session_id, $old_session_id));
$this->_setCookie();
}
public function setData($key, $value) {
$this->_data[$key] = $value;
$this->_write();
}
public function unsetData($key) {
if (isset($this->_data[$key])) {
unset($this->_data[$key]);
}
}
function getData($key) {
return isset($this->_data[$key]) ? $this->_data[$key] : FALSE;
}
public function getAllData() {
return $this->_data;
}
public function destroy() {
if (isset($this->_session_id)) {
$stmt = $this->_db->prepare("DELETE FROM {$this->_table_name} WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
}
setcookie($this->_cookie_name, '', time() - 31500000, NULL, NULL, NULL, NULL);
}
private function _read() {
$session_id = filter_input(INPUT_COOKIE, $this->_cookie_name) ? filter_input(INPUT_COOKIE, $this->_cookie_name) : FALSE;
if (!$session_id) {
return FALSE;
}
$this->_session_id = $session_id;
$stmt = $this->_db->prepare("SELECT data, time_updated, user_agent, ip_address FROM {$this->_table_name} WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result !== FALSE && count($result) > 0) {
if (!$this->_expire_on_close && (($result['time_updated'] + $this->_seconds_till_expiration) < time())) {
$this->destroy();
return FALSE;
}
if ($this->_ip_address && ($result['ip_address'] != $this->_ip_address)) {
$this->_flagForUpdate();
return FALSE;
}
if ($this->_user_agent && ($result['user_agent'] != $this->_user_agent)) {
$this->_flagForUpdate();
return FALSE;
}
$this->_checkUpdateFlag();
$this->_checkIdRenewal();
$user_data = unserialize($result['data']);
if ($user_data) {
$this->_data = $user_data;
unset($user_data);
}return TRUE;
}return FALSE;
}
private function _create() {
$this->_session_id = $this->_generateId();
$stmt = $this->_db->prepare("INSERT INTO {$this->_table_name} (session_id, user_agent, ip_address, time_updated) VALUES (?, ?, ?, ?)");
$stmt->execute(array($this->_session_id, $this->_user_agent, $this->_ip_address, time()));
}
private function _update() {
$stmt = $this->_db->prepare("UPDATE {$this->_table_name} SET time_updated = ? WHERE session_id = ?");
$stmt->execute(array(time(), $this->_session_id));
}
private function _write() {
if (count($this->_data) == 0) {
$custom_data = '';
} else {
$custom_data = serialize($this->_data);
}
$stmt = $this->_db->prepare("UPDATE {$this->_table_name} SET data = ?, time_updated = ? WHERE session_id = ?");
$stmt->execute(array($custom_data, time(), $this->_session_id));
}
private function _setCookie() {
setcookie(
$this->_cookie_name, $this->_session_id, ($this->_expire_on_close) ? 0 : time() + $this->_seconds_till_expiration, // Expiration timestamp
NULL, NULL, $this->_secure_cookie, // Will cookie be set without HTTPS?
TRUE // HttpOnly
);
}
private function _cleanExpired() {
if (mt_rand(1, 1000) == 1) {
$stmt = $this->_db->prepare("DELETE FROM {$this->_table_name} WHERE (time_updated + {$this->_seconds_till_expiration}) < ?");
$stmt->execute(array(time()));
}
}
function _generateId() {
$salt = 'x7^!bo3p,.$$!$6[&Q.#,//#i"%[X';
$random_number = '9085723012206';
$random_txt = 'sanoj';
$ip_address_fragment = md5(substr(filter_input(INPUT_SERVER, 'REMOTE_ADDR'), 0, 5));
$hash_data = $random_number . $ip_address_fragment . $random_txt . $salt;
$hash = hash('sha256', $hash_data);
return $hash;
}
private function _checkIdRenewal() {
$stmt = $this->_db->prepare("SELECT time_updated FROM {$this->_table_name} WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result !== FALSE && count($result) > 0) {
if ((time() - $this->_renewal_time) > $result['time_updated']) {
$this->regenerateId();
}
}
}
private function _flagForUpdate() {
$stmt = $this->_db->prepare("UPDATE {$this->_table_name} SET flagged_for_update = '1' WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
}
private function _checkUpdateFlag() {
$stmt = $this->_db->prepare("SELECT flagged_for_update FROM {$this->_table_name} WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result !== FALSE && count($result) > 0) {
if ($result['flagged_for_update']) {
$this->regenerateId();
$stmt = $this->_db->prepare("UPDATE {$this->_table_name} SET flagged_for_update = '0' WHERE session_id = ?");
$stmt->execute(array($this->_session_id));
}
}
}
private function _setConfig(array $config) {
if (isset($config['database'])) {
$this->_db = $config['database'];
} else {
throw new Exception('Database handle not set!');
}
if (isset($config['cookie_name'])) {
if (!ctype_alnum(str_replace(array('-', '_'), '', $config['cookie_name']))) {
throw new Exception('Invalid cookie name!');
} $this->_cookie_name = $config['cookie_name'];
}
if (isset($config['table_name'])) {
if (!ctype_alnum(str_replace(array('-', '_'), '', $config['table_name']))) {
throw new Exception('Invalid table name!');
} $this->_table_name = $config['table_name'];
}
if (isset($config['seconds_till_expiration'])) {
if (!is_int($config['seconds_till_expiration']) || !preg_match('#[0-9]#', $config['seconds_till_expiration'])) {
throw new Exception('Seconds till expiration must be a valid number.');
}
if ($config['seconds_till_expiration'] < 1) {
throw new Exception('Seconds till expiration can not be zero or less. Enable session expiration when the browser closes instead.');
}
$this->_seconds_till_expiration = (int) $config['seconds_till_expiration'];
}
if (isset($config['expire_on_close'])) {
if (!is_bool($config['expire_on_close'])) {
throw new Exception('Expire on close must be either TRUE or FALSE.');
}
$this->_expire_on_close = $config['expire_on_close'];
}
if (isset($config['renewal_time'])) {
if (!is_int($config['renewal_time']) || !preg_match('#[0-9]#', $config['renewal_time'])) {
throw new Exception('Session renewal time must be a valid number.');
}
if ($config['renewal_time'] < 1) {
throw new Exception('Session renewal time can not be zero or less.');
}
$this->_renewal_time = (int) $config['renewal_time'];
}
if (isset($config['check_ip_address'])) {
if (!is_string($config['check_ip_address'])) {
throw new Exception('The IP address must be a string similar to this: \'172.16.254.1\'.');
}
if (!preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/', $config['check_ip_address'])) {
throw new Exception('Invalid IP address.');
}
$this->_ip_address = $config['check_ip_address'];
}
if (isset($config['check_user_agent'])) {
$this->_user_agent = substr($config['check_user_agent'], 0, 999);
} if (isset($config['secure_cookie'])) {
if (!is_bool($config['secure_cookie'])) {
throw new Exception('The secure cookie option must be either TRUE or FALSE.');
}
$this->_secure_cookie = $config['secure_cookie'];
}
}
}
How do i get session values even after restarting browser,
GET.PHP
ob_start();
session_start();
include_once('index.php');
echo $session->getData('fname').'<br>';
echo $session->getData('password').'<br>';
echo $session->getData('email').'<br>';
SET.PHP
ob_start();
session_start();
include_once('index.php');
$session->setData('fname', 'first last');
$session->setData('password', '123456');
$session->setData('email', 'first#last.com');
$sesi = $session->_generateId();
echo $sesi;
$_SESSION['test'] = $sesi;
try replacing _setCookie() so that your cookie won't expire
private function _setCookie() {
setcookie($this->_cookie_name, $this->_session_id, ($this->_expire_on_close) ? 0 : time() + (10 * 365 * 24 * 60 * 60), //Expiration timestamp
NULL, NULL, $this->_secure_cookie, // Will cookie be set without HTTPS?
TRUE // HttpOnly
);
}

Need help on a PHP website logic

I am creating a contest website on my localhost using PHP. The project works as follows:
The user can log in and is directed to a page level.php?n=getUserData()['level'] , the logic is that if the user submits the right answer the user is redirected to the next level and the level field in the database must be updated so that the user can redirected to the next level level.php?n=2 and so on...., during login the users credentials are being stored in a session variable.(user_id,level,email ..etc).
My login controller:
include 'core/init.php';
$id = isset($_GET['n']) ? $_GET['n'] : null;
$validate = new Validator;
$template = new Template("templates/question.php");
$template->title = $validate->getQuestion($id)->body;
//$template->answer = $validate->getQuestion($id)->answer;
$userid = getUserData()['user_id'];
if(isset($_POST['submit']))
{
// echo getUserData()['level']; die();
$data = array();
$data['answer'] = $_POST['answer'];
$required_fields = array("answer");
if($validate->isRequired($required_fields))
{
if($validate->check_answer($_POST['answer']))
{
if($validate->update_level($userid))
{
redirect("level.php?n=".getUserData()['level'],"Correct Anwser","success");
}
}
else
{
redirect("level.php?n=".getUserData()['level'],"Incorrect","error");
}
}
else
{
redirect("level.php?n=".getUserData()['level'],"Empty","error");
}
}
echo $template;
?>
`
My Validation class:
<?php
class Validator
{
private $db;
public function __construct()
{
$this->db = new Database;
}
public function isrequired($field_array)
{
foreach($field_array as $field)
{
if(empty($_POST[''.$field.'']))
{
return false;
}
}
return true;
}
public function login($username,$password)
{
$this->db->query("SELECT * FROM users WHERE username=:username AND password=:password");
$this->db->bind(":username",$username);
$this->db->bind(":password",$password);
$result = $this->db->single();
$row = $this->db->rowCount();
if($row>0)
{
$this->getData($result);
return true;
}
else
{
return false;
}
}
public function getData($row)
{
$_SESSION['is_logged_in'] = true;
$_SESSION['user_id'] = $row->id;
$_SESSION['username'] = $row->username;
$_SESSION['email'] = $row->email;
$_SESSION['level'] = $row->level;
}
public function getQuestion($id)
{
$this->db->query("SELECT * FROM question WHERE question_id = :id");
$this->db->bind(":id",$id);
$result = $this->db->single();
return $result;
}
public function logout()
{
unset($_SESSION['is_logged_in']);
unset($_SESSION['username']);
unset($_SESSION['user_id']);
unset($_SESSION['email']);
return true;
}
public function update_level($id)
{
$level = getUserData()['level']+1;
$this->db->query("UPDATE users SET level = :level WHERE id = :id");
$this->db->bind(":level",$level);
$this->db->bind(":id",getUserData()['user_id']);
$this->db->execute();
return true;
}
function check_answer($answer)
{
$this->db->query("SELECT * FROM question WHERE correct = :answer");
$this->db->bind(":answer",$answer);
$row = $this->db->single();
return $row;
}
}
?>
The getUserData() function:
function getUserData()
{
$userarray = array();
$userarray['username'] = $_SESSION['username'];
$userarray['user_id'] = $_SESSION['user_id'];
$userarray['email'] = $_SESSION['email'];
$userarray['level'] = $_SESSION['level'];
return $userarray;
}
I believe your problem is in your update portion when the user gets the answer correct. You need to update your session. I suggest you rework your script to convert the getUserData() into a User class or similar:
include('core/init.php');
$id = (isset($_GET['n']))? $_GET['n'] : null;
$validate = new Validator;
$template = new Template("templates/question.php");
# Create User class
$User = new User();
# Create make sure you set the files to internal array
$User->init();
# Start template
$template->title = $validate->getQuestion($id)->body;
# Fetch the id here
$userid = $User->getUserId();
# Check post
if(isset($_POST['submit'])) {
$data = array();
$data['answer'] = $_POST['answer'];
$required_fields = array("answer");
if($validate->isRequired($required_fields)) {
if($validate->check_answer($_POST['answer'])) {
# Update the database
if($validate->update_level($userid)) {
# Increment the init() here to push the level up
redirect("level.php?n=".$User->init(1)->getLevel(),"Correct Anwser","success");
}
}
else {
# Since you are not updating, don't need the init() here
redirect("level.php?n=".$User->getLevel(),"Incorrect","error");
}
}
else {
# Since you are not updating, don't need the init() here
redirect("level.php?n=".$User->getLevel(),"Empty","error");
}
}
echo $template;
Create a user class
User Class
<?php
class User
{
private $userData;
public function init($increment = 0)
{
# Get the current level
$level = $_SESSION['level'];
# If there is an increment
if($increment > 0) {
# Increment the level
$level += $increment;
# !!!***Re-assign the session***!!!
$_SESSION['level'] = $level;
}
# Save the internal array
$userarray['username'] = $_SESSION['username'];
$userarray['user_id'] = $_SESSION['user_id'];
$userarray['email'] = $_SESSION['email'];
# Level will be set by variable now
$userarray['level'] = $level;
# Save to array
$this->userData = (object) $userarray;
# Return object for chaining
return $this;
}
# This will call data from your internal array dynamically
public function __call($name,$args=false)
{
# Strip off the "get" from the method
$name = preg_replace('/^get/','',$name);
# Split method name by upper case
$getMethod = preg_split('/(?=[A-Z])/', $name, -1, PREG_SPLIT_NO_EMPTY);
# Create a variable from that split
$getKey = strtolower(implode('_',$getMethod));
# Checks if there is a key with this split name
if(isset($this->userData->{$getKey}))
$getDataSet = $this->userData->{$getKey};
# Checks if there is a key with the raw name (no get though)
elseif(isset($this->userData->{$name}))
$getDataSet = $this->userData->{$name};
# Returns value or bool/false
return (isset($getDataSet))? $getDataSet : false;
}
}

Return fetch_object from self class PHP

I'm trying to do a login class what checks if all fields are correct, and if is it then proccess.
My code: (login.php)
<?php
require('sql.php');
class login {
private $user;
private $email;
private $doc;
private $password;
function login($field, $pass){
$user = $field;
$email = $field;
$doc = strtoupper($field);
$password = $pass;
$this->getUser($user, $password, $r) ? $r : $this->getEmail($email, $password, $r) ? $r : $this->getDoc($doc, $password, $r) ? $r : null;
}
private function getUser($u, $p, &$r){
global $sql;
$count = 0;
$check = $sql->query("SELECT ... ");
while($row = $check->fetch_object()){
$count++;
$r = $row;
}
$count == 1 ? true : false;
}
private function getEmail($e, $p, &$r){ same as getUser()... }
private function getDoc($d, $p, &$r){ same as getUser()... }
}
?>
Now in Index (index.php)
<html>
ALL HTML STUFF WITH THE FORM
</html>
<?php
require('login.php');
if(isset($_POST['submit'])){
$login = new login(trim($sql->real_escape_string($_POST['user'])), md5(trim($sql->real_escape_string($_POST['pass']))));
if($login != null){
echo "SUCCESSFUL: ".$login->user;
}else{
echo "INCORRECT PASSWORD";
}
}
?>
The idea is get $login values like $login->user. But show me an error...
How can I do this? Where is my mistake?
This give you error because of private $user;
Make it public $user; because private member are not allowed to access from outside
or you can do some like following
public function getUsername(){
return $this->username;
}
and access it via echo $Obj->getusername();
Ok, thanks everyone but i solve the problem!!
in the constructor of login i put one value more.
public function login($field, $pass, &$r)
then in index.php
$login = new login(//user, //pass, $r);
echo "SUCCESSFUL: ".$r->user;
This return me the value from SQL query. This is what i was looking for.
Thanks again.
I m not saying all of this is working. Is just to get an idea of what i mean.
What you want is to get user informations.
For that you have created a class login.
Why dont you just create a User class where you retrieve and store your informations.
If constructor get an error. Just return null.
class User {
private $user;
private $email;
private $doc;
private $password;
private $detail1;
private $detail2;
private $detail3;
private $detail4;
public function __constructfunction login($field, $pass){
$user = $field;
$email = $field;
$doc = strtoupper($field);
$password = $pass;
$error = false;
//Detail for User
$count = 0;
$check = $sql->query("SELECT ... WHERE username='.$this->user.' AND pass = '.$this->password.'");
while($row = $check->fetch_object()){
$count++;
$r = $row;
}
if($count == 1)
{
$this->detail1 = $row['detail1'];
$this->detail2 = $row['detail2'];
}
else
{
$error = true;
}
//Detail for Doc
$count = 0;
$check = $sql->query("SELECT ... WHERE username='.$this->user.' AND pass = '.$this->password.'");
while($row = $check->fetch_object()){
$count++;
$r = $row;
}
if($count == 1)
{
$this->detail3 = $row['detail3'];
$this->detail4 = $row['detail4'];
}
else
{
$error = true;
}
if(true === $error)
return null;
}
public function getUser(){
return $this->user;
}
public function getEmail(){
return $this->doc;
}
public function getDoc(){
return $this->doc;
}
//Maybe not usefull
public function getPassword(){
return $this->password;
}
}

PDO mysql Update error

I seem to have an error I don't really understand. The process works fine, the connection to database is fine, but for some reason it doesn't update. There are no visible errors for me, or that php recognizes. Here is the code: (note that the last missing) on class I know about, and that happened when I copy pasted it, it's fine in the code
public function change_password($user, $pass) {
if($user) {
$password = md5($pass);
$this->_query = $this->_pdo->prepare("UPDATE users SET password = ? WHERE ? = ?");
if($this->_query->execute(array($pass, Check::data($user), $user))) {
return true;
}
}
return false;
}
class Check {
public static function data($data) {
if($data) {
if(is_numeric($data)) {
$_id = 'id';
} else if(filter_var($data, FILTER_VALIDATE_EMAIL)) {
$_id = 'email';
} else {
$_id = 'username';
}
return $_id;
}
return false;
}
}
If anyone is intressed, I resolved the problem, and for future simular problems , I found a way around..
public function change_password($user, $pass) {
if($user) {
$pass = md5($pass);
$id = $this->id($user);
$this->_query = $this->_pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
if($this->_query->execute(array($pass, $id))) {
return true;
}
}
return false;
}
public function id($user) {
if($user) {
$params = $this->fetch($user);
foreach($params as $param) {
if($param['id']) {
return $param['id'];
}
}
}
return false;
}
public function fetch($user) {
if($user) {
if(Check::data($user) === 'id') {
$this->_query = $this->_pdo->prepare("SELECT * FROM users WHERE id = :user");
}
if(Check::data($user) === 'email') {
$this->_query = $this->_pdo->prepare("SELECT * FROM users WHERE email = :user");
}
if(Check::data($user) === 'username') {
$this->_query = $this->_pdo->prepare("SELECT * FROM users WHERE username = :user");
}
$this->_query->execute(array(':user' => $user));
return $this->_query->fetchAll();
}
return false;
}`class Check {
public static function data($data) {
if($data) {
if(is_numeric($data)) {
$_id = 'id';
} else if(filter_var($data, FILTER_VALIDATE_EMAIL)) {
$_id = 'email';
} else {
$_id = 'username';
}
return $_id;
}
return false;
} }

Categories