Attempts connection to remote host. Returns TRUE if sucessful.

@return boolean
195605
public function connect() {

        // check if we need to convert host to IP
        if (!preg_match('/([0-9]{1,3}\\.){3,3}[0-9]{1,3}/', $this->host)) {

            $ip = gethostbyname($this->host);

            if ($this->host == $ip) {

                throw new \Exception("Cannot resolve $this->host");
            } else {
                $this->host = $ip;
            }
        }

        // attempt connection
        $this->socket = fsockopen($this->host, $this->port, $this->errno, $this->errstr, $this->timeout);

        if (!$this->socket) {
            throw new \Exception("Cannot connect to " . $this->host . " on port " . $this->port . "\n" . $this->errstr . ": " . $this->errstr);
        }

        return true;
    }
791398
public function connect()
    {
        if ($this->connection) {
            return true;
        }

        $config = $this->config + $this->defaultConfig;

        $dsn = sprintf(
            '%s:host=%s;port=%p;dbname=%s',
            self::DSN_PREFIX,
            $config['host'],
            $config['port'],
            $config['database']
        );

        if ($config['unix_socket']) {
            $dsn = sprintf(
                '%s:unix_socket=%s;dbname=%s',
                self::DSN_PREFIX,
                $config['unix_socket'],
                $config['database']
            );
        }

        $this->connection = new PDO(
            $dsn,
            $config['username'],
            $config['password'],
            $config['options']
        );

        return true;
    }
476018
protected function performConnect()
    {
        // Note: Connecting is briefly described in RFC1777.
        // Basicly it works like this:
        //  1. set up TCP connection
        //  2. secure that connection if neccessary
        //  3a. setLDAPVersion to tell server which version we want to speak
        //  3b. perform bind
        //  3c. setLDAPVersion to tell server which version we want to speak
        //      together with a test for supported versions
        //  4. set additional protocol options

        // Return true if we are already connected.
        if ($this->_link !== false) {
            return true;
        }

        // Connnect to the LDAP server if we are not connected.  Note that
        // with some LDAP clients, ldapperformConnect returns a link value even
        // if no connection is made.  We need to do at least one anonymous
        // bind to ensure that a connection is actually valid.
        //
        // Ref: http://www.php.net/manual/en/function.ldap-connect.php

        // Default error message in case all connection attempts
        // fail but no message is set
        $current_error = new PEAR_Error('Unknown connection error');

        // Catch empty $_host_list arrays.
        if (!is_array($this->_host_list) || count($this->_host_list) == 0) {
            $current_error = PEAR::raiseError('No Servers configured! Please '.
               'pass in an array of servers to Net_LDAP2');
            return $current_error;
        }

        // Cycle through the host list.
        foreach ($this->_host_list as $host) {

            // Ensure we have a valid string for host name
            if (is_array($host)) {
                $current_error = PEAR::raiseError('No Servers configured! '.
                   'Please pass in an one dimensional array of servers to '.
                   'Net_LDAP2! (multidimensional array detected!)');
                continue;
            }

            // Skip this host if it is known to be down.
            if (in_array($host, $this->_down_host_list)) {
                continue;
            }

            // Record the host that we are actually connecting to in case
            // we need it later.
            $this->_config['host'] = $host;

            // Attempt a connection.
            $this->_link = @ldap_connect($host, $this->_config['port']);
            if (false === $this->_link) {
                $current_error = PEAR::raiseError('Could not connect to ' .
                    $host . ':' . $this->_config['port']);
                $this->_down_host_list[] = $host;
                continue;
            }

            // If we're supposed to use TLS, do so before we try to bind,
            // as some strict servers only allow binding via secure connections
            if ($this->_config["starttls"] === true) {
                if (self::isError($msg = $this->startTLS())) {
                    $current_error           = $msg;
                    $this->_link             = false;
                    $this->_down_host_list[] = $host;
                    continue;
                }
            }

            // Try to set the configured LDAP version on the connection if LDAP
            // server needs that before binding (eg OpenLDAP).
            // This could be necessary since rfc-1777 states that the protocol version
            // has to be set at the bind request.
            // We use force here which means that the test in the rootDSE is skipped;
            // this is neccessary, because some strict LDAP servers only allow to
            // read the LDAP rootDSE (which tells us the supported protocol versions)
            // with authenticated clients.
            // This may fail in which case we try again after binding.
            // In this case, most probably the bind() or setLDAPVersion()-call
            // below will also fail, providing error messages.
            $version_set = false;
            $ignored_err = $this->setLDAPVersion(0, true);
            if (!self::isError($ignored_err)) {
                $version_set = true;
            }

            // Attempt to bind to the server. If we have credentials configured,
            // we try to use them, otherwise its an anonymous bind.
            // As stated by RFC-1777, the bind request should be the first
            // operation to be performed after the connection is established.
            // This may give an protocol error if the server does not support
            // V2 binds and the above call to setLDAPVersion() failed.
            // In case the above call failed, we try an V2 bind here and set the
            // version afterwards (with checking to the rootDSE).
            $msg = $this->bind();
            if (self::isError($msg)) {
                // The bind failed, discard link and save error msg.
                // Then record the host as down and try next one
                if ($msg->getCode() == 0x02 && !$version_set) {
                    // provide a finer grained error message
                    // if protocol error arieses because of invalid version
                    $msg = new Net_LDAP2_Error($msg->getMessage().
                        " (could not set LDAP protocol version to ".
                        $this->_config['version'].")",
                        $msg->getCode());
                }
                $this->_link             = false;
                $current_error           = $msg;
                $this->_down_host_list[] = $host;
                continue;
            }

            // Set desired LDAP version if not successfully set before.
            // Here, a check against the rootDSE is performed, so we get a
            // error message if the server does not support the version.
            // The rootDSE entry should tell us which LDAP versions are
            // supported. However, some strict LDAP servers only allow
            // bound suers to read the rootDSE.
            if (!$version_set) {
                if (self::isError($msg = $this->setLDAPVersion())) {
                    $current_error           = $msg;
                    $this->_link             = false;
                    $this->_down_host_list[] = $host;
                    continue;
                }
            }

            // Set LDAP parameters, now we know we have a valid connection.
            if (isset($this->_config['options']) &&
                is_array($this->_config['options']) &&
                count($this->_config['options'])) {
                foreach ($this->_config['options'] as $opt => $val) {
                    $err = $this->setOption($opt, $val);
                    if (self::isError($err)) {
                        $current_error           = $err;
                        $this->_link             = false;
                        $this->_down_host_list[] = $host;
                        continue 2;
                    }
                }
            }

            // At this stage we have connected, bound, and set up options,
            // so we have a known good LDAP server.  Time to go home.
            return true;
        }


        // All connection attempts have failed, return the last error.
        return $current_error;
    }
