Establishes connection
@throws \Grace\DBAL\Exception\ConnectionException
186871
private function connect($selectDb = true)
    {
        if (!$this->isPhpEnvironmentSupported()) {
            throw new ConnectionException("Function mysqli_connect doesn't exist");
        }

        //Can throw warning, if have incorrect connection params
        //So we need '@'
        $this->getLogger()->startConnection('Mysqli connection');
        $this->dbh = @mysqli_connect($this->host, $this->user, $this->password, $selectDb ? $this->database : null, (int)$this->port);
        $this->getLogger()->stopConnection();

        if (mysqli_connect_error()) {
            throw new ConnectionException('Error ' . mysqli_connect_errno() . ' - ' . mysqli_connect_error());
        }

        $this->getLogger()->startConnection('Setting utf8 charset');
        $this->dbh->query("SET character SET 'utf8'");
        $this->dbh->query('SET character_set_client = utf8');
        $this->dbh->query('SET character_set_results = utf8');
        $this->dbh->query('SET character_set_connection = utf8');
        $this->dbh->query("SET SESSION collation_connection = 'utf8_general_ci'");
        $this->dbh->query("SET sql_mode = 'ANSI'");
        $this->getLogger()->stopConnection();
    }
987387
public function connect()
    {
        $connection = null;

        /**
         * @todo we need a SQLLogger that logs to a (CSV?) file, as we probably do not want to log into the database.
         *
         * $configuration->setSQLLogger(new EchoSQLLogger());
         */

        try {
            $connection = $this->getConnectionFromDriverManager();
            $connection->connect();

            $this->setConnection($connection);

            $this->ensureConnectionIsEstablished($connection);
        } catch (DBALException $exception) {
            $exception = $this->convertException($exception);
            $this->handleException($exception);
        } catch (PDOException $exception) {
            $exception = $this->convertException($exception);
            $this->handleException($exception);
        }
    }
307554
public function connect()
    {
        $config = $this->getConfig();
        if(isset($config['database']['database'])) {
            $conn = $this->instanceConnector();
            $host = $config['database']['hostname'];
            $user = $config['database']['username'];
            $pass = $config['database']['password'];
            if ($conn->connect($host, $user, $pass)) {
                $this->connection = $conn;
                $this->createCache();
                return true;
            }
            $err = $conn->getLastError();
            throw new \Exception(sprintf('Can not establish connection to database! {host=%s, user=%s, database=%s} Error: %s',
                        $config['database']['hostname'], $config['database']['username'], $config['database']['database'], $err));
        }

        return false;

//        if (!$this->connection) {
//
//            if ($conn->connect()
//            ) {
//                if ($conn->select_database($config['database']['database'])) {
//                    $this->connection = $conn;
//                    self::$selected = true;
//                    $this->createCache();
////
////                    if (!defined("GL_INSTALL") || !GL_INSTALL) {
////                        $this->checkDatabaseStructure();
////                    }
//                    return true;
//                }
//                return false;
//            } else {
//                $err =$conn->getLastError();
//                throw new \Exception(sprintf('Can not establish connection to database! {host=%s, user=%s, database=%s} Error: %s',
//                    $config['database']['hostname'], $config['database']['username'], $config['database']['database'], $err));
//            }
//        }
//        return true;
    }
1110033
public static function connect() :void {

		// configure the database and get the dns
		$dsn = self::configureAndGetDSN();

		// try to connect
		self::$_handle = new \PDO(
			$dsn, 
			self::$_config['username'] ?: null, 
			self::$_config['password'] ?: null
		);

		// check if connection the connexion failed
		if(!self::$_handle) {
			// throw an exception if it failed
			Throw new Exception('Database::connect() : Failed to connect', 500);
		}

		// if a before statement has to be executed
		if(self::$_config['before']) {
			// execute the before statement
			self::$_handle->query(self::$_config['before']);
		}
	}
1205419
public function connect() {
		if ($this->connection->isConnected()) return true;
		$this->connection->connect();
		$response = $this->connection->sendRequest(
			RequestFactory::startup($this->options)
		);
		$responseType = $response->getType();
		switch($responseType) {
			case OpcodeEnum::ERROR:
				throw new ConnectionException($response->getData());

			case OpcodeEnum::AUTHENTICATE:
				$nodeOptions = $this->connection->getNode()->getOptions();
				$response = $this->connection->sendRequest(
					RequestFactory::credentials(
						$nodeOptions['username'],
						$nodeOptions['password']
					)
				);
				$responseType = $response->getType();
		}
		if ($responseType === OpcodeEnum::ERROR) throw new ConnectionException($response->getData());
		if (!empty($this->keyspace)) $this->setKeyspace($this->keyspace);

		return true;
	}
