[^:]+)$/', $host, $matches)) { $host = null; $socket = $matches['socket']; $port = null; } // It's an IPv4 address with or without port elseif (preg_match('/^(?P((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(:(?P.+))?$/', $host, $matches)) { $host = $matches['host']; if (!empty($matches['port'])) { $port = $matches['port']; } } // Square-bracketed IPv6 address with or without port, e.g. [fe80:102::2%eth1]:3306 elseif (preg_match('/^(?P\[.*\])(:(?P.+))?$/', $host, $matches)) { $host = $matches['host']; if (!empty($matches['port'])) { $port = $matches['port']; } } // Named host (e.g example.com or localhost) with or without port elseif (preg_match('/^(?P(\w+:\/{2,3})?[a-z0-9\.\-]+)(:(?P[^:]+))?$/i', $host, $matches)) { $host = $matches['host']; if (!empty($matches['port'])) { $port = $matches['port']; } } // Empty host, just port, e.g. ':3306' elseif (preg_match('/^:(?P[^:]+)$/', $host, $matches)) { $host = '127.0.0.1'; $port = $matches['port']; } // ... else we assume normal (naked) IPv6 address, so host and port stay as they are or default // If there is both a valid port and a valid socket we will choose the socket instead if (is_numeric($port) && !empty($socket)) { $port = null; } // Get the port number or socket name if (is_numeric($port)) { $port = (int) $port; $socket = ''; } elseif (is_string($port) && empty($socket)) { $socket = $port; $port = null; } // If there is a socket the hostname must be null if (!empty($socket)) { $host = null; } // If there is a socket the port must be null if (!empty($socket)) { $port = null; } // If there is a numeric port and the hostname is 'localhost' convert to 127.0.0.1 if (is_numeric($port) && ($host === 'localhost')) { $host = '127.0.0.1'; } /** * Special case: MySQL sockets on Windows need to be enclosed with parentheses and have \\.\ in front. * * @see https://dev.mysql.com/doc/mysql-shell/8.0/en/mysql-shell-connection-socket.html * @see https://www.php.net/manual/en/mysqli.quickstart.connections.php */ if (!empty($socket) && $isNamedPipe) { $host = '.'; /** * Remove any existing parentheses, otherwise URL-decode the socket (in case it was given in the correct * percent encoded format). */ if (substr($socket, 0, 1) === '(' && substr($socket, -1) === ')') { $socket = substr($socket, 1, -1); } else { $socket = rawurldecode($socket); } // If the socket doesn't already start with \\.\ add it if (substr($socket, 0, 4) !== '\\\\.\\') { $socket = '\\\\.\\' . $socket; } $socket = '(' . $socket . ')'; } // Finally, if it's a persistent connection we have to prefix the hostname with 'p:' $host = ($isPersistent && $host !== null) ? "p:$host" : $host; } }