315057
public function connect(): bool
	{
		if ($this->ssl === true)
		{
			$this->connection = fsockopen('ssl://'.$this->host, $this->port);
		}
		else
		{
			$this->connection = fsockopen($this->host, $this->port);
		}

		return $this->connected();
	}
1178210
public function connect()
    {
        try {
            $this->pdo = new \PDO(
                $this->datasource->getDsn(),
                $this->datasource->getUser(),
                $this->datasource->getPassword(),
                $this->datasource->getOption()
            );
            return true;
        } catch (PDOException $e) {
            throw new \Exception($e->getMessage());
            return false;
        }
    }
937429
protected function connect()
    {
        $rs = false;

        foreach ((array)$this->server as $svr) {
            $error = 0;
            $errstr = '';
            $rs = @fsockopen($svr['host'], $svr['port'], $error, $errstr);

            if ($rs) {
                $this->socket = $rs;

            } else {
                $key = $this->getServerKey(
                    $svr['host'],
                    $svr['port'],
                    $svr['weight']
                );
                $s = "Connect to $key error:" . PHP_EOL .
                    "    [$error] $errstr";
                error_log($s);
            }
        }

        if (is_null($this->socket)) {
            $this->resultCode = Memcached::RES_FAILURE;
            $this->resultMessage = 'No server avaliable.';
            return false;

        } else {
            $this->resultCode = Memcached::RES_SUCCESS;
            $this->resultMessage = '';
            return true;
        }
    }
834075
function isConnected() {
		try {
			return $this->connection->isOpen();
		} catch (SmtpException $ex) {
			$this->log('EOF caught while checking if connected', 'client');
			$this->close();
		}
		return false;
	}
