Getting class variable errors in PHP - php

I got errors saying my email var is empty, besides that I have problems with the regex, which seems to be range out of order in character class, I guess it is some stupid mistake, for that I have much to learn
<?php
include_once('../resources/config.php');
class register
{
private $username;
private $password;
private $passmd5;
private $email;
private $errors;
private $token;
private $db;
public function __construct()
{
$this->db = new config();
$this->db = $this->db->dbConnect();
$this->errors = array();
$this->username = $this->regex($_POST['user']);
$this->password = $this->regex($_POST['pass']);
$this->email = $this->regex($_POST['email']);
$this->token = $this->regex($_POST['token']);
$this->passmd5 = md5($this->password);
}
public function process()
{
if($this->valid_token() && $this->valid_data())
$this->register();
}
public function regex($var)
{
$reggie = preg_replace('/[^a-zA-ZO-90.]/','',$var);
return $reggie;
}
public function register()
{
$this->db->prepare("insert into users(name, pass) values ('($this->username)','($this->passmd5)')");
if(rowCount() < 1)
$this->errors() == "form has failed you";
}
public function show_errors()
{
foreach ($this->errors as $key => $value) {
echo $value."</br>";
}
}
public function valid_data()
{
if(empty($this->username))
$this->errors() == 'invalid username';
if(empty($this->password))
$this->errors() == 'invalid password';
if(empty($this->email) || !ereg('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\#[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $this->email))
$this->errors() == 'invalid email';
return count ($this->errors)? 0:1;
}
public function valid_token()
{
}
}
?>
$obj_reg = new register();
if($obj_reg->process())
{
echo 'succes';
}else
{
$obj_reg->show_errors();
}
}
$token = $_SESSION['token'] = md5(uniqid(mt_rand(), true));
?>
<form method="post" action="index.php?page=register.php" >
<table>
<tr><td>username:</td><td> <input type="text" name="user"/></td></tr>
<tr><td>password:</td><td> <input type="password" name="pass"/></td></tr>
<tr><td>email:</td><td> <input type="text" name="email"/></td></tr>
</table>
<input type="hidden" name="token" value="<?=$token;?>"/>
<input type="submit" name="register" value="register"/>
</form>

For the email regex you should replace:
if(empty($this->email) || !ereg('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\#[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $this->email))
$this->errors() == 'invalid email';
With:
if (!filter_var($this->email, FILTER_VALIDATE_EMAIL))
$this->errors() == 'invalid email';

Use
$this->errors[] = "invalid foo";
instead of
$this->errors() == "invalid foo";

<?php
require_once('../resources/config.php');
class register
{
private $username;
private $password;
private $passmd5;
private $errors;
public function process()
{
if($this->valid_data())
{
$this->send();
}
else
{
echo "mama";
}
}
public function regex($var)
{
$reggie = preg_replace('/[^A-Za-z0-9:.\/_-]/','',$var);
return $reggie;
}
public function send()
{
mysql_query("INSERT INTO 'users' WHERE name='.$this->username.' pass='.$this->password.'");
}
public function checking($name, $pass)
{
$this->errors = array();
$this->username = $this->regex($name);
$this->password = $this->regex($pass);
$this->passmd5 = md5($this->password);
}
public function show_errors()
{
foreach ($this->errors as $key => $value) {
echo $value."</br>";
}
}
public function valid_data()
{
if(empty($this->username))
$this->errors[] = 'invalid username';
if(empty($this->password))
$this->errors[] = 'invalid password';
return count ($this->errors);
}
}
?>

Related

How to display a logged in user name in my oop php project?

When I try to display a username from my logged in user in my project, I get this error Undefined variable: user_id in C:\xampp\htdocs\login1\index.php on line 2
Query Failed!!!You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1 . Here is my code:
index.php:
<?php require_once("includes/header.php"); ?>
<?php $user = User::find_user_by_id($user_id); ?>
<?php
if (!$session->is_signed_in()) {
redirect("login.php");
}
?>
<div class="row">
<div class="col-md-12">
<h1>Home</h1>
<h1>Hello, <?php echo $user->username; ?></h1>
</div>
<?php require_once("includes/footer.php"); ?>
user.php:
class User
{
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
private function has_the_attribute($the_attribute)
{
$object_properties = get_object_vars($this);
return array_key_exists($the_attribute, $object_properties);
}
public static function instantation($the_record)
{
$the_object = new self;
foreach ($the_record as $the_attribute => $value) {
if ($the_object->has_the_attribute($the_attribute)) {
$the_object->$the_attribute = $value;
}
}
return $the_object;
}
public static function find_this_query($sql)
{
global $database;
$result_set = $database->query($sql);
$the_object_array = [];
while ($row = mysqli_fetch_array($result_set)) {
$the_object_array[] = self::instantation($row);
}
return $the_object_array;
}
public static function find_all_users()
{
return self::find_this_query("SELECT * FROM users");
}
public static function find_user_by_id($user_id)
{
global $database;
$the_result_array = self::find_this_query("SELECT * FROM users WHERE id=$user_id");
return !empty($the_result_array) ? array_shift($the_result_array) : false;
}
public static function verify_user($username, $password)
{
global $database;
$username = $database->escape_string($username);
$password = $database->escape_string($password);
$sql = "SELECT * FROM users WHERE ";
$sql .= "username = '{$username}' ";
$sql .= "AND password = '{$password}'";
$the_result_array = self::find_this_query($sql);
return !empty($the_result_array) ? array_shift($the_result_array) : false;
}
}
$user = new User();
session.php:
<?php
class Session
{
private $signed_in = false;
public $user_id;
public $message;
public function __construct()
{
session_start();
$this->check_the_login();
$this->check_message();
}
public function login($user)
{
if ($user) {
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->signed_in = true;
}
}
public function logout()
{
unset($_SESSION['user_id']);
unset($this->user_id);
$this->signed_in = false;
}
private function check_the_login()
{
if (isset($_SESSION['user_id'])) {
$this->user_id = $_SESSION['user_id'];
$this->signed_in = true;
} else {
unset($this->user_id);
$this->signed_in = false;
}
}
public function is_signed_in()
{
return $this->signed_in;
}
public function message($msg="")
{
if (!empty($msg)) {
$_SESSION['message'] = $msg;
} else {
return $this->message;
}
}
public function check_message()
{
if (isset($_SESSION['message'])) {
$this->message = $_SESSION['message'];
unset($_SESSION['message']);
} else {
$this->message = "";
}
}
}
$session = new Session();

Warning: Illegal offset type php

I have been attempting to make a login system with php oop however I have come across this error Warning: Illegal offset type....classes\Session.php on line 11 I'm not quite sure where I'm going wrong any advice would be appreciated.
login
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()){
//log user in
$user = new User();
$login = $user->login(Input::get('username'), Input::get('password'));
if($login){
echo 'Success';
}else{
echo'<p>Sorry invalid details</p>';
}
} else{
foreach($validation->errors() as $error)
echo $error, '<br />';
}
}
}
?>
<form action="" method="POST">
<div class="field">
<label for="username" id="username"> Username </label>
<input type="text" name="username" id="username" autocomplete="off">
</div>
<div class="field">
<label for="password" id="password"> Password </label>
<input type="password" name="password" id="password" autocomplete="off">
</div>
<input type="hidden" name="token" value="<?php echo Token::generate();?>">
<input type="submit" value="Login">
</form>
User
<?php
class User{
private $_db,
$_data,
$_sessionName;
public function __construct($user = null){
$this ->_db = DB::getInstance();
$this->_sessionName = Config::get('session/session_name');
}
public function create($fields = array()){
if($this->_db->insert('users', $fields)){
throw new Exception('There was a problem creating 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;
}
private function data(){
return $this->_data;
}
}
Session
<?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);
}
}
}
index
<?php
require_once 'core/init.php';
if(Session::exists('home')){
echo '<p>' . Session::flash('home', 'You have been registered and can now log in!') . '</p>';
}
echo Session::get(Config::get('session/session_name'));
?>
You should check if session key exist before trying to access it:
<?php
class Session {
public static function put($name, $value){
return $_SESSION[$name] = $value;
}
public static function get($name)
{
return self::exists($name) ? $_SESSION[$name] : null;
}
public static function exists($name)
{
return #$_SESSION[$name] !== null;
}
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);
}
}
}

