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;
}
}
Related
I want get data from offers table ordered DESC by payout. If offer ID exist in offers_disabled_smart_link table, move to next and display link. What I'm doing wrong? I getting NULL when echo $link.
My DeliverService class is:
class DeliveryService {
protected $user_id;
protected $country;
protected $os;
protected $ip;
protected $referrer;
protected $token;
protected $smart_link;
public function __construct($user_id,$country,$ip,$os,$referrer,$token,$smart_link)
{
$this->user_id = $user_id;
$this->user_country = $country;
$this->user_ip = $ip;
$this->user_os = $os;
$this->user_referrer = $referrer;
$this->user_token = $token;
$this->smart_link_id = $smart_link;
}
public function getStatusOfferSmartLink($offer_id,$smart_link_id,$user_id)
{
global $db;
$sql="SELECT offer_id,smart_link_id,user_id FROM offers_disabled_smart_link WHERE smart_link_id=:smart_link_id AND offer_id=:offer_id and user_id=:user_id";
$stmp = $db->prepare($sql);
$stmp->execute(array(":smart_link_id"=>$smart_link_id,":offer_id"=>$offer_id,":user_id"=>$user_id));
$results = $stmp->fetchAll(PDO::FETCH_OBJ);
if($results)
return true;
else return false;
}
public function deliver()
{
global $db;
$sql="SELECT id, link, payout FROM offers ORDER BY payout DESC";
$stmp = $db->prepare($sql);
$stmp->execute();
while ($row = $stmp->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$link = $row['link'];
if($this->getStatusOfferSmartLink($id,$this->smart_link_id,$this->user_id)){
continue;
}
break;
$this->localFlag = true;
}
if ($this->localFlag) {
return $link;
}
}
Here I call function deliver() and echo $link
$ad = new DeliveryService(354,$country,$ip,$os,$referrer,$token,$smart_link);
$link = $ad->deliver();
echo $link;
If you want any informations, ask me.
Lets assume that your query return your expected data.
$this->localFlag = true; line will never execute as it's after break statement. (Assume that you didn't set $this->localFlag anywhere else.)
change this:
break;
$this->localFlag = true;
to:
$this->localFlag = true;
break;
and try. Hope it will work.
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;
}
}
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;
} }
I'm creating a class in which MySQL queries will be generated automatically , but I've some problem ...
here is my Database class...
<?php
class Database {
var $host="localhost";
var $username="";
Var $password="";
var $database="";
var $fr_query;
var $row= array() ;
public function connect()
{
$conn= mysql_connect($this->host,$this->username,$this->password);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
}
public function db()
{
$conn_db = mysql_select_db($this->database);
if(! $conn_db )
{
echo 'Could Not Connect the Database';
}
}
public function run_query($sql)
{
$run = mysql_query($sql);
if(!$run)
{
throw new Exception("!!!!!Invalid query!!!!!!!");
}
$newId = mysql_insert_id();
if($newId)
{
return $newId;
}
return true;
}
public function fetchRow($fr)
{
if($fr)
{
$run = mysql_query($fr);
if($run)
{
return mysql_fetch_assoc($run);
}
}
return null;
}
function fetchAll($fr_query)
{
if($fr_query)
{
$run = mysql_query($fr_query);
if($run)
{
$data=array();
while($row=mysql_fetch_assoc($run))
{
$data[]=$row;
}
return $data;
}
}
return null;
}
}
$n = new Database();
$n->connect();
$n->db();
?>
and this is my test.php
<?php
include("database.php");
class Model_Abstract
{
protected $_data = array();
protected $_tableName = null;
protected $_primaryKey = null;
public function getTableName()
{
return $this->_tableName;
}
public function getPrimaryKey()
{
return $this->_primaryKey;
}
public function __set($key, $value = NULL)
{
$key = trim($key);
if(!$key)
{
throw new Exception('"$key" should not be empty.');
}
$this->_data[$key] = $value;
return $this;
}
public function __get($key)
{
$key = trim($key);
if(!$key)
{
throw new Exception('"$key" should not be empty.');
}
if(array_key_exists($key, $this->_data))
{
return $this->_data[$key];
}
return NULL;
}
public function insert()
{
print_r($this->_data);
$keyString = "`".implode("`,`", array_keys($this->_data))."`";
$valueString = "'".implode("','", array_keys($this->_data))."'";
echo $query = "INSERT INTO `{$this->getTableName()}` ({$keyString}) VALUES ({$valueString})";
$this->adpater()->run_query($query);
echo 'Inserted';
}
public function setData($data)
{
if(!is_array($data))
{
throw new Exception('"$data" should not be empty.');
}
$this->_data = $data;
return $this;
}
public function load($id, $key = null)
{
if(!is_int($id) && $id)
{
throw new Exception('"$id" should not be blank.');
}
if($id)
{
echo $query = "SELECT * FROM `{$this->getTableName()}` WHERE `{$this->getPrimaryKey()}` = '{$id}'";
$data[] = $this->adpater()->fetchRow($query);
$tabelName = $this->getTableName();
foreach($data as &$_data)
{
print_r($_data);
$object = new $tabelName();
$object->setData($_data);
$_data = $object;
}
print_r($data);
return $this;
/*
$query = "SELECT * FROM `{$this->getTableName()}` WHERE `{$this->getPrimaryKey()}` = '{$id}'";
$this->_data = $this->adpater()->fetchRow($query);
return $this; */
}
}
public function loadAll()
{
$query = "SELECT * FROM `{$this->getTableName()}`";
$data[] = $this->adpater()->fetchAll($query);
return $data;
}
public function delete($id, $key = null)
{
if(!is_int($id) && $id)
{
throw new Exception('"$id" should not be blank.');
}
if($id)
{
echo $query = "DELETE FROM `{$this->getTableName()}` WHERE `{$this->getPrimaryKey()}` = '{$id}'";
$data[] = $this->adpater()->run_query($query);
$tabelName = $this->getTableName();
$msg = 'Deleted Successfully....';
return $msg;
}
}
public function update()
{
print_r($this->_data);
$keyString = "`".implode("`,`", array_keys($this->_data))."`";
$valueString = "'".implode("','", array_keys($this->_data))."'";
echo $query = "UPDATE`{$this->getTableName()}` SET ({$keyString}) = ({$valueString}) WHERE `{$this->getPrimaryKey()}` = '{$id}'";
$this->adpater()->run_query($query);
echo 'Updated';
}
public function adpater()
{
return new Database();
}
}
class Product extends Model_Abstract
{
protected $_tableName = 'product';
protected $_primaryKey = 'product_id';
}
$product = new Product();
echo $product->name;
$product->insert();
print_r($product);
$product = new Product();
$product->name = 'Nokia Lumia';
$product->description = 'Windows';
$product->price = '15000';
$product->quantity = '12';
$product->sku = 'x2';
$product->status = '2';
$product->created_date = '0000-00-00 00:00:00';
$product->updated_date = ' ';
?>
So in here my problem is in Insert query, the values are same the column_name ...
I'm having Problem in loadAll();
the browser says "Catchable fatal error: Object of class Product could not be converted to string in"
$keyString = "`".implode("`,`", array_keys($this->_data))."`";
$valueString = "'".implode("','", array_keys($this->_data))."'";
Same lines, same value. Perhaps you meant
$keyString = "`".implode("`,`", array_keys($this->_data))."`";
$valueString = "'".implode("','", $this->_data) ."'";
Which would take the array keys for $keyString and the array values for $valueString.
Depreciation warning
mysql_* are deprecated functions. Use mysqli_* or PDO
Warning
This class does not protect you against SQL injections.
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.