1164152
function _connect()
    {
        if ($this->bitmap & NET_SSH2_MASK_CONSTRUCTOR) {
            return false;
        }

        $this->bitmap |= NET_SSH2_MASK_CONSTRUCTOR;

        $this->curTimeout = $this->timeout;

        $this->last_packet = strtok(microtime(), ' ') + strtok(''); // == microtime(true) in PHP5

        if (!is_resource($this->fsock)) {
            $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838
            // with stream_select a timeout of 0 means that no timeout takes place;
            // with fsockopen a timeout of 0 means that you instantly timeout
            // to resolve this incompatibility a timeout of 100,000 will be used for fsockopen if timeout is 0
            $this->fsock = @fsockopen($this->host, $this->port, $errno, $errstr, $this->curTimeout == 0 ? 100000 : $this->curTimeout);
            if (!$this->fsock) {
                $host = $this->host . ':' . $this->port;
                user_error(rtrim("Cannot connect to $host. Error $errno. $errstr"));
                return false;
            }
            $elapsed = strtok(microtime(), ' ') + strtok('') - $start;

            $this->curTimeout-= $elapsed;

            if ($this->curTimeout <= 0) {
                $this->is_timeout = true;
                return false;
            }
        }

        $this->identifier = $this->_generate_identifier();

        fputs($this->fsock, $this->identifier . "\r\n");

        /* According to the SSH2 specs,

          "The server MAY send other lines of data before sending the version
           string.  Each line SHOULD be terminated by a Carriage Return and Line
           Feed.  Such lines MUST NOT begin with "SSH-", and SHOULD be encoded
           in ISO-10646 UTF-8 [RFC3629] (language is not specified).  Clients
           MUST be able to process such lines." */
        $temp = '';
        $extra = '';
        while (!feof($this->fsock) && !preg_match('#^SSH-(\d\.\d+)#', $temp, $matches)) {
            if (substr($temp, -2) == "\r\n") {
                $extra.= $temp;
                $temp = '';
            }

            if ($this->curTimeout) {
                if ($this->curTimeout < 0) {
                    $this->is_timeout = true;
                    return false;
                }
                $read = array($this->fsock);
                $write = $except = null;
                $start = strtok(microtime(), ' ') + strtok('');
                $sec = floor($this->curTimeout);
                $usec = 1000000 * ($this->curTimeout - $sec);
                // on windows this returns a "Warning: Invalid CRT parameters detected" error
                // the !count() is done as a workaround for <https://bugs.php.net/42682>
                if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) {
                    $this->is_timeout = true;
                    return false;
                }
                $elapsed = strtok(microtime(), ' ') + strtok('') - $start;
                $this->curTimeout-= $elapsed;
            }

            $temp.= fgets($this->fsock, 255);
        }

        if (feof($this->fsock)) {
            user_error('Connection closed by server');
            return false;
        }

        if (defined('NET_SSH2_LOGGING')) {
            $this->_append_log('<-', $extra . $temp);
            $this->_append_log('->', $this->identifier . "\r\n");
        }

        $this->server_identifier = trim($temp, "\r\n");
        if (strlen($extra)) {
            $this->errors[] = utf8_decode($extra);
        }

        if ($matches[1] != '1.99' && $matches[1] != '2.0') {
            user_error("Cannot connect to SSH $matches[1] servers");
            return false;
        }

        $response = $this->_get_binary_packet();
        if ($response === false) {
            user_error('Connection closed by server');
            return false;
        }

        if (!strlen($response) || ord($response[0]) != NET_SSH2_MSG_KEXINIT) {
            user_error('Expected SSH_MSG_KEXINIT');
            return false;
        }

        if (!$this->_key_exchange($response)) {
            return false;
        }

        $this->bitmap|= NET_SSH2_MASK_CONNECTED;

        return true;
    }
305551
public boolean connect() {
        if (client.isConnected()) {
            logger.warn("Already connected");
            return true;
        }
        try {
            logger.info("Connecting to remote host " + remoteHost);
            client.connect(remoteHost);
            client.rlogin(localUser, remoteUser, terminalType);
            writer = new OutputStreamWriter(client.getOutputStream());
            outputReaderThread = new Thread(new OutputReader());
            outputReaderThread.start();
            if (interactive) {
                standardInputReaderThread = new Thread(new StandardInputReader());
                standardInputReaderThread.start();
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException ex) {
            }
            if (client.isConnected()) {
                return true;
            } else {
                logger.fatal("Client has been immediately disconnected from remote host:" + remoteHost);
                return false;
            }
            //outputReaderThread.
        } catch (IOException e) {
            logger.fatal("Could not connect to remote host:" + remoteHost, e);
            return false;
        }
    }
