Logging a User In - ZingPHP/Zing GitHub Wiki
Logging in a user
Many applications require that a user be logged in to do particular actions, here is a simple user login that works effectively.
class Home extends Zing{
protected $db;
public function runBefore(){
$this->db = $this->dbo("localhost");
}
public function userLogin(){
// Get the POST data passed in
$email = $this->input->post("email");
$password = $this->input->post("password");
// Note that everything after the underscore in `getItemsBy_email` is the database column name
$user = $this->db->getTable("users")->getItemsBy_email($email, true)->toArray();
// Test the password from the database if valid, set login data
if(isset($user["password"]) && $this->user->verifyPassword($password, $user["password"])){
$this->user->login(array(
"id" => $user["user_id"],
"email" => $user["email"],
"username" => $user["username"],
"first" => $user["first_name"],
"last" => $user["last_name"],
));
// Redirect to the users page
$this->http->location("/user");
}
// Invalid data sent, redirect to login page
$this->http->location("/home/login");
}
public function logout(){
$this->user->logout();
$this->http->location("/home/login");
}
}
Note: I find it best to place the database connection methods in a Helper class (Helpers go in the Helpers directory Websites/Helpers)
class Base extends Zing{
protected $db;
public function runBefore(){
$this->db = $this->dbo("localhost");
}
}
Then the class Home
would be modified to extend Base
instead of Zing
then protected $db
and Home::runBefore()
would be removed from the Home
class. The class would then look like this:
class Home extends Base{
public function userLogin(){
// Snipped code from above
}
public function logout(){
// Snipped code from above
}
}