1249244
void establishConnection () throws IOException {
        synchronized (operationOnConnectionMonitor) {
            if (state == State.CLOSED) {
                throw new IOException("Attempt to establish a connection with a closed connection factory");
            } else if (state == State.CONNECTED) {
                LOGGER.warn("Establishing new connection although a connection is already established");
            }
            try {
                LOGGER.info("Trying to establish connection to {}:{}", getHost(), getPort());
                connection = super.newConnection(executorService);
                connection.addShutdownListener(connectionShutdownListener);
                LOGGER.info("Established connection to {}:{}", getHost(), getPort());
                changeState(State.CONNECTED);
            } catch (IOException e) {
                LOGGER.error("Failed to establish connection to {}:{}", getHost(), getPort());
                throw e;
            }
        }
    }
536763
protected function _connect()
    {
        if ($this->_connection) {
            return;
        }

        if (!extension_loaded('mysqli')) {
            /**
             * @see Zend_Db_Adapter_Mysqli_Exception
             */
            // require_once 'Zend/Db/Adapter/Mysqli/Exception.php';
            throw new Zend_Db_Adapter_Mysqli_Exception('The Mysqli extension is required for this adapter but the extension is not loaded');
        }

        if (isset($this->_config['port'])) {
            $port = (integer) $this->_config['port'];
        } else {
            $port = null;
        }

        $this->_connection = mysqli_init();

        $enable_ssl = false;
        $ssl_options = array (
            'ssl_ca' => null,
            'ssl_ca_path' => null,
            'ssl_cert' => null,
            'ssl_cipher' => null,
            'ssl_key' => null,
        );

        if(!empty($this->_config['driver_options'])) {
            foreach($this->_config['driver_options'] as $option=>$value) {
                if(array_key_exists($option, $ssl_options)) {
                    $ssl_options[$option] = $value;
                    $enable_ssl = true;
                } elseif(is_string($option)) {
                    // Suppress warnings here
                    // Ignore it if it's not a valid constant
                    $option = @constant(strtoupper($option));
                    if($option === null)
                        continue;
                }
                mysqli_options($this->_connection, $option, $value);
            }
        }


        if ($enable_ssl) {
            mysqli_ssl_set(
                $this->_connection,
                $ssl_options['ssl_key'],
                $ssl_options['ssl_cert'],
                $ssl_options['ssl_ca'],
                $ssl_options['ssl_ca_path'],
                $ssl_options['ssl_cipher']
            );
        }

        $flags = null;
        if ($enable_ssl) {
            $flags = MYSQLI_CLIENT_SSL;
            if (!empty($this->_config['driver_options']['ssl_no_verify'])
                && defined('MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT')
            ) {
                $flags = MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
            }
        }

        // Suppress connection warnings here.
        // Throw an exception instead.
        $_isConnected = @mysqli_real_connect(
            $this->_connection,
            $this->_config['host'],
            $this->_config['username'],
            $this->_config['password'],
            $this->_config['dbname'],
            $port,
            $socket = null,
            $enable_ssl ? $flags : null
        );

        if ($_isConnected === false || mysqli_connect_errno()) {

            $this->closeConnection();
            /**
             * @see Zend_Db_Adapter_Mysqli_Exception
             */
            // require_once 'Zend/Db/Adapter/Mysqli/Exception.php';
            throw new Zend_Db_Adapter_Mysqli_Exception(mysqli_connect_error());
        }

        if (!empty($this->_config['charset'])) {
            mysqli_set_charset($this->_connection, $this->_config['charset']);
        }
    }