577876
public function isWorking()
    {
        if (empty($_SERVER[self::TEST_SERVER_VAR])
            && empty($_SERVER[self::TEST_SERVER_VAR_ALT])
            && empty($_SERVER[self::TEST_SERVER_VAR_ALT_IPV6])
        ) {
            return Piwik::translate("UserCountry_CannotFindGeoIPServerVar", self::TEST_SERVER_VAR . ' $_SERVER');
        }

        return true; // can't check for another IP
    }
773938
public function connect()
    {
        if ($this->EnableAPCu && extension_loaded('apcu') && ini_get('apc.enabled')) {
            $this->Using = 'APCu';
            return true;
        }
        if ($this->EnableMemcached && extension_loaded('memcached')) {
            $this->WorkingData = new \Memcached();
            if ($this->WorkingData->addServer($this->MemcachedHost, $this->MemcachedPort)) {
                $this->Using = 'Memcached';
                return true;
            }
            $this->WorkingData = null;
        }
        if ($this->EnableRedis && extension_loaded('redis')) {
            $this->WorkingData = new \Redis();
            if ($this->WorkingData->connect($this->RedisHost, $this->RedisPort, $this->RedisTimeout)) {
                $this->Using = 'Redis';
                return true;
            }
            $this->WorkingData = null;
        }
        if ($this->EnablePDO && extension_loaded('pdo')) {
            try {
                $PDO = new \PDO($this->PDOdsn, $this->PDOusername, $this->PDOpassword);
            } catch (\PDOException $Exception) {
                $this->Exceptions[] = $Exception->getMessage();
                return false;
            }
            if (is_object($PDO)) {
                $this->WorkingData = $PDO;
                $this->Using = 'PDO';
                return true;
            }
            unset($PDO);
        }
        if ($this->FFDefault) {
            if (is_file($this->FFDefault)) {
                if (is_readable($this->FFDefault) && is_writable($this->FFDefault)) {
                    $this->Using = 'FF';
                    if (!$Filesize = filesize($this->FFDefault)) {
                        $this->WorkingData = [];
                        return $this->Modified = true;
                    }
                    $Data = '';
                    $Handle = false;
                    $Start = time();
                    while (true) {
                        $Handle = fopen($this->FFDefault, 'rb');
                        if ($Handle !== false || (time() - $Start) > self::FLOCK_TIMEOUT) {
                            break;
                        }
                    }
                    if ($Handle === false) {
                        return false;
                    }
                    $Locked = false;
                    while (true) {
                        if ($Locked = flock($Handle, LOCK_EX | LOCK_NB) || (time() - $Start) > self::FLOCK_TIMEOUT) {
                            break;
                        }
                    }
                    if (!$Locked) {
                        fclose($Handle);
                        return false;
                    }
                    $Size = ($Filesize && self::BLOCKSIZE) ? ceil($Filesize / self::BLOCKSIZE) : 0;
                    $Step = 0;
                    while ($Step < $Size) {
                        $Data .= fread($Handle, self::BLOCKSIZE);
                        $Step++;
                    }
                    flock($Handle, LOCK_UN);
                    fclose($Handle);
                    $Data = $Data ? unserialize($Data) : [];
                    $this->WorkingData = is_array($Data) ? $Data : [];
                    return true;
                }
            } else {
                $Parent = dirname($this->FFDefault);
                if (is_dir($Parent) && is_readable($Parent) && is_writable($Parent)) {
                    $this->WorkingData = [];
                    $this->Using = 'FF';
                    return $this->Modified = true;
                }
            }
            return false;
        }
        return is_array($this->WorkingData);
    }
