You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Slim框架JWT登录页遇unexpected end of file错误求助

Hey Matteo, let's break down and fix your issues step by step—those syntax errors and undefined variable problems are easier to resolve than they look!

1. Fix the Core Syntax Error Causing "Unexpected End of File" / "Unexpected ?>"

Your main issue is a missing closure for the $app->post() method call plus a misnamed database connection variable:

  • You forgot to add ); at the end of your /authenticate route definition. PHP was reaching the end of the file looking for this closing marker, which triggered the "unexpected end of file" error. When you messed with the ?> tag, it just shifted the syntax error to that line instead.
  • You initialized your database connection as $db = $db->connect(); but then tried to use an undefined $conn variable for the query—replace $conn with $db everywhere you interact with the database.

2. Fix Undefined Variables and SQL Query Gaps

Your SQL query isn't fetching all the fields your code tries to use, which would cause "Undefined Index" errors even after fixing the syntax:

  • Update your SQL to include username, roles, and email (since your code references these values):
    SELECT id, username, first_name, last_name, password, roles, email FROM " . $table_name . " WHERE username = ? LIMIT 0,1
    
  • Assign the $email variable from your query result (it was missing in your original code): $email = $row['email'];

3. Add Missing JWT Import and Slim App Execution

  • You're using JWT::encode() but haven't imported the JWT class. Add this line at the top of your file (make sure you've installed the firebase/php-jwt package via Composer first):
    use Firebase\JWT\JWT;
    
  • Slim apps require a final $app->run(); call to start the application—without this, your route won't ever execute.

4. Fixed Full Code

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use Firebase\JWT\JWT; // Import JWT class

// CORS headers (note: for production, use Slim's CORS middleware instead)
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, DELETE, PUT, PATCH, OPTIONS');
header('Access-Control-Allow-Headers: token, Content-Type');

$app = new \Slim\App;

$app->post("/authenticate", function(Request $request, Response $response){
    $username = $request->getParam('username');
    $password = $request->getParam('password');
    $table_name = 't_users';

    // Updated SQL with all required fields
    $sql = "SELECT id, username, first_name, last_name, password, roles, email FROM " . $table_name . " WHERE username = ? LIMIT 0,1";

    $db = new db();
    $db = $db->connect();

    // Fixed database connection variable
    $stmt = $db->prepare($sql);
    $stmt->bindParam(1, $username);
    $stmt->execute();
    $num = $stmt->rowCount();

    if($num > 0){
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $id = $row['id'];
        $username = $row['username'];
        $roles = $row['roles'];
        $password2 = $row['password'];
        $email = $row['email']; // Define missing email variable

        if(password_verify($password, $password2)) {
            $secret_key = "javainuse";
            $issuer_claim = "LATAVOLAITALIANA";
            $audience_claim = "THE_AUDIENCE";
            $issuedat_claim = time();
            $notbefore_claim = $issuedat_claim + 10;
            $expire_claim = $issuedat_claim + 60;

            $token = array(
                "iss" => $issuer_claim,
                "aud" => $audience_claim,
                "iat" => $issuedat_claim,
                "nbf" => $notbefore_claim,
                "exp" => $expire_claim,
                "data" => array(
                    "id" => $id,
                    "username" => $username,
                    "roles" => $roles,
                    "email" => $email
                )
            );

            http_response_code(200);
            $jwt = JWT::encode($token, $secret_key);
            echo json_encode( array(
                "message" => "Successful login.",
                "jwt" => $jwt,
                "email" => $email,
                "expireAt" => $expire_claim
            ));
        } else {
            http_response_code(401);
            echo json_encode(array("message" => "Login failed.", "password" => $password));
        }
    } else {
        // Add handling for when no user is found
        http_response_code(404);
        echo json_encode(array("message" => "User not found."));
    }
}); // Added missing closure for $app->post()

$app->run(); // Start the Slim application
?>

Quick Best Practice Notes

  • For production, replace the raw header() calls with a proper Slim CORS middleware (like tuupola/slim-jwt-auth or neomerx/cors-psr7)—it's more reliable and maintainable.
  • Instead of echo json_encode(), use Slim's response object for JSON output (e.g., return $response->withJson($data, 200);) to avoid header/output conflicts.
  • Double-check that your db class's connect() method returns a valid PDO instance—this is a common hidden issue.

内容的提问来源于stack exchange,提问作者matteo sperti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:45:50