wpdb::parse_db_host() WordPress Method

The wpdb::parse_db_host() method is used to parse a database host string. This is useful when you need to connect to a database on a different host.

wpdb::parse_db_host( string $host ) #

Parses the DB_HOST setting to interpret it for mysqli_real_connect().


Description

mysqli_real_connect() doesn’t support the host param including a port or socket like mysql_connect() does. This duplicates how mysql_connect() detects a port and/or socket file.


Top ↑

Parameters

$host

(string)(Required)The DB_HOST setting to parse.


Top ↑

Return

(array|false) Array containing the host, the port, the socket and whether it is an IPv6 address, in that order. False if the host couldn't be parsed.

  • (string) Host name.
  • '1'
    (string|null) Port.
  • '2'
    (string|null) Socket.
  • '3'
    (bool) Whether it is an IPv6 address.


Top ↑

Source

File: wp-includes/wp-db.php

	public function parse_db_host( $host ) {
		$port    = null;
		$socket  = null;
		$is_ipv6 = false;

		// First peel off the socket parameter from the right, if it exists.
		$socket_pos = strpos( $host, ':/' );
		if ( false !== $socket_pos ) {
			$socket = substr( $host, $socket_pos + 1 );
			$host   = substr( $host, 0, $socket_pos );
		}

		// We need to check for an IPv6 address first.
		// An IPv6 address will always contain at least two colons.
		if ( substr_count( $host, ':' ) > 1 ) {
			$pattern = '#^(?:\[)?(?P<host>[0-9a-fA-F:]+)(?:\]:(?P<port>[\d]+))?#';
			$is_ipv6 = true;
		} else {
			// We seem to be dealing with an IPv4 address.
			$pattern = '#^(?P<host>[^:/]*)(?::(?P<port>[\d]+))?#';
		}

		$matches = array();
		$result  = preg_match( $pattern, $host, $matches );

		if ( 1 !== $result ) {
			// Couldn't parse the address, bail.
			return false;
		}

		$host = '';
		foreach ( array( 'host', 'port' ) as $component ) {
			if ( ! empty( $matches[ $component ] ) ) {
				$$component = $matches[ $component ];
			}
		}

		return array( $host, $port, $socket, $is_ipv6 );
	}


Top ↑

Changelog

Changelog
VersionDescription
4.9.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.