1101873
protected function _connect(): bool {

		if ($this->_oPDO) {
			return FALSE;
		}

		$sName = $this->_sName;
		$sDSN = $this->_aConfig['dsn'];
		$this->_sPrevPrepareQuery = NULL;
		$this->_oPrevPrepare = NULL;

		try {

			$this->_oPDO = new \PDO(
				$this->_aConfig['dsn'],
				$this->_aConfig['user'],
				$this->_aConfig['password'],
				$this->_aConfig['option']
			);

		} catch (\Throwable $e) {

			$sError = 'MySQL Connect fail, Database "' . $sName . '"' . "\n"
				. $e->getMessage() . "\n"
				. 'DSN ' . $sDSN;
			throw new TangoException($sError, 2);
		}
		return TRUE;
	}
924868
public static function get()
    {
        $possibleKeys = [
            'HTTP_X_FORWARDED_FOR',
            'HTTP_X_FORWARDED',
            'HTTP_X_CLUSTER_CLIENT_IP',
            'HTTP_FORWARDED_FOR',
            'HTTP_FORWARDED',
            'HTTP_VIA',
            'HTTP_X_COMING_FROM',
            'HTTP_COMING_FROM',
            'HTTP_X_REAL_IP',
            'REMOTE_ADDR',
        ];

        foreach ($possibleKeys as $key) {
            if ($ip = static::getGlobalValue($key)) {
                return $ip;
            }
        }

        return false;
    }
600032
protected function checkConnection()
    {
        // If the connection could not be established, fsockopen sadly does not
        // only return false (as documented), but also always issues a warning.
        if ( ( $this->connection === null ) &&
             ( ( $this->connection = @fsockopen( $this->options['ip'], $this->options['port'], $errno, $errstr ) ) === false ) )
        {
            // This is a bit hackisch...
            $this->connection = null;
            throw new phpillowConnectionException(
                "Could not connect to server at %ip:%port: '%errno: %error'",
                array(
                    'ip'    => $this->options['ip'],
                    'port'  => $this->options['port'],
                    'error' => $errstr,
                    'errno' => $errno,
                )
            );
        }
    }
281346
function _connect(&$fp)
	{
		if(!empty($this->proxy_host) && !empty($this->proxy_port))
		{
			$this->_isproxy = true;

			$host = $this->proxy_host;
			$port = $this->proxy_port;
		}
		else
		{
			$host = $this->host;
			$port = $this->port;
		}

		$this->status = 0;

		if($fp = fsockopen(
				$host,
				$port,
				$errno,
				$errstr,
				$this->_fp_timeout
		))
		{
			// socket connection succeeded

			return true;
		}
		else
		{
			// socket connection failed
			$this->status = $errno;
			switch($errno)
			{
				case -3:
					$this->error="socket creation failed (-3)";
				case -4:
					$this->error="dns lookup failure (-4)";
				case -5:
					$this->error="connection refused or timed out (-5)";
				default:
					$this->error="connection failed (".$errno.")";
			}
			return false;
		}
	}
1014840
public function connect()
        {
            // check if non-SSL connection
            if(!static::$ssl) {
                // attempt connection
                if(!static::$_stream = ftp_connect(static::$_host, static::$_port, static::$_timeout)) {
                    // set last error
                    static::$error = "Failed to connect to {static::$_host}";
                    return false;
                }
            // SSL connection
            } elseif(function_exists("ftp_ssl_connect")) {
                // attempt SSL connection
                if(!static::$_stream = ftp_ssl_connect(static::$_host, static::$_port, static::$_timeout)) {
                    // set last error
                    static::$error = "Failed to connect to {static::$_host} (SSL connection)";
                    return false;
                }
            // invalid connection type
            } else {
                static::$error = "Failed to connect to {static::$_host} (invalid connection type)";
                return false;
            }

            // attempt login
            if(ftp_login(static::$_stream, static::$_user, static::$_pwd)) {
                // set passive mode
                ftp_pasv(static::$_stream, (bool)static::$passive);

                // set system type
                static::$systemType = ftp_systype(static::$_stream);

                // connection successful
                return true;
            // login failed
            } else {
                static::$error = "Failed to connect to {static::$_host} (login failed)";
                return false;
            }
        }
920694
public function ping(): bool
    {
        parent::connect();

        if ($this->_conn instanceof Driver\PingableConnection) {
            return $this->_conn->ping();
        }

        try {
            parent::query($this->getDatabasePlatform()->getDummySelectSQL());

            return true;
        } catch (DBALException $e) {
            return false;
        }
    }