43534
public function connect()
	{
		if ($this->_connection)
		{
			return;
		}

		// Extract the connection parameters, adding required variabels
		extract($this->_config['connection'] + array(
			'dsn'        => '',
			'username'   => null,
			'password'   => null,
			'persistent' => false,
			'compress'   => false,
		));

		// determine db type
		$_dsn_find_collon = strpos($dsn, ':');
		$this->_db_type = $_dsn_find_collon ? substr($dsn, 0, $_dsn_find_collon) : null;

		// Force PDO to use exceptions for all errors
		$attrs = array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION);

		if ( ! empty($persistent))
		{
			// Make the connection persistent
			$attrs[\PDO::ATTR_PERSISTENT] = true;
		}

		if (in_array(strtolower($this->_db_type), array('mysql', 'mysqli')) and $compress)
		{
			// Use client compression with mysql or mysqli (doesn't work with mysqlnd)
			$attrs[\PDO::MYSQL_ATTR_COMPRESS] = true;
		}

		// add the charset to the DSN if needed
		if ( ! empty($this->_config['charset']) and strpos($dsn, ';charset=') === false and strtolower($this->_db_type) != 'sqlite')
		{
			$dsn .= ';charset='.$this->_config['charset'];
		}

		try
		{
			// Create a new PDO connection
			$this->_connection = new \PDO($dsn, $username, $password, $attrs);
		}
		catch (\PDOException $e)
		{
			// and convert the exception in a database exception
			if ( ! is_numeric($error_code = $e->getCode()))
			{
				if ($this->_connection)
				{
					$error_code = $this->_connection->errorinfo();
					$error_code = $error_code[1];
				}
				else
				{
					$error_code = 0;
				}
			}
			throw new \Database_Exception(str_replace($password, str_repeat('*', 10), $e->getMessage()), $error_code, $e);
		}

		if ( ! empty($this->_config['charset']))
		{
			// Set the character set
			$this->set_charset($this->_config['charset']);
		}
	}
1013428
public function connect() {
    // Check that the SQLite3 extension is installed.
    if (!class_exists('SQLite3')) {
      throw new Exceptions\UnableToConnectException(
          'SQLite3 PHP extension is not available. It probably has not '.
          'been installed. Please install and configure it in order to use '.
          'SQLite3.'
      );
    }
    $filename = $this->config['SQLite3']['filename'];
    $busyTimeout = $this->config['SQLite3']['busy_timeout'];
    $openFlags = $this->config['SQLite3']['open_flags'];
    $encryptionKey = $this->config['SQLite3']['encryption_key'];
    // Connecting
    if (!$this->connected) {
      $this->link = new SQLite3($filename, $openFlags, $encryptionKey);
      if ($this->link) {
        $this->connected = true;
        $this->link->busyTimeout($busyTimeout);
        // Set database and connection options.
        $this->link->exec("PRAGMA encoding = \"UTF-8\";");
        $this->link->exec("PRAGMA foreign_keys = 1;");
        $this->link->exec("PRAGMA case_sensitive_like = 1;");
        // Create the preg_match and regexp functions.
        // TODO(hperrin): Add more of these functions to get rid of post-query checks.
        $this->link->createFunction('preg_match', 'preg_match', 2, SQLITE3_DETERMINISTIC);
        $this->link->createFunction('regexp', function ($pattern, $subject) {
          return !!$this->posixRegexMatch($pattern, $subject);
        }, 2, SQLITE3_DETERMINISTIC);
      } else {
        $this->connected = false;
        if ($filename === ':memory:') {
          throw new Exceptions\NotConfiguredException();
        } else {
          throw new Exceptions\UnableToConnectException('Could not connect.');
        }
      }
    }
    return $this->connected;
  }
123256
public function _connect()
    {
        if ($this->_connection) {
            return;
        }
        parent::_connect();

        $this->getConnection()->setAttribute(Zend_Db::ATTR_STRINGIFY_FETCHES, true);

        try {
            if ($this->_serverType === null) {
                $server = substr($this->getConnection()->getAttribute(PDO::ATTR_SERVER_INFO), 0, 3);

                switch ($server) {
                    case 'DB2':
                        $this->_serverType = new Zend_Db_Adapter_Pdo_Ibm_Db2($this);

                        // Add DB2-specific numeric types
                        $this->_numericDataTypes['DECFLOAT'] = Zend_Db::FLOAT_TYPE;
                        $this->_numericDataTypes['DOUBLE']   = Zend_Db::FLOAT_TYPE;
                        $this->_numericDataTypes['NUM']      = Zend_Db::FLOAT_TYPE;

                        break;
                    case 'IDS':
                        $this->_serverType = new Zend_Db_Adapter_Pdo_Ibm_Ids($this);

                        // Add IDS-specific numeric types
                        $this->_numericDataTypes['SERIAL']       = Zend_Db::INT_TYPE;
                        $this->_numericDataTypes['SERIAL8']      = Zend_Db::BIGINT_TYPE;
                        $this->_numericDataTypes['INT8']         = Zend_Db::BIGINT_TYPE;
                        $this->_numericDataTypes['SMALLFLOAT']   = Zend_Db::FLOAT_TYPE;
                        $this->_numericDataTypes['MONEY']        = Zend_Db::FLOAT_TYPE;

                        break;
                    }
            }
        } catch (PDOException $e) {
            /** @see Zend_Db_Adapter_Exception */
            // require_once 'Zend/Db/Adapter/Exception.php';
            $error = strpos($e->getMessage(), 'driver does not support that attribute');
            if ($error) {
                throw new Zend_Db_Adapter_Exception("PDO_IBM driver extension is downlevel.  Please use driver release version 1.2.1 or later", 0, $e);
            } else {
                throw new Zend_Db_Adapter_Exception($e->getMessage(), $e->getCode(), $e);
            }
        }
    }
