Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

A PHP/MySQL error that says Connection timed out almost always means the client could not complete a TCP connection or MySQL handshake. Start with the server’s listening address, network route, firewall, security group, and MySQL account host permission; changing PHP timeout values cannot repair a blocked port. If the message is Lost connection to MySQL server, a connection existed and then dropped, so investigate idle and data-transfer timeouts instead.

Identify which timeout you actually have

Read the complete error text before changing configuration. Similar wording describes different failure stages, and each stage has a different fix.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Error pattern What happened First things to check
Connection timed out while connecting The TCP connection or MySQL handshake did not complete. Hostname resolution, route, server listening address, TCP port 3306, firewalls, cloud security groups, account host permission, and the connect timeout.
Can't connect to MySQL server The client could not establish a session. The accompanying code may distinguish refusal, timeout, or name-resolution failure. Test the host and port from the PHP machine, then inspect bind and firewall settings.
Lost connection to MySQL server A session was established and later closed or became unusable. wait_timeout, stale persistent sockets, server restarts, network interruptions, and read/write timeouts.
Lost connection to MySQL server during query (commonly error 2013) The connection dropped while sending a query or receiving its result. net_read_timeout, net_write_timeout, oversized results, long-running work, and intermediary network devices.

Do not treat an initial connect timeout as an idle-session problem. The server cannot apply wait_timeout to a connection that never reached the server.

Use a short, deterministic diagnostic order

  1. Test from the PHP host. Run the MySQL command-line client on the same machine, container, or virtual network where PHP runs. This removes browser, application, and DNS assumptions from the first test.
  2. Check the exact endpoint. Confirm the hostname resolves to the intended private or public address and that the configured port is 3306 unless your server uses another port.
  3. Test the port before changing timeouts. A timeout from the command-line client indicates a path, listener, firewall, or access-control problem. Fix that layer first.
  4. Only after a successful connection, reproduce the PHP failure. Then decide whether the failure occurs during the handshake, while idle, or during data transfer.
  5. Inspect server logs and variables. Look for refused connections, bind errors, restarts, inactivity disconnects, and packet-transfer failures at the time of the request.

Run a command-line connection test

From the PHP server, use a deliberately short test:

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application:Upgraded attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Warranty & Support: Our Electric air duster comes with 5 years warranty and 24/7 customer service. During this period, if you have any questions,pls kindly feel free to contact us.
mysql -h <mysql-host> -u <user> -p --connect-timeout=30

Enter the password when prompted. A successful login proves that the host can reach MySQL and that the supplied account is accepted from that machine. It does not prove that your PHP process uses the same DNS name, network namespace, credentials, or port.

The --connect-timeout option is available on current MySQL clients; support was reported as added in MySQL 8.0.18, so older client binaries may reject it. MySQL Shell expresses its connect timeout in milliseconds and uses 10,000 ms by default, while the C API option uses seconds. Do not copy a value between clients without checking the unit.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Make MySQL listen on the remote interface

bind_address controls which local interfaces accept MySQL connections. MySQL 8.0 server documentation reports a wildcard default of *, but packaged distributions often place an explicit 127.0.0.1 in their configuration. Check the running server instead of assuming either value.

Check the effective bind setting

On the database host, inspect the active configuration and process arguments. If you can log in locally, run:

SHOW VARIABLES LIKE 'bind_address';

If the value is 127.0.0.1, MySQL is reachable only from the database host. Set an address that includes the interface used by the PHP server, then restart MySQL using your operating system’s service manager. Bind only to the required private interface when possible; a wildcard listener increases the number of interfaces that must be protected by firewall rules.

Since MySQL 8.0.13, a comma-separated list of addresses is supported. A list that includes a wildcard is invalid, and the server will not start if the bind configuration fails. Validate the service status and error log immediately after every change.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth

Confirm the listener, not just the configuration file

A correct-looking file is not proof that the running process loaded it. Verify that a MySQL process is listening on the expected address and port with the host’s socket-inspection tool. If it listens only on loopback, fix the selected configuration file or startup profile. If it listens on the right interface but remote tests still time out, continue with firewall and routing checks.

Open the network path to TCP 3306

Remote access can be blocked at several independent layers:

  • The database host’s local firewall may deny inbound TCP 3306.
  • A cloud security group, network ACL, or hosting-provider firewall may deny the source address.
  • A private-network route may be missing between the PHP and database subnets.
  • Container or virtualization networking may expose a different address than the host configuration.
  • An outbound policy on the PHP host may prevent connections to the database network.