PHP OOP Login system stdClass::$id

When I login with the correct information I get the following message:
Notice: Undefined property: stdClass::$id in /var/www/classes/User.php on line 37
Success Login!
Line 37 in User.php is following
Session::put($this->_sessionName, $this->data()->id);
Also after i sign in and update page and go to /index.php just to try print out the session, I get nothing.
Following command on index.php page
echo Session::get(Config::get('session/session_name'));
If i don't sign in and just go to index.php i get the following message
Notice: Undefined index: user in /var/www/classes/Session.php on line 12
Login.php
<?php
require_once 'core/init.php';
ini_set('display_errors', 1);
error_reporting(~0);
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) {
echo 'Success Login!';
} else {
echo 'Login failed';
}
} else {
foreach($validation->errors() as $error) {
echo $error;
}
}
}
}
?>
<form action="" method="post">
<div class="field">
<label for="username">Username</label>
<input type="text" name="username" id="username">
</div>
<div class="field">
<label for="password">Password</label>
<input type="password" name="password" id="password">
</div>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input type="submit" value="Logga in">
</form>
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;
public function __construct($user = null) {
$this->_db = DB::getInstance();
$this->_sessionName = Config::get('session/session_name');
}
public function create($fields = array()) {
if(!$this->_db->insert('users', $fields)) {
throw new Exception('Could not create 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;
}
private function data() {
return $this->_data;
}
}
Token.php
<?php
class Token {
public static function generate() {
return Session::put(Config::get('session/token_name'), sha1(uniqid()));
}
public static function check($token) {
$tokenName = Config::get('session/token_name');
if(Session::exists($tokenName) && $token === Session::get($tokenName)) {
Session::delete($tokenName);
return true;
}
return false;
}
}

php : Warning: Invalid argument supplied for foreach()

I just can't figure it out.. but i got a feeling the problem is around there when im throwing the exception messages. I got almost the same code in my registration class. There is just give the errors array the messages normaly like $this->errors[] = "some error".
<?php
class class_login
{
private $id;
private $username;
private $password;
private $passmd5;
private $errors;
private $access;
private $login;
private $ltoken;
public function __cunstruct()
{
$this->errors = array();
$this->login = isset($_POST['login'])? 1:0;
$this->access = 0;
$this->ltoken = $_POST['ltoken'];
$this->id = 0;
$this->username = ($this->login)? $this->filter($_POST['lusername']) : $_SESSION['username'];
$this->password = ($this->login)? $this->filter($_POST['lpassword']) : '';
$this->passmd5 = ($this->login)? md5($this->password) : $_SESSION['password'];
}
public function isLoggedIn()
{
($this->login)? $this->verifyPost() : $this->verifySession();
return $this->access;
}
public function filter($var)
{
return preg_replace('/[^a-zA-Z0-9]/','',$var);
}
public function verifyPost()
{
try
{
if(!$this->tokenValid())
throw new Exception('Invalid Form Submission!');
if(!$this->isDataValid())
throw new Exception('Ivalid Form Data!');
if(!$this->verifyDatabase())
throw new Exception('Invalid Username/Password!');
$this->access = 1;
$this->registerSession();
}
catch(Exception $e)
{
$this->errors[] = $e->getMessage();
}
}
public function verifySession()
{
if($this->sessionExist() && $this->verifyDatabase())
$this->access = 1;
}
public function verifyDatabase()
{
include('db_connect.php');
$data = mysql_query("SELECT ID FROM users WHERE username = '($this->username)' AND password = '($this->passmd5)'");
if (mysql_num_rows($data))
{
list($this->id) = #array_values(mysql_fetch_assoc($data));
return true;
}
else
return false;
}
public function isDataValid()
{
return (preg_match('/[^a-zA-Z0-9](5,12)$/', $this->username) && preg_match('/[^a-zA-Z0-9](5,12)$/', $this->password))? 1:0;
}
public function tokenValid()
{
return (!isset($_SESSION['ltoken']) || $this->ltoken != $_SESSION['ltoken'])? 0 : 1;
}
public function registerSession()
{
$_SESSION['ID'] = $this->id;
$_SESSION['username'] = $this->username;
$_SESSION['password'] = $this->passmd5;
}
public function sessionExist()
{
return (isset($_SESSION['username']) && isset($_SESSION['password']))? 1 : 0;
}
public function show_errors()
{
foreach($this->errors as $key=>$value)
echo $value."</br>";
}
}
?>
The constructor is called __construct, not __cunstruct.
I see you are setting $this->errors to an array in your __cunstruct function, but since it is not __construct it may never be set.
You need a associative array for
foreach($this->errors as $key=>$value)
But you have no one. ($this->errors[] = $e->getMessage();)
With out an associative array you must use:
foreach($this->errors as $value)
public function __cunstruct() <------ The error is probably here. It is __construct
{
$this->errors = array();
$this->login = isset($_POST['login'])? 1:0;
$this->access = 0;
$this->ltoken = $_POST['ltoken'];
$this->id = 0;
$this->username = ($this->login)? $this->filter($_POST['lusername']) : $_SESSION['username'];
$this->password = ($this->login)? $this->filter($_POST['lpassword']) : '';
$this->passmd5 = ($this->login)? md5($this->password) : $_SESSION['password'];
}
You have a typo.... _construct and not _construct

Not displaying values from an array

I have a form that has this code in it, so I can echo the errors as I check the fields from a class:
<?php if( isset($_POST['send'])){
$new_user = new Register();
$new_user->check_required_fields($_POST);
$new_user->display_errors();
}
?>
and the class is:
<?php
class Register extends Database
{
public $fname;
public $lname;
public $uname;
public $email;
public $pass1;
public $pass2;
public $year;
public $month;
public $day;
public $required_array;
public $error;
public $errors = array();
public function check_required_fields($required_array)
{
if(in_array('', $required_array)) {
$errors[] = "One or more fields are missing";
//var_dump($errors);
}
else
{
$errors[] = "All fields are ok";
$this->fname = $required_array['fname'];
$this->lname = $required_array['lname'];
$this->uname = $required_array['lname'];
$this->email = $required_array['email'];
$this->pass1 = $required_array['pass1'];
$this->pass2 = $required_array['pass2'];
$this->year = $required_array['year'];
$this->month = $required_array['month'];
$this->day = $required_array['day'];
}
}
public function display_errors ($errors)
{
foreach ($errors as $error){
echo $error;
}
}
For some reason it will not display the $errors array and I am not sure why? I would be greatful for any help, thanks.
Try using
$this->errors
in both check_required_fields and display_errors.
public function display_errors ($errors)
{
foreach($errors as $error){
echo $error;
}
}
the "$errors" you use in the foreach statement is the one in the function display_errors's parameter list, and when you invoke the function, you didn't give any parameter, so this variable would be empty
you should use $this->errors in the foreach statement

Categories