404396
protected function connect() {
        $db = Config::config()['user']['database'];

        if ($db['enabled']) {
            switch ($db['driver']) {
                case 'pdo' :
                    $options = [Pdo::ATTR_STATEMENT_CLASS => ['\Gcs\Framework\Core\Pdo\PdoStatement', []]];

                    switch ($db['type']) {
                        case 'mysql':
                            try {
                                $this->db = new Pdo('mysql:host=' . $db['hostname'] . ';dbname=' . $db['database'], $db['username'], $db['password'], $options);
                                //self::$sql->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                                $this->db->exec('SET NAMES ' . strtoupper($db['charset']));
                            }
                            catch (\PDOException $e) {
                                throw new MissingDatabaseException($e->getMessage() . ' / ' . $e->getCode() . ' / ' . $e->getFile());
                            }
                            break;

                        case 'pgsql':
                            try {
                                $this->db = new Pdo('mysql:host=' . $db['hostname'] . ';dbname=' . $db['database'], $db['username'], $db['password'], $options);
                                //self::$sql->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                                $this->db->exec('SET NAMES ' . strtoupper($db['charset']));
                            }
                            catch (\PDOException $e) {
                                throw new MissingDatabaseException($e->getMessage() . ' / ' . $e->getCode());
                            }
                            break;

                        default :
                            throw new MissingDatabaseException("Can't connect to SQL Database because the driver is not supported");
                            break;
                    }
                    break;

                default :
                    throw new MissingDatabaseException("Can't connect to SQL Database because the API is unrecognized");
                    break;
            }

            return $this->db;
        }
        else {
            return null;
        }
    }