Permit only the PHP host’s fixed private address or subnet where feasible. Avoid exposing MySQL directly to the public internet merely to make a timeout disappear. After changing a rule, rerun the command-line test from the PHP host; a port test from your laptop does not represent the application’s route.

Check the MySQL account’s allowed host

MySQL accounts include both a user name and a host pattern. An account created for 'app'@'localhost' is not automatically the same account as 'app'@'10.0.0.5'. The PHP machine’s source address must match an account that is permitted to connect and has the required privileges.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Ask a database administrator to inspect the account rows and create or alter a least-privilege account for the PHP host. Use a narrow host value or controlled subnet rather than an unrestricted wildcard. The exact account and privilege statements vary with your MySQL version and security policy, so apply them through your normal change process and verify the resulting host entry with SHOW GRANTS.

An account or grant mismatch commonly produces an immediate access-denied response rather than a silent timeout. However, firewalls and security devices can conceal that response, so verify both the network path and account host independently.

Rank #3
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.

Understand MySQL’s server-side timeout variables

Variable Scope of the timer Reported default or behavior When to change it
connect_timeout Initial client handshake 10 seconds by default; high-latency or multi-proxy paths may need roughly 15–30 seconds. Only after routing, listener, firewall, and grants are correct and the handshake genuinely needs more time.
wait_timeout Idle established sessions Eight hours of inactivity by default. Since MySQL 8.0.24, the server reports that the client was disconnected because of inactivity before closing it. Set a value that matches your pool or application lifecycle; do not use it to fix an initial connect timeout.
net_read_timeout Waiting to read data during an active exchange Applies while data is being transferred, not while a session is simply idle. Consider it for slow uploads or long result transfers after confirming the network is stable.
net_write_timeout Waiting to write data during an active exchange Applies while sending data to the client, not to idle connections. Consider it when the client or an intermediary consumes large results slowly.

Inspect the current values

Run the following on the target server, replacing the variable name as needed:

SHOW VARIABLES LIKE 'connect_timeout';
SHOW VARIABLES LIKE 'wait_timeout';
SHOW VARIABLES LIKE 'net_read_timeout';
SHOW VARIABLES LIKE 'net_write_timeout';

Session and global values can differ. Check the value relevant to the PHP session, and record the current setting before changing it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Make a server-side change persistent

For a permanent change, place the setting under the [mysqld] section of the server configuration file: typically my.cnf on Unix-like systems or my.ini on Windows. Restart MySQL and verify the effective value with SHOW VARIABLES. A setting written to the wrong configuration file, or placed under a client section, will not affect the server.

Raise one timer at a time and observe connection behavior. Very large values can leave broken sessions hanging, consume threads, and delay detection of network failures. Prefer fixing a slow query, unstable route, or undersized connection pool over making every timeout effectively infinite.

Set the mysqli connect timeout correctly in PHP

With mysqli, set connection options after mysqli_init() and before mysqli_real_connect(). The timeout value must be an integer; passing a string has caused bogus timeout behavior in PHP bug reports.

<?php
$mysqli = mysqli_init();
if ($mysqli === false) {
    throw new RuntimeException('mysqli_init failed');
}

$connectTimeout = 30; // integer seconds
if (!mysqli_options($mysqli, MYSQLI_OPT_CONNECT_TIMEOUT, $connectTimeout)) {
    throw new RuntimeException('Could not set connect timeout');
}

// Available since PHP 7.2.0; applies while waiting for command results.
mysqli_options($mysqli, MYSQLI_OPT_READ_TIMEOUT, 60);

$ok = mysqli_real_connect(
    $mysqli,
    $host,
    $user,
    $password,
    $database,
    3306,
    null,
    0
);

if (!$ok) {
    throw new RuntimeException(mysqli_connect_error());
}

MYSQLI_OPT_CONNECT_TIMEOUT controls the connection attempt. MYSQLI_OPT_READ_TIMEOUT, available since PHP 7.2.0, addresses stalls while waiting for command results after the session is open. It does not open a blocked firewall port and does not replace server-side transfer settings.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.

Do not set options on an already-open connection

Calling mysqli_options() after mysqli_real_connect() is too late for the handshake. If your framework creates the connection internally, find the framework’s pre-connect hook or construct the mysqli object yourself so the option is applied at the required point.

Use integer values and log the effective failure

Keep the timeout as an integer number of seconds, not a quoted value such as '30'. Log the host, port, elapsed time, and mysqli error code without logging the password. This distinguishes a consistent 30-second network wait from an immediate authentication rejection.

Handle dropped and stale connections

Persistent connections can retain a socket that MySQL has already closed. The next request may receive a lost-connection error even though the server is healthy. On failure, discard the object and establish a fresh connection; do not blindly retry every write because a request may have been partially executed.

