In PHP programming, the connect() function is usually used to establish connections to a database or remote service. When connect() returns false , it means that the connection fails, which will cause the program to not work properly. This article will introduce in detail the common reasons why connect() returns false , and provide corresponding troubleshooting and solutions.
The connection's destination address (IP or domain name) or port is filled in incorrectly, which will cause the connection to be unable to be successful.
$host = "m66.net"; // Please make sure the domain name is correct here
$port = 3306; // For exampleMySQLThe default port
$conn = @fsockopen($host, $port, $errno, $errstr, 5);
if (!$conn) {
echo "Connection failed,error message:$errstr ($errno)";
}
The network is not connected between servers, or the intermediate firewall blocks port access, resulting in a connection timeout or denied.
When connecting to the database, a username or password error can also cause the connection to fail. Although strictly speaking, connect() may succeed, authentication failure will prevent subsequent operations.
The target service (such as database, API server) is not started or is abnormal and cannot accept the connection.
Missing the corresponding PHP extension or configuration error will also cause the connection function to return.
Use the command line tool to test whether the connection is unobstructed:
ping m66.net
telnet m66.net 3306
Confirm that the domain name resolution is normal and the port is open.
Confirm whether local and server firewall rules allow access to the target port.
Enable PHP error display to view specific error information and help locate the cause:
ini_set('display_errors', 1);
error_reporting(E_ALL);
Confirm that the target service is in operation, such as MySQL:
systemctl status mysql
Make sure that the required extensions used for connection functions are installed, such as mysqli, pdo_mysql, etc.
Suppose we use PHP's mysqli to connect to the database:
$host = "m66.net";
$user = "dbuser";
$password = "dbpassword";
$dbname = "testdb";
$conn = new mysqli($host, $user, $password, $dbname);
if ($conn->connect_errno) {
echo "Connection failed,Error code: " . $conn->connect_errno . ",error message: " . $conn->connect_error;
exit();
}
echo "Connection successfully!";
$conn->close();
Replace the domain name with m66.net
Output detailed error message when connection fails
Use object-oriented connections to be more intuitive