PHP user class (login/logout/signup)

PHP user class (login/logout/signup)

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Architecting Authentication: A Critique of the PHP User Class Pattern

The initial instinct to bundle user registration, login, and logout logic into a single UserService class is understandable. It creates a self-contained unit that seems tidy on paper. However, looking at the provided implementation reveals several architectural patterns from the 2010s that need immediate attention before you proceed further with this codebase.

The most glaring issue lies in the use of the mysql_* functions. The PHP extension mysql has been removed as of version 5.5 and is effectively deprecated in modern environments. It does not support prepared statements, which are critical for preventing SQL injection attacks. The current implementation uses mysql_real_escape_string within the class properties. This approach is fundamentally flawed because it couples your class to a specific database connection context that doesn't exist here. You cannot safely escape strings without an active database resource (mysqli or PDO).

Furthermore, storing raw passwords and salts in class properties like $this->_password is a severe anti-pattern. When you assign $_POST['password'] directly to a private property, you are exposing that variable within the object's scope. Even though you hash it later, passing sensitive data through public or protected methods without immediate processing increases the surface area for bugs.

The Logic Flow: Direct vs. Separated Calls

You asked whether the login flow should be automatic ($User->login() calling _checkCredentials()) or separated into explicit steps. From a functional standpoint, both achieve the same result if the first approach is chosen correctly. However, the separation of concerns in your second example suggests a misunderstanding of what login and checkCredentials represent.

In Object-Oriented Design, a "service" class should encapsulate business logic, not necessarily act as a state machine for session management. If _checkCredentials is protected, it implies it's an internal helper. If you call it directly from outside the class ($User->checkCredentials()), you are breaking encapsulation and forcing the caller to understand your internal implementation details.

The first approach, where login handles the entire transaction, is generally preferred for user-facing actions like authentication. It hides the complexity of querying the database and validating the hash from the controller. The second approach, splitting the logic, introduces a state dependency: you must store the $userId in the object to pass it to the next method, or accept that the class needs to maintain internal state across public method calls.

Refactoring toward Modern Standards

To move this code forward safely, you must adopt prepared statements and proper connection handling. Here is how a modern implementation using PDO would look, addressing the SQL injection risks and connection management:

class UserService
{
    private $pdo;

    public function __construct($pdo)
    {
        $this->pdo = $pdo;
    }

    public function login($email, $password)
    {
        // Bind parameters safely to prevent SQL injection
        $stmt = $this->pdo->prepare("SELECT id, password, salt FROM users WHERE email = :email LIMIT 1");
        $stmt->execute(['email' => $email]);

        if (!$user = $stmt->fetch()) {
            return false;
        }

        // Verify password hash
        $hash = sha1($user['salt'] . $password);
        
        if ($hash === $user['password']) {
            session_regenerate_id(true); // Prevent session fixation
            $_SESSION['user_id'] = $user['id'];
            return true;
        }

        return false;
    }
}

Notice the shift from mysql_* to PDO. The connection is injected via the constructor (Dependency Injection), ensuring the class doesn't rely on a global state. The query uses placeholders (:email), rendering manual string escaping unnecessary and unsafe.

Handling Registration and Logout

Your title mentions signup, but the code snippet focuses entirely on login. A robust authentication system requires a symmetric approach for registration. You cannot reuse the login class for registration without adding methods that handle password hashing (using bcrypt instead of SHA1) and uniqueness checks. Additionally, logout is missing from your current scope. In PHP, logging out simply involves destroying the session:

session_destroy();
$_SESSION = [];

Migration Path

If you are currently running legacy code using mysql_*, migrating to PDO or MySQLi is non-negotiable for security compliance. While frameworks like Laravel abstract these details away, understanding the underlying mechanics helps when writing raw PHP services. If you are building a larger application where rapid development and security maintenance are priorities, exploring a framework might be more efficient than maintaining custom service classes from scratch. For instance, resources from https://laravelcompany.com discuss how modern frameworks handle these complexities out of the box, allowing you to focus on business logic rather than connection strings and escaping functions.

Ultimately, the choice between automatic execution and separated calls is less important than ensuring your class encapsulates its own state correctly, uses secure database interactions, and does not expose internal implementation details to external callers.

Our network