I am developing a simple registration form that validates with php. problem is rather than the validation echoing on screen once I click the submit button nothing happens, no error or brake it dose not show me what the error is, I believe my logic is correct but I believe there may be a mistake.
would appriciate any advise or identification of my problem
register.php
<?php
require_once 'core/init.php';
if(Input::exists()) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array(
'required' => true,
'min' => 2,
'max' => 20,
'unique' => 'users'
),
'password' => array(
'required' => true,
'min' => 6
),
'password_again' => array(
'required' => true,
'matches' => 'password'
),
'name' => array(
'required' => true,
'min' => 2,
'max' => 50
),
));
if($validation->passed()) {
echo 'Passed';
} else {
print_r($validation->errors());
}
}
?>
<form action="" methord="post">
<div class="field">
<lable for="username">Username</lable>
<input type="text" name="username" id="username" value="<?php echo escape(Input::get('username')); ?>" autocomplete="off">
</div>
<div class="field">
<lable for="password">Choose Your Password</lable>
<input type="password" name="password" id="password">
</div>
<div class="field">
<lable for="password_again">Verify Password</lable>
<input type="password" name="password_again" id="password_again">
</div>
<div class="field">
<lable for="name">Your Name</lable>
<input type="text" name="name" value="<?php echo escape (Input::get('name')); ?>" id="name">
</div>
<input type="submit" value="Register">
</form>
Validation.php
<?php
class Validate {
private $_passed = false,
$_errors = array(),
$_db = null;
public function __contruct() {
$this->_db = DB::getInstance();
}
public function check($source, $items = array()) {
foreach($items as $item => $rules) {
foreach($rules as $rule => $rule_value) {
$value = $source[$item];
if($rule == 'required' && empty($value)) {
$this->addError("{$item} is required")
} else {
}
}
}
if(empty($this->_errors)) {
$this->_passed = true;
}
return $this;
}
private function addError() {
$this->_errors[] = $error;
}
public function errors() {
return $this->_errors;
}
public function passed() {
return $this->_passed;
}
}
UPDATE
Have corrected typo that was correctly pointed out by #PeteR, but there is still a problem that the echo validation is not printing out.
Link to form
http://stuweb.cms.gre.ac.uk/~ob219/membership/register.php
Looks like you have a typo, fella.
if($rule == 'requierd' && empty($value)) {
You also have a semicolon missing here:
$this->addError("{$item} is required");
----^
And another typo:
<form action="" methord="post">
Should be method...
And finally, try this:
private function addError($error) {
Input::exists()
returns false/null or contains errors, thus, the if statement is not true
if(Input::exists()) {
and the code inside of it (validation) does never get executed.
Debug with
print_r(Input::exists());
You should also change your if to a real condition:
if(Input::exists() === true) {
Enable error reporting in PHP (from http://blog.flowl.info/2013/enable-display-php-errors/)
<?php
// Put these lines to the top of your script
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('display_startup_errors', true);
ini_set('xmlrpc_errors', true);
Update - Yet another one:
private function addError() {
$this->_errors[] = $error;
}
Method has no parameters..
private function addError($error) {
$this->_errors[] = $error;
}
Related
im currently learning how to make a working multi level login using code igniter using multi table because every type of user have some uniqueness and i tried to use md5 in the past but someone tell me that md5 is not save, so i try to use password-hash/password-verify but when i try to fill the login form it just telling me that the password is wrong even though i fill it with the same password "123456789" when create the account
This is my AuthController
namespace App\Controllers;
use App\Models\AdminModel;
use App\Models\GuruModel;
use App\Models\MuridModel;
use App\Models\WalimuridModel;
class Auth extends BaseController
{
public function __construct()
{
$this->adminModel = new AdminModel();
$this->guruModel = new GuruModel();
$this->muridModel = new MuridModel();
$this->walimuridModel = new WalimuridModel();
$this->validation = \Config\Services::validation();
$this->session = \Config\Services::session();
}
public function valid_login()
{
//Take data from the login form
$nama_user = $this->request->getVar('username');
$password = $this->request->getVar('password');
//Take data from database that have the same username
$admin = $this->adminModel->where('username_admin', $nama_user)->first();
$guru = $this->guruModel->where('username_guru', $nama_user)->first();
$murid = $this->muridModel->where('username_murid', $nama_user)->first();
$walimurid = $this->walimuridModel->where('username_walimurid', $nama_user)->first();
//check if username founded
if($admin){
$verify_pass = password_verify($password, $admin['password_admin']);
if($verify_pass){
$sessLogin = [
'isLogin' => true,
'username' => $admin['username_admin'],
'password' => $admin['password_admin'],
'email' => $admin['email_admin'],
'nama' => $admin['nama_admin'],
'jeniskelamin' => $admin['jenis_kelamin'],
'fotoprofil' => $admin['foto_profile'],
'level' => 'admin'
];
$this->session->set($sessLogin);
return redirect()->to('/admin/index');
}
else {
session()->setFlashdata('password', 'Password salah');
return redirect()->to('/login');
}
}
else if($guru){
if($guru['password_guru'] == md5($data['password'])){
$sessLogin = [
'isLogin' => true,
'username' => $guru['username_guru'],
'password' => $guru['password_guru'],
'email' => $guru['email_guru'],
'nama' => $guru['nama_guru'],
'jeniskelamin' => $guru['jenis_kelamin'],
'fotoprofil' => $guru['foto_profile'],
'level' => 'guru'
];
$this->session->set($sessLogin);
return redirect()->to('/guru/index');
}
}
else if($murid){
if($murid['password_murid'] == md5($data['password'])){
$sessLogin = [
'isLogin' => true,
'nisn' => $murid['nisn'],
'username' => $murid['username_murid'],
'password' => $murid['password_murid'],
'email' => $murid['email_murid'],
'nama' => $murid['nama_murid'],
'jeniskelamin' => $murid['jenis_kelamin'],
'fotoprofil' => $murid['foto_profile'],
'level' => 'murid'
];
$this->session->set($sessLogin);
return redirect()->to('/murid/index');
}
}
else if($walimurid){
if($walimurid['password_walimurid'] == md5($data['password'])){
$sessLogin = [
'isLogin' => true,
'username' => $walimurid['username_walimurid'],
'password' => $walimurid['password_walimurid'],
'email' => $walimurid['email_walimurid'],
'nama' => $walimurid['nama_walimurid'],
'nisnanak' => $walimurid['nisn_murid'],
'jeniskelamin' => $walimurid['jenis_kelamin'],
'fotoprofil' => $walimurid['foto_profile'],
'level' => 'walimurid'
];
$this->session->set($sessLogin);
return redirect()->to('/walimurid/index');
}
}
else{
//jika username tidak ditemukan, balikkan ke halaman login
session()->setFlashdata('username', 'Username tidak ditemukan');
return redirect()->to('/login');
}
}
this is my Admin Model
<?php
namespace App\Models;
use CodeIgniter\Model;
class AdminModel extends Model
{
protected $table = 'admin';
protected $primaryKey = 'id_admin';
protected $useAutoIncrement = true;
protected $protectFields = true;
protected $allowedFields = ["id_admin","username_admin","password_admin","email_admin","nama_admin","jenis_kelamin","foto_profile"];
}
every model is basically the same
this is my login.php (login form)
<form method="post" action="/auth/valid_login">
<div class="wrap">
<input type="username" name="username" class="input" placeholder="username">
<span class="underline"></span><br>
<?php if($username){ ?>
<div class="alert alert-danger" role="alert">
<?php echo $username?>
</div>
<?php } ?>
</div>
<div class="wrap">
<input type="password" name="password" class="input" placeholder="Password">
<span class="underline"></span><br>
<?php if($password){ ?>
<div class="alert alert-danger" role="alert">
<?php echo $password?>
</div>
<?php } ?>
</div>
<div class="col-md-12 text-center">
<button type="submit" class="btn-a">Login</button>
</div>
</form>
this is my create admin form
<form method="post" action="/admin/save_admin">
Username: <br>
<input type="text" name="username" required><br>
Password: <br>
<input type="password" name="password" required><br>
Email: <br>
<input type="email" name="email" required><br>
Nama: <br>
<input type="text" name="nama_admin" required><br>
Jenis Kelamin: <br>
<input type="text" name="jenis_kelamin" required><br>
Foto Profil: <br>
<input type="text" name="fotoprofil" required><br>
<button type="submit">Register</button>
</form>
and my create function
public function save_admin()
{
$data = $this->request->getPost();
$this->validation->run($data, 'cradmin');
$errors = $this->validation->getErrors();
if($errors){
session()->setFlashdata('error', $errors);
return redirect()->to('/admin/admin/create');
}
$password = password_hash($data['password'], PASSWORD_DEFAULT);
$this->adminModel->save([
'username_admin' => $data['username'],
'password_admin' => $password,
'email_admin' => $data['email'],
'nama_admin' => $data['nama_admin'],
'jenis_kelamin' => $data['jenis_kelamin'],
'foto_profile' => $data['fotoprofil'],
]);
session()->setFlashdata('add', 'Data Admin berhasil dibuat');
return redirect()->to('/admin/admin/index');
}
i have tried to change the requirement of login like if the password same as the database it will make session or if password wrong go to login form and make session and none of it work sorry if my english is bad
I have tried to copy from Codegniter's documentation, but I can't make form validation callbacks working.
I added helper form, url and library form_validation. It's not working and always returns "false"
Controller
public function addtest()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if ($this->form_validation->run() == TRUE)
{
die('true');
}
else
{
die('false');
}
}
$this->template
->build('myform',array());
}
public function username_check($str)
{
if ($str == 'test')
{
return TRUE;
}
else
{
return FALSE;
}
}
View
<form method="post" action="" class="form-horizontal form-label-left">
<div class="col-xs-12 col-md-9">
<div class="x_panel">
<div class="form-group col-xs-12">
<div class="col-xs-3">
<label class="control-label">Folder name</label>
</div>
<div class="col-xs-9">
<input type="text" name="username" value="" class="form-control " id="" placeholder="">
</div>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
Extend your form_validation library in Libraries.php
MY_Form_validation.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation
{
function run($module = '', $group = '') {
(is_object($module)) AND $this->CI =& $module;
return parent::run($group);
}
}
/* End of file MY_Form_validation.php */
/* Location: ./application/libraries/MY_Form_validation.php */
My Controller function is like this and it runs perfectly. I have autoloaded all libraries
public function change_password()
{
if($this->isLoggedin()){
$data['title']='Change Password';
if($_POST)
{
$config=array(
array(
'field' => 'old_password',
'label' => 'Old Password',
'rules' => 'trim|required|callback_checkPassword'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required'
),
array(
'field' => 'conf_password',
'label' => 'Confirm Password',
'rules' => 'trim|required|matches[password]'
)
);
$this->form_validation->set_rules($config);
if ($this->form_validation->run() == false)
{
// if validation has errors, save those errors in variable and send it to view
$data['errors'] = validation_errors();
$this->load->view('change_password',$data);
}
else
{
// if validation passes, check for user credentials from database
$this->Login_model->updatePassword($_POST['password'],$this->session->userdata['id']);
$this->session->set_flashdata('log_success','Congratulations! Password Changed');
redirect(base_url() . 'Login/dashboard');
}
}
else
{
$this->load->view('change_password',$data);
}
}
else
{
redirect(base_url().'Login');
}
}
public function checkPassword($str)
{
$check=$this->Login_model->checkPassword($str);
if($check)
{
return true;
}
else
{
$this->form_validation->set_message('checkPassword', 'The Current Password you have provided is incorrect');
return false;
}
}
In HTML (Add ID field)
<input type="text" name="username" value="" class="form-control " id="username" placeholder="">
<button type="submit" class="btn btn-success" id="submit">Submit</button>
In your AJAX code
<script type="text/javascript">
$(function(){
$( "#submit" ).click(function(event)
{
event.preventDefault();
var username= $("#username").username();
$.ajax(
{
type:"post",
url: "<?php echo base_url(); ?>index.php/controller/Method",
data:{ username:username},
success:function(res)
{
}
});
});
});
</script>>
In Controller
No need of check if($_SERVER['REQUEST_METHOD'] == 'POST') because it comes through it always
public function addtest()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
if ($this->form_validation->run() == TRUE)
{
die('true');
}
else
{
die('false');
}
$this->template->build('myform',array());
}
public function username_check($str)
{
if (empty($str))
{
echo "Empty";
}
else
{
if ($str == 'test')
{
return TRUE;
}
else
{
return FALSE;
}
}
}
Check more about CodeIgniter callback function
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
}
}
I looked in the forum for similar questions but could not find anything that would help me.
I have the validation class that validates form entries. But It displays them at the top of the table. How could I display these next to the fields rather then top of the form?
Registration.php
if(Input::exists()){
$validate = new Validate();
$validation = $validate->check($_POST, array(
'fullName' => array(
'required' => true,
'min' => 4,
'max' => 20
),
'username' => array(
'required' => true,
'min' => 4,
'max' => 20,
'unique' => 'user'
),
'email' => array(
'required' => true,
'unique' => 'user'
),
'password' => array(
'required' => true,
'min' => 6
),
'password_again' => array(
'required' => true,
'matches' => 'password'
)
));
if($validation->passed()){
// Register User
echo('Passed');
} else {
// Output Errors
foreach($validation->errors() as $error){
echo $error, '</br>';
}
}
}
?>
<div class="registration">
<h3> Register with WebA<font style="color: #c14a44;">ww</font>ards </h3>
<p> Spare us few little seconds, and you'll be glad you did. </p>
<form method="post" action="">
<input type="text" id="fullName" value="<?php echo escape(Input::get('fullName')); ?>" name="fullName" placeholder="Your Full name">
<input type="text" id="username" value="<?php echo escape(Input::get('username')); ?>" name="username" placeholder="Choose Username" autocomplete="off">
<input type="email" id="email" value="<?php echo escape(Input::get('email')); ?>" name="email" placeholder="Email address">
<input type="password" id="password" name="password" placeholder="Password">
<input type="password" id="password_again" name="password_again" placeholder="Comfirm password">
<input id="gobutton" type="submit" value="Register">
</form>
Validate.php
public function check($source, $items = array()){
foreach($items as $item => $rules){
foreach($rules as $rule => $rule_value){
$value = trim($source[$item]);
$item = escape($item);
// if rule is required and value is empty add error
if($rule === 'required' && empty($value)){
$this->addError("{$item} is required");
} else if(!empty($value)) {
// DEFINE THE RULES FOR VALIDATION MIN, MAX
// USE SWITCH STATEMENT TO SWITCH BETWEEN THE RULES AND CHECK IF VALID
// Case for each of the rules defined on the form
switch($rule){
case 'min':
if(strlen($value) < $rule_value){
$this->addError("{$item} must be a minimum of {$rule_value} characters.");
}
break;
case 'max':
if(strlen($value) > $rule_value){
$this->addError("{$item} must be a maximum of {$rule_value} characters.");
}
break;
case 'matches':
if($value != $source[$rule_value]){
$this->addError("{$rule_value} must match {$item}");
}
break;
case 'unique':
$check = $this->_db->get($rule_value, array($item, '=', $value));
if($check->count()){
$this->addError("{$item} already exists.");
}
break;
}
}
}
}
if(empty($this->_errors)){
$this->_passed = true;
}
return $this;
}
You write code that puts those errors where you want them.
<?php
$errors = array();
if (!$something) {
$errors['field'] = 'Message';
}
?>
<? if (isset($errors['field'])) : ?>
<p class="error"><?php echo $errors['field']; ?></p>
<?php endif; ?>
<input type="text" name="field" ...>
Without seeing more of your code I can't tell (the addError method isn't included), but your validation class doesn't appear to have an easy way of associating an error with a field in the response (it's just a single string), so it will need some work to do this. I would suggest returning the errors as an associative array, with the key being the name of the field, and the value being the error message to be printed, and leave it blank for fields that are correct. Then, in your registration file, you can easily refer to the field in question.
You have to iterate through the errors while you are outputting the fields, check for errors related to that field, and print them after outputting the inputs, instead of echoing all the errors above the form.
The errors array should be multidimensional, if you need to have more than one validation error in each field. You should have an array with an entry for each field name.
You would also need the fields to be an array to achieve this.
This way you could do something like this (untested):
foreach ($field as $f) {
echo "<input type='{$f->type}' id='{$f->name}' value='{$f->value}' name='{$f->name}' placeholder='{$f->description}'>";
if (in_array($f->name, $errors)) {
echo "<span class='errors'>{$errors[$f->name]}</span>";
}
}
If the error entry for each field is an array, you would have to iterate through it before echoing the errors.
I have this code that was working initially, but does not work after I restarted my computer.
The error I am getting is:
Warning: Illegal offset type in isset or empty in D:\xampp\htdocs\cookieboylive\classes\Session.php on line 4
There's 3 files on my site - Index, Login, Register. Index page checks if users is logged in, but I don't think it has anything to do with the problem.
Here's the current code:
The main register/login.php page
require_once 'core/init.php';
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array('required' => true),
'password' => array('required' => true)
));
if($validation->passed()) {
$user = new User();
$login = $user->login(Input::get('username'), Input::get('password'));
if($login) {
Redirect::to('index.php');
} else {
echo '<p>Sorry, login failed.</p>';
}
} else {
foreach($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
}
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array(
'required' => true,
'min' => 2,
'max' => 20,
'unique' => 'users'
),
'password' => array(
'required' => true,
'min' => 6
),
'password_again' => array(
'required' => true,
'matches' => 'password'
),
'name' => array(
'required' => true,
'min' => 2,
'max' => 50
)
));
if($validation->passed()) {
$user = new User();
$salt = Hash::salt(32);
try {
$user->create(array(
'username' => Input::get('username'),
'password' => Hash::make(Input::get('password'), $salt),
'salt' => $salt,
'name' => Input::get('name'),
'joined' => date('Y-m-d H:i:s'),
'group' => 1
));
Session::flash('home', 'Register SUCCESS');
Redirect::to('index.php');
} catch(Exception $e) {
die($e->getMessage());
}
} else {
foreach($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="styles/register_login_styles.css">
<link rel="stylesheet" type="text/css" href="styles/animate-custom.css">
</head>
<body>
<div class="container">
<div id="container_demo" >
<a class="hiddenanchor" id="toregister"></a>
<a class="hiddenanchor" id="tologin"></a>
<div id="wrapper">
<div id="login" class="animate form">
<form action="" method="post">
<div class="field">
<h1>Log in</h1>
<p>
<label for="username" class="uname" data-icon="u" >Username </label>
<input id="username" name="username" required="required" type="text" placeholder="Username" autocomplete="off">
</p>
<p>
<label for="password" class="youpasswd" data-icon="p">Password </label>
<input id="password" name="password" required="required" type="password" placeholder="Password">
</p>
<p class="keeplogin">
<input type="checkbox" name="loginkeeping" id="loginkeeping" value="loginkeeping">
<label for="loginkeeping">Keep me logged in</label>
</p>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<p class="login button">
<input type="submit" value="Login">
</p>
<p class="change_link">
Not a member yet ?
Join us
</p>
</form>
</div>
</div>
<div id="register" class="animate form">
<form action="" method="post">
<h1> Sign up </h1>
<p>
<label for="username" class="uname" data-icon="u">Username</label>
<input id="username" value="<?php echo escape(Input::get('username')); ?>" name="username" required="required" type="text" placeholder="Username" autocomplete="off">
</p>
<p>
<label for="password" class="youpasswd" data-icon="p">Your password </label>
<input id="password" name="password" required="required" type="password" placeholder="Password">
</p>
<p>
<label for="password_again" class="youpasswd" data-icon="p">Please confirm your password </label>
<input id="password_again" name="password_again" required="required" type="password" placeholder="Password again">
</p>
<p>
<label for="name" class="youmail" data-icon="n" >Name</label>
<input id="name" name="name" value="<?php echo escape(Input::get('name')); ?>" required="required" type="text" placeholder="Name" autocomplete="off">
</p>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<p class="signin button">
<input type="submit" value="Sign up">
</p>
<p class="change_link">
Already a member ?
Go and log in
</p>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Session.php
<?php
class Session {
public static function exists($name) {
return (isset($_SESSION[$name])) ? true : false;
}
public static function put($name, $value) {
return $_SESSION[$name] = $value;
}
public static function get($name) {
return $_SESSION[$name];
}
public static function delete($name) {
if(self::exists($name)) {
unset($_SESSION[$name]);
}
}
public static function flash($name, $string = '') {
if(self::exists($name)) {
$session = self::get($name);
self::delete($name);
return $session;
} else {
self::put($name, $string);
}
}
}
User.php
<?php
class User {
private $_db,
$_data,
$_sessionName,
$_isLoggedIn;
public function __construct($user = null) {
$this->_db = DB::getInstance();
$this->_sessionName = Config::get('session/session_name');
if(!$user) {
if(Session::exists($this->_sessionName)) {
$user = Session::get($this->_sessionName);
if($this->find($user)) {
$this->_isLoggedIn = true;
} else {
// Pr0cess logout
}
} else {
$this->find($user);
}
}
}
public function create($fields = array()) {
if(!$this->_db->insert('users', $fields)) {
throw new Exception('There was a problem creating an account.');
}
}
public function find($user = null) {
if($user) {
$field = (is_numeric($user)) ? 'id' : 'username';
$data = $this->_db->get('users', array($field, '=', $user));
if($data->count()) {
$this->_data = $data->first();
return true;
}
}
return false;
}
public function login($username = null, $password = null) {
$user = $this->find($username);
if($user) {
if($this->data()->password === Hash::make($password, $this->data()->salt)) {
Session::put($this->_sessionName, $this->data()->id);
return true;
}
}
return false;
}
public function data() {
return $this->_data;
}
public function isLoggedIn() {
return $this->_isLoggedIn;
}
}
I'm getting Fatal error: DEBUG: array ...
That means $name is an array, which is obviously an illegal string offset. $_SESSION[array()] does not work. Make sure you're passing the right value to Session::exists().
I tried most of the solutions suggested above. In actual fact the answer is not in the spelling but is in the fact that, as was pointed out above, the $name variable in the exists function is actually an array.
public static function exists($name) {
return (isset($_SESSION[$name])) ? true : false;
}
The simple fix is to append [0] to [$name] so it becomes [$name][0] which returns the value associated with it and the one you want to see. Works for me. Why it worked in the video, I can't figure out; may be a configuration thing.
I recognize the context you are dealing with, a tutorial PHP login/registration project from Skillfeed. In fact I had the very same error that led me to a google search on the same error - I ended on this stackoverflow thread by You.
I couldn't find the answers very helpful but I looked through the classes of my project and I found the source of my problem in another class than your 3 classes shown in here.
That is in Token.php :
public static function check($token){
$tokenName = Config::get('sesson/token_name');
if(Session::exists($tokenName) && $token === Session::get($tokenName)){
Session::delete($tokenName);
return true;
}
return false;
}
The problem was a simple misspelling , notice the get() function with its string parameter 'sesson/token_name', it should have been 'session/token_name'. Once I fixed this it worked for me!
It simply means the type of the variable (int, bool, array,..) you are passing does not aligns with expected parameter type in empty or isset.
You have not typed the $name variable and that`s should be problem.
Try this which will check also $name variable:
return !empty($name) && is_string($name) && isset($_SESSION[$name]) ? true : false;
Just play with some situations or implement typing into you code.
"Warning: Illegal offset type in isset or empty" may be shown if key-variable is not string. Example:
foreach ($xml->attributes() as $attrname => $attrval)
{
if($attrname == "Name") $Name = $attrval;
if(isset($_GET[$Name])) //catch Warning
...
Because gettype($Name) --> object.
Use type conversion to string:
if(isset((string)$_GET[$Name])) //pass Perfect