PHP Slim框架路由报错“No such file or directory”及多参数路由使用问题咨询
1. Fixing the "No such file or directory" Error
That error usually pops up when your web server isn’t routing requests through Slim’s front controller (public/index.php) correctly. Let’s walk through the fixes:
PHP Built-in Server Setup: If you’re using PHP’s built-in server, start it with this command from your project root:
php -S localhost:8080 public/index.phpWithout specifying
public/index.php, the server will hunt for a physical directory nameduser/test@gmail.cominstead of passing the request to Slim to handle the route.Route Placement & SQL Fix: Double-check your route is placed after initializing
$appand before$app->run(). Also, you missed binding the email parameter in your SQL execute call—here’s the corrected code:use Slim\Factory\AppFactory; use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; require __DIR__ . '/vendor/autoload.php'; $app = AppFactory::create(); // Your corrected route $app->get('/user/{email}', function (Request $request, Response $response, array $args){ $email = $args["email"]; $sql = "SELECT * FROM user WHERE email=:email"; $stmt = $this->db->prepare($sql); $stmt->execute(['email' => $email]); // Bind the parameter here! $result = $stmt->fetchAll(); return $response->withJson(["status" => "success", "data" => $result], 200); }); $app->run();Database Container Registration: Make sure you’ve registered your database connection in Slim’s container so
$this->dbworks. Add this before your routes:$app->getContainer()->set('db', function () { $host = 'localhost'; $dbname = 'your_database_name'; $user = 'your_db_user'; $pass = 'your_db_password'; return new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass); });
2. Using Multiple Parameters in Routes
Absolutely! Slim handles multiple route parameters just like Node.js—you define them in the route pattern and grab them from the $args array, similar to req.params in Node.
Here’s how to implement your example:
$app->get('/user/{email}/{password}', function (Request $request, Response $response, array $args) { // Fetch parameters from $args (just like req.params in Node) $email = $args['email']; $password = $args['password']; // Use them in your query (remember parameter binding for security!) $sql = "SELECT * FROM user WHERE email=:email AND password=:password"; $stmt = $this->db->prepare($sql); $stmt->execute([ 'email' => $email, 'password' => $password ]); $result = $stmt->fetchAll(); return $response->withJson(["status" => "success", "data" => $result], 200); });
You can then access this route via localhost:8080/user/test@gmail.com/pass exactly as you planned.
Quick Security Note: Passing passwords in the URL is risky—they get logged in server logs, browser history, etc. For authentication, use a POST request and send credentials in the request body instead.
内容的提问来源于stack exchange,提问作者Ananda Pramono

