原生PHP控制台启动服务器时数据库连接报“Could not find driver”的问题排查及其他解决方法咨询
Hey there, I’ve run into this exact issue before—let’s get you sorted out. The core problem here is almost always that PHP’s built-in web server (php -S) is using a different php.ini configuration file than your working environment (like Apache/Nginx + PHP-FPM). Here’s how to diagnose and fix it:
Step 1: Verify Which php.ini File Each Environment Uses
First, confirm the config file path for both scenarios:
- For the built-in server:
- Create a file named
info.phpwith this content:<?php phpinfo(); ?> - Start the built-in server:
php -S localhost:8000 - Visit
http://localhost:8000/info.phpin your browser, then look for the Loaded Configuration File line—note this path.
- Create a file named
- For your working environment:
- Either run
php -r "phpinfo();"in your terminal (if CLI matches your web env), or create the sameinfo.phpfile and access it via your normal web server. Note theLoaded Configuration Filepath here too.
- Either run
If the paths are different, that’s your culprit. The built-in server is using a config that doesn’t have your database driver enabled.
Step 2: Enable the Database Driver in the Correct php.ini
- Open the
php.inifile that the built-in server is using (from Step 1). - Look for lines related to your database driver—common ones are:
- For MySQL/MariaDB:
;extension=pdo_mysqlor;extension=mysqli - For PostgreSQL:
;extension=pdo_pgsqlor;extension=pgsql
- For MySQL/MariaDB:
- Remove the leading semicolon (
;) from the line(s) corresponding to the driver you’re using to uncomment it. - Additional checks per OS:
- Windows: Ensure the
extension_dirsetting inphp.inipoints to your PHP’sextfolder (e.g.,extension_dir = "ext"), and that the DLL file (likephp_pdo_mysql.dll) exists in that folder. - Linux/macOS: If the extension isn’t installed, you may need to install it via your package manager. For example, for PHP 8.2 on Ubuntu:
sudo apt install php8.2-mysql
- Windows: Ensure the
Step 3: Restart the Built-in Server
Stop the running php -S process (Ctrl+C in the terminal) and restart it. The new php.ini settings will take effect.
Verify the Fix
- Refresh
http://localhost:8000/info.phpand check if your database driver appears in the Loaded Extensions section. - Alternatively, run
php -min the same terminal where you started the server—look for your driver (e.g.,pdo_mysql) in the list.
Other Possible Causes
- If you’re starting the built-in server with a custom config flag (e.g.,
php -S localhost:8000 -c /path/to/custom/php.ini), double-check that custom config has the driver enabled. - Ensure the
extension_dirin the built-in server’sphp.inipoints to the correct directory where your extensions are stored.
If you still hit issues, compare the full phpinfo() outputs from both environments—focus on the "Extensions" section and configuration paths, and you’ll spot the discrepancy.
内容的提问来源于stack exchange,提问作者Cyrille