If you use a pool, configure its maximum lifetime below the server’s idle policy or validate a connection before borrowing it. Keep application-level idle limits aligned with wait_timeout. A server restart, failover, or network interruption also requires reconnect logic regardless of the configured idle timer.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Fix timeouts that occur during a query

When the initial login succeeds but a query later fails, capture the query duration, result size, and exact error text. A transfer can stall while the server reads request data or writes a large result, which is where net_read_timeout and net_write_timeout apply.

  • Reduce unnecessarily large result sets with selective columns, filtering, pagination, or streaming APIs.
  • Inspect slow queries and missing indexes instead of treating database work as a network timeout.
  • Check whether a reverse proxy, VPN, NAT device, or load balancer has a shorter idle or request limit.
  • Increase transfer timers only enough to cover the measured operation, then retest under realistic load.

A query that runs longer than the client’s read timeout can look like a lost connection even though MySQL is still working. Capture server activity before increasing limits so that a slow plan is not hidden by a larger timeout.

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.

Apply changes safely in configuration files

  1. Back up the active MySQL configuration and record current variable values.
  2. Confirm which file the service actually loads and place server variables under [mysqld].
  3. Change one setting, restart MySQL during a maintenance window, and verify service health.
  4. Run SHOW VARIABLES and the remote command-line test from the PHP host.
  5. Exercise a real PHP request, including an idle period if that is where the failure occurs.
  6. Review logs and roll back the change if connection counts, latency, or resource usage worsen.

Common symptoms and targeted fixes

The command-line client also times out

Stay on the infrastructure path: verify DNS, route, bind address, listener port, local firewall, cloud security group, and account host. PHP configuration is not yet the primary suspect.

The command-line client connects, but PHP times out

Compare PHP’s resolved hostname, port, credentials, and network namespace with the successful shell test. Then verify that MYSQLI_OPT_CONNECT_TIMEOUT is set before mysqli_real_connect() and receives an integer.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

PHP works once, then fails after idling

Inspect wait_timeout, pool lifetime, and persistent-connection reuse. Reconnect stale sockets and align client recycling with the server’s inactivity policy.

Only large or slow queries fail

Measure query and transfer time, inspect net_read_timeout and net_write_timeout, and check intermediary limits. Optimize or stream the result before raising timers.

MySQL will not start after changing bind_address

Undo the change or correct the address list. MySQL 8.0.13 and later allow comma-separated addresses, but a list containing a wildcard is invalid. Read the startup error log and confirm that every address belongs to a local interface.

Network fixes versus timeout tuning

Approach Use it when What it can and cannot solve
Bind, firewall, route, and grant correction The PHP host cannot establish a TCP session or the server never sees the request. Restores reachability and authorization; it is the required fix for a blocked path.
Server connect_timeout The path works but the handshake needs more time because of measured latency or proxies. Allows a slow handshake; it cannot create a listener or bypass a firewall.
PHP MYSQLI_OPT_CONNECT_TIMEOUT You need a bounded client-side wait for the initial connection. Controls how long PHP waits; it does not alter server reachability.
wait_timeout and reconnect logic An established connection is closed after inactivity or a pool reuses stale sockets. Addresses idle-session lifecycle; it does not fix a first-connection timeout.
net_read_timeout and net_write_timeout Active requests or result transfers stall. Addresses data movement after login; it does not govern idle sessions.

What not to change

  • Do not expose port 3306 publicly as a substitute for a private route and restricted firewall rule.
  • Do not set every timeout to hours or disable timeouts without measuring the failure stage.
  • Do not assume the MySQL 8.0 bind default applies to a packaged installation; inspect the effective value.
  • Do not use the obsolete PHP mysql extension’s settings as if they applied to mysqli or PDO.
  • Do not copy PDO connect-timeout examples without checking the PDO driver documentation for your PHP version; the syntax is driver-specific and is not established here.

Final verification checklist

  • The PHP host resolves the intended database address.
  • A MySQL client from the PHP host reaches the expected port.
  • MySQL listens on the interface used by the application.
  • Local and cloud firewalls permit TCP traffic from the PHP host only.
  • The MySQL account has a host entry matching the PHP machine and least-privilege grants.
  • mysqli options are applied between initialization and mysqli_real_connect(), with integer seconds.
  • Idle failures are handled with appropriate wait_timeout and reconnect logic.
  • Mid-query failures are investigated with transfer timers, query performance, result size, and intermediary limits.
  • Every configuration change is verified after restart and tested from the application’s actual network location.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.