PHP5.6+mysqlnd环境下如何增大PDO最大缓冲区大小?
Fixing "max_allowed_packet" Error with PHP 5.6, PDO (mysqlnd) and AWS MySQL
I’ve dealt with this exact issue before—since you’re using mysqlnd (the default PDO driver in PHP 5.6), the MYSQL_ATTR_MAX_BUFFER_SIZE flag is indeed ignored. Here’s how to properly increase the buffer size on both the server and client sides:
1. Adjust the MySQL Server (AWS RDS/EC2)
First, you need to make sure the MySQL server allows larger packets. For AWS setups:
- For AWS RDS: Go to your RDS dashboard, open the parameter group linked to your instance, find the
max_allowed_packetparameter, and set it to a value that fits your needs (e.g.,67108864for 64MB). Save the parameter group and restart your RDS instance (some parameters require a reboot to take full effect). - Temporary test fix: If you need an immediate workaround, connect to your MySQL server via CLI and run:
Keep in mind this resets when the server restarts, so don’t rely on it for long-term use.SET GLOBAL max_allowed_packet = 67108864;
2. Configure PHP (mysqlnd) Client
Since MYSQL_ATTR_MAX_BUFFER_SIZE doesn’t work with mysqlnd, use these client-side settings:
- Edit php.ini: Add or update the
mysqlnd.net_read_buffer_sizedirective to match your server’smax_allowed_packetvalue. For example:
Restart your PHP-FPM or Apache service after making this change.mysqlnd.net_read_buffer_size = 67108864 - Session-level override in PDO: To ensure the active database session uses the correct packet size, add an init command to your PDO connection:
$dsn = 'mysql:host=your-aws-mysql-host;dbname=your_database'; $username = 'your_user'; $password = 'your_pass'; $options = [ PDO::MYSQL_ATTR_INIT_COMMAND => 'SET SESSION max_allowed_packet = 67108864', PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ]; try { $pdo = new PDO($dsn, $username, $password, $options); } catch (PDOException $e) { die("Connection failed: " . $e->getMessage()); }
Key Notes
- Always ensure the server’s
max_allowed_packetis at least as large as the client’smysqlnd.net_read_buffer_size—otherwise the error will persist. - If you’re inserting large BLOBs or handling file uploads, also check PHP’s
post_max_sizeandupload_max_filesizedirectives (these control HTTP request sizes, not database packets, but they’re often linked to this scenario). - Confirm mysqlnd is enabled by checking your
phpinfo()output—look for the dedicated "mysqlnd" section.
内容的提问来源于stack exchange,提问作者Joris
相关产品推荐
相关产品推荐