890812
public function connect(): void
    {
        // no need to get excited
        if ($this->isConnected()) {
            return;
        }

        // export credentials & others
        [$host, $name, $username, $password] = [
            $this->config['host'], $this->config['name'],
            $this->config['username'], $this->config['password'],
        ];
        $port = (int) $this->config['port'];
        $socket = (string) $this->config['socket'];

        // call big boss
        $resource = mysqli_init();

        // supported constants: http://php.net/mysqli.options
        if (isset($this->config['options'])) {
            foreach ($this->config['options'] as $option => $value) {
                if (!$resource->options($option, $value)) {
                    throw new ConnectionException("Setting '{$option}' option failed!");
                }
            }
        }

        // start connection profile
        $this->profiler && $this->profiler->start('connection');

        $resourceStatus =@ $resource->real_connect($host, $username, $password, $name, $port, $socket);
        if (!$resourceStatus) {
            $error = $this->parseConnectionError();
            throw new ConnectionException($error['message'], $error['code'], $error['sql_state']);
        }

        // finish connection profile
        $this->profiler && $this->profiler->end('connection');

        // log with info level
        $this->logger && $this->logger->log(Logger::INFO, sprintf('New connection via %s addr.', Util::getIp()));

        // set charset for connection
        if (isset($this->config['charset'])) {
            $run = $resource->set_charset($this->config['charset']);
            if (!$run) {
                throw new ConnectionException(sprintf('Unable to connect to MySQL server at "%s", '.
                    'invalid or not-supported character set "%s" given!', $this->config['host'], $this->config['charset']),
                        $resource->errno, SqlState::OPPA_CHARSET_ERROR);
            }
        }

        // set timezone for connection
        if (isset($this->config['timezone'])) {
            $run = $resource->query('SET time_zone = \''. $resource->real_escape_string($this->config['timezone']) .'\'');
            if (!$run) {
                throw new ConnectionException(sprintf('Unable to connect to MySQL server at "%s", '.
                    'invalid or not-supported timezone "%s" given.', $this->config['host'], $this->config['timezone']),
                        $resource->errno, SqlState::OPPA_TIMEZONE_ERROR);
            }
        }

        // assign resource
        $this->resource = new Resource($resource);

        // fill mapper map for once
        if ($this->mapper) {
            $map = $cache = null;
            if ($this->config['map_result_cache']) {
                $cache = new Cache();
                $cache->read('mapper.map', $map, true, $this->config['map_result_cache_ttl']);
            }

            if ($map == null) {
                try {
                    $result = $this->query("SELECT table_name, column_name, data_type, is_nullable, numeric_precision, character_maximum_length FROM information_schema.columns WHERE table_schema = '{$name}'", null, -1, 2);
                    if ($result->count()) {
                        $map = [];
                        foreach ($result->items() as $item) {
                            $item = (object) array_change_key_case($item); // normalize key cases

                            $length = null;
                            if ($item->data_type == 'bit') { // for only bools
                                $length = (int) $item->numeric_precision;
                            } elseif (substr($item->data_type, -4) == 'char') { // for extra (char) crop
                                $length = (int) $item->character_maximum_length;
                            }

                            $map[$item->table_name][$item->column_name] = [
                                /* type */ Mapper::normalizeType($item->data_type, $length),
                                /* length */ $length,
                                /* nullable */ ($item->is_nullable == 'YES'),
                            ];
                        }

                        $cache && $cache->write('mapper.map', $map);
                    }
                    $result->reset();
                } catch (QueryException $e) {
                    throw new QueryException('Could not retrieve schema info for mapper!', null,
                        SqlState::OPPA_CONNECTION_ERROR, $e);
                }
            }

            // set map
            $this->mapper->setMap($map);
        }
    }
952829
public function connect() {
    // Check that the PostgreSQL extension is installed.
    if (!is_callable('pg_connect')) {
      throw new Exceptions\UnableToConnectException(
          'PostgreSQL PHP extension is not available. It probably has not '.
          'been installed. Please install and configure it in order to use '.
          'PostgreSQL.'
      );
    }
    $connectionType = $this->config['PostgreSQL']['connection_type'];
    $host = $this->config['PostgreSQL']['host'];
    $port = $this->config['PostgreSQL']['port'];
    $user = $this->config['PostgreSQL']['user'];
    $password = $this->config['PostgreSQL']['password'];
    $database = $this->config['PostgreSQL']['database'];
    // Connecting, selecting database
    if (!$this->connected) {
      if ($connectionType === 'host') {
        $connectString = 'host=\''.addslashes($host).
            '\' port=\''.addslashes($port).
            '\' dbname=\''.addslashes($database).
            '\' user=\''.addslashes($user).
            '\' password=\''.addslashes($password).
            '\' connect_timeout=5';
      } else {
        $connectString = 'dbname=\''.addslashes($database).
            '\' user=\''.addslashes($user).
            '\' password=\''.addslashes($password).
            '\' connect_timeout=5';
      }
      if ($this->config['PostgreSQL']['allow_persistent']) {
        $this->link = pg_connect(
            $connectString.
                ' options=\'-c enable_hashjoin=off -c enable_mergejoin=off\''
        );
      } else {
        $this->link = pg_connect(
            $connectString.
                ' options=\'-c enable_hashjoin=off -c enable_mergejoin=off\'',
            PGSQL_CONNECT_FORCE_NEW
        );
        // Don't think this is necessary, but if put in options, will guarantee
        // connection is new. " -c timezone='.round(rand(10001000, 10009999)).'"
      }
      if ($this->link) {
        $this->connected = true;
      } else {
        $this->connected = false;
        if ($host === 'localhost'
            && $user === 'nymph'
            && $password === 'password'
            && $database === 'nymph'
            && $connectionType === 'host') {
          throw new Exceptions\NotConfiguredException();
        } else {
          throw new Exceptions\UnableToConnectException(
              'Could not connect: '.
                  pg_last_error()
          );
        }
      }
    }
    return $this->connected;
  }
1272939
protected function startConnection()
    {

        $this->initSettings();

        $this->prefix = $this->settings['prefix'];

        $con = $this->settings['connection.type'] . ':host=' . $this->settings['connection.host'] . ';dbname=' . $this->settings['connection.dbname'] . "";
        try {
            $this->connection = new \PDO($con, $this->settings['authontification.user'], $this->settings['authontification.password'], array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
        } catch (\Exception $ex) {
            throw new \OWeb\Exception("Couldn't connect to DB : " . $con, 0, $ex);
        }
        $this->done = true;
    }
1239469
protected function connect(): void
    {
        $this->connection = @\stream_socket_client( // @ is escalated to exception
            ($this->secure === 'ssl' ? 'ssl://' : '') . $this->host . ':' . $this->port,
            $errno, $error, $this->timeout, STREAM_CLIENT_CONNECT, $this->context
        );
        if (!$this->connection) {
            throw new SmtpException($error ?: error_get_last()['message'], $errno);
        }
        \stream_set_timeout($this->connection, $this->timeout, 0);
        $this->read(); // greeting

        $this->write("EHLO {$this->clientHost}");
        $ehloResponse = $this->read();
        if ((int) $ehloResponse !== 250) {
            $this->write("HELO {$this->clientHost}", 250);
        }

        if ($this->secure === 'tls') {
            $this->write('STARTTLS', 220);
            if (!\stream_socket_enable_crypto($this->connection, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
                throw new SmtpException('Unable to connect via TLS.');
            }
            $this->write("EHLO {$this->clientHost}", 250);
        }

        $password = $this->getPassword();
        if ($this->username !== '' && $password !== '') {
            $authMechanisms = [];
            if (\preg_match('~^250[ -]AUTH (.*)$~im', $ehloResponse, $matches)) {
                $authMechanisms = \explode(' ', \trim($matches[1]));
            }

            if (\in_array('PLAIN', $authMechanisms, true)) {
                $credentials = $this->username . "\0" . $this->username . "\0" . $password;
                $this->write('AUTH PLAIN ' . \base64_encode($credentials), 235, 'PLAIN credentials');
            } else {
                $this->write('AUTH LOGIN', 334);
                $this->write(\base64_encode($this->username), 334, 'username');
                $this->write(\base64_encode($password), 235, 'password');
            }
        }
    }
980696
protected function connect()
    {
        // Build a database connection if we don't have one connected

        $adapter = '\\Pixie\\ConnectionAdapters\\' . ucfirst(strtolower($this->adapter));

        $adapterInstance = $this->container->build($adapter, array($this->container));

        $pdo = $adapterInstance->connect($this->adapterConfig);
        $this->setPdoInstance($pdo);

        // Preserve the first database connection with a static property
        if (!static::$storedConnection) {
            static::$storedConnection = $this;
        }
    }
235578
public function establish() {

                // Check whether the socket is already connected
                if( isset($this->established) && $this->established ) {
                        return true;
                }
                
		// Try to open the socket connection to MPD with a 5 second timeout
		if( !$this->socket = @fsockopen( $this->host, $this->port, $errn, $errs, 5 ) ) {

			// Throw an MPDConnectionException along with the connection errors
			throw new MPDConnectionException( 'Connection failed: '.$errs, self::MPD_CONNECTION_FAILED );
		}

                // Clear connection messages
                while( !feof( $this->socket ) ) {

                        $response = trim( fgets( $this->socket ) );

                        // If the connection messages have cleared
                        if( strncmp( self::MPD_OK, $response, strlen( self::MPD_OK ) ) == 0 ) {

				// Successully connected
                                $this->established = true;

                                // Parse the MPD version from the response and replace the ending 0 with an x 
                                $this->version = preg_replace('/[0]$/','x', current( sscanf( $response, self::MPD_OK . " MPD %s\n" )));

				// Connected successfully
				return true;
                        }

                        // Check to see if there is a connection error message that was sent in the response
                        if( strncmp( self::MPD_ERROR, $response, strlen( self::MPD_ERROR ) ) == 0 ) {

				// Parse out the error message from the response
                                preg_match( '/^ACK \[(.*?)\@(.*?)\] \{(.*?)\} (.*?)$/', $response, $matches );

				// Throw an exception and include the response errors
                                throw new MPDConnectionException( 'Connection failed: '.$matches[4], self::MPD_CONNECTION_FAILED );
                        }
                }
      
		// Throw a general connection failed exception 
		throw new MPDConnectionException( 'Connection failed', self::MPD_CONNECTION_FAILED );
        }