Read response from server

@return string
774461
public function read()
    {
        // First, read headers only
        $response = '';
        $gotStatus = false;
        while ($line = @fgets($this->socket)) {
            $gotStatus = $gotStatus || (strpos($line, 'HTTP') !== false);
            if ($gotStatus) {
                $response .= $line;
                if (!chop($line)) { break;
                }
            }
        }

        $statusCode = Zend_Http_Response::extractCode($response);
         
        // Handle 100 and 101 responses internally by restarting the read again
        if ($statusCode == 100 || $statusCode == 101) { return $this->read();
        }

        /**
         * Responses to HEAD requests and 204 or 304 responses are not expected
         * to have a body - stop reading here
         */
        if ($statusCode == 304 || $statusCode == 204  
            || $this->method == Zend_Http_Client::HEAD
        ) { return $response;
        }

        // Check headers to see what kind of connection / transfer encoding we have
        $headers = Zend_Http_Response::extractHeaders($response);

        // if the connection is set to close, just read until socket closes
        if (isset($headers['connection']) && $headers['connection'] == 'close') {
            while ($buff = @fread($this->socket, 8192)) {
                $response .= $buff;
            }

            $this->close();

            // Else, if we got a transfer-encoding header (chunked body)
        } elseif (isset($headers['transfer-encoding'])) {
            if ($headers['transfer-encoding'] == 'chunked') {
                do {
                    $chunk = '';
                    $line = @fgets($this->socket);
                    $chunk .= $line;

                    $hexchunksize = ltrim(chop($line), '0');
                    $hexchunksize = strlen($hexchunksize) ? strtolower($hexchunksize) : 0;

                    $chunksize = hexdec(chop($line));
                    if (dechex($chunksize) != $hexchunksize) {
                        @fclose($this->socket);
                        include_once 'Zend/Http/Client/Adapter/Exception.php';
                        throw new Zend_Http_Client_Adapter_Exception(
                            'Invalid chunk size "' .
                            $hexchunksize . '" unable to read chunked body'
                        );
                    }

                    $left_to_read = $chunksize;
                    while ($left_to_read > 0) {
                        $line = @fread($this->socket, $left_to_read);
                        $chunk .= $line;
                        $left_to_read -= strlen($line);
                    }

                    $chunk .= @fgets($this->socket);
                    $response .= $chunk;
                } while ($chunksize > 0);
            } else {
                throw new Zend_Http_Client_Adapter_Exception(
                    'Cannot handle "' .
                    $headers['transfer-encoding'] . '" transfer encoding'
                );
            }

            // Else, if we got the content-length header, read this number of bytes
        } elseif (isset($headers['content-length'])) {
            $left_to_read = $headers['content-length'];
            $chunk = '';
            while ($left_to_read > 0) {
                $chunk = @fread($this->socket, $left_to_read);
                $left_to_read -= strlen($chunk);
                $response .= $chunk;
            }
        
            // Fallback: just read the response (should not happen)
        } else {
            while ($buff = @fread($this->socket, 8192)) {
                $response .= $buff;
            }

            $this->close();
        }

        return $response;
    }
488575
public function getJsonResponse()
    {
        $json = json_decode($this->httpResponse);
        if (is_null($json) && json_last_error() != JSON_ERROR_NONE) {
            return null; // decode error
        } else {
            return is_object($json) ? $json : null;
        }
    }
265753
protected function processResponse()
    {
        $body = $this->response->getBody();

        // Look for UTF-8 BOM and remove.
        if (0 === strpos(bin2hex(substr($body, 0, 4)), 'efbbbf')) {
            $body = substr($body, 3);
        }

        $parsedResponse = \json_decode($body);

        // Test if return a valid JSON.
        if (JSON_ERROR_NONE !== json_last_error()) {
            $message = function_exists('json_last_error_msg') ? json_last_error_msg() : 'Invalid JSON returned';
            throw new HttpClientException(
                sprintf('JSON ERROR: %s', $message),
                $this->response->getCode(),
                $this->request,
                $this->response
            );
        }

        $this->lookForErrors($parsedResponse);

        return $parsedResponse;
    }
197025
private function interpretResponseXML()
    {
        $this->debug_echo("\n\nResponse (xml):\n".$this->state['response']['body_raw']);

        $this->state['response']['body'] = $this->state['response']['body_raw'];

        if ($this->state['response']['code'] < 200 ||
            $this->state['response']['code'] >= 300
        ) {
            $this->handleHttpError();
        }

        return $this->state;
    }
1194476
protected function getResponse()
    {
        if ($this->response === null) {
            $this->response = $this->client->send($this->request);
        }

        return $this->response;
    }
377079
private function read()
    {
        // Fetch session cookie
        $sessionId = isset($_COOKIE[$this->cookieName]) ? $_COOKIE[$this->cookieName] : false;

        // Cookie does not exist
        if (!$sessionId) {
            return false;
        }

        $this->sessionId = $sessionId;

        // Fetch the session from the database
        $stmt = $this->db->prepare("SELECT data, user_agent, ip_address, time_updated FROM {$this->tableName} WHERE session_id = ?");
        $stmt->execute([$this->sessionId]);

        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        // Run validations if a session exists
        if ($result !== false && !empty($result)) {
            // Check if the session has expired in the database
            if ($this->expireOnClose === false && ($result['time_updated'] + $this->secondsUntilExpiration) < $this->now) {
                $this->destroy();
                return false;
            }

            // Check if the IP address matches the one saved in the database
            if ($this->checkIpAddress === true && $result['ip_address'] !== $this->ipAddress) {
                $this->destroy();
                return false;
            }

            // Check if the user agent matches the one saved in the database
            if ($this->checkUserAgent === true && $result['user_agent'] !== $this->userAgent) {
                $this->destroy();
                return false;
            }

            // Is it time to regenerate the session ID?
            if (($result['time_updated'] + $this->renewalTime) < $this->now) {
                $this->regenerateId();
            }

            // Make stored user data available
            if ($sessionData = json_decode($result['data'], true)) {
                $this->data = isset($sessionData['data']) ? $sessionData['data'] : [];
                $this->lastFlashData = isset($sessionData['flash']) ? $sessionData['flash'] : [];

                unset($sessionData);
            }

            // We have a valid session
            return true;
        }

        // No session found
        return false;
    }
674754
private function readContent(): bool
    {
        $rawContent = $this->getRequest()->getRawContent();
        if ($rawContent === '') {
            $this->content = null;

            return true;
        }

        $this->content = json_decode($rawContent, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $this->getResponse()->setStatusCode(new StatusCode(StatusCode::BAD_REQUEST));

            return false;
        }

        return true;
    }
1084326
public function processResponse()
    {
        if (empty($this->packets_response)) {
            return [];
        }

        // Implode and rip out the JSON
        preg_match('/\{(.*)\}/ms', implode('', $this->packets_response), $matches);

        // Return should be JSON, let's validate
        if (!isset($matches[0]) || ($json = json_decode($matches[0])) === null) {
            throw new Exception("JSON response from Eco server is invalid.");
        }

        $result = new Result();

        // Server is always dedicated
        $result->add('dedicated', 1);

        foreach ($json->Info as $info => $setting) {
            $result->add(strtolower($info), $setting);
        }

        return $result->fetch();
    }
753657
protected function getResponse()
	{
		$response = trim($this->connection->readLine());

		switch(substr($response, 0, 1))
		{
			case '-': // error reply
				return $this->handleErrorResponse($response);
				break;
			case '+': // status reply
				return $this->handleStatusResponse($response);
				break;
			case ':': // integer reply
				return $this->handleIntegerResponse($response);
				break;
			case '$': // bulk reply
				return $this->handleBulkResponse($response);
				break;
			case '*': // multi-bulk reply
				return $this->handleMultiBulkResponse($response);
				break;
			default:
				throw new RedisException(vsprintf('Unable to handle server response [ %s ].', [$response]));
		}
	}
88777
private function readPacket()
    {
        //get packet size.
        $size_data = fread($this->socket, 4);
        $size_pack = unpack('V1size', $size_data);
        $size = $size_pack['size'];

        // if size is > 4096, the response will be in multiple packets.
        // this needs to be address. get more info about multi-packet responses
        // from the RCON protocol specification at
        // https://developer.valvesoftware.com/wiki/Source_RCON_Protocol
        // currently, this script does not support multi-packet responses.

        $packet_data = fread($this->socket, $size);
        $packet_pack = unpack('V1id/V1type/a*body', $packet_data);

        return $packet_pack;
    }
363715
public function readString()
    {
        if (!is_resource($this->fp)) {
            return $this->raiseError('not connected');
        }

        $string = '';
        while (($char = @fread($this->fp, 1)) !== "\x00") {
            $string .= $char;
        }

        return $string;
    }
1257865
private function read(): string
    {
        $this->lastResponse = fread($this->stream, 1024); // Read up to 1KB
        $this->lastResponseCode = intval(explode(" ", $this->lastResponse)[0]);
        $this->lastResponseCode = $this->lastResponseCode > 0 ? $this->lastResponseCode : -1;
        return $this->lastResponse;
    }
481504
public function read() {
		if (!is_resource($this->_resource)) {
			return false;
		}
		$meta = stream_get_meta_data($this->_resource);
		if (isset($meta['wrapper_data'])) {
			$headers = join("\r\n", $meta['wrapper_data']) . "\r\n\r\n";
		} else {
			$headers = null;
		}
		return $headers . stream_get_contents($this->_resource);
	}
850411
public function getResponse()
	{
		$query = '';
		if (sizeof($this->parameters) > 0)
		{
			$query = substr($this->uri, -1) !== '?' ? '?' : '&';
			foreach ($this->parameters as $var => $value)
				if ($value == null || $value == '') $query .= $var.'&';
				else $query .= $var.'='.rawurlencode($value).'&';
			$query = substr($query, 0, -1);
			$this->uri .= $query;

			if (array_key_exists('acl', $this->parameters) ||
			array_key_exists('location', $this->parameters) ||
			array_key_exists('torrent', $this->parameters) ||
			array_key_exists('website', $this->parameters) ||
			array_key_exists('logging', $this->parameters))
				$this->resource .= $query;
		}
		$url = (S3::$useSSL ? 'https://' : 'http://') . ($this->headers['Host'] !== '' ? $this->headers['Host'] : $this->endpoint) . $this->uri;

		//var_dump('bucket: ' . $this->bucket, 'uri: ' . $this->uri, 'resource: ' . $this->resource, 'url: ' . $url);

		// Basic setup
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_USERAGENT, 'S3/php');

		if (S3::$useSSL)
		{
			// Set protocol version
			curl_setopt($curl, CURLOPT_SSLVERSION, S3::$useSSLVersion);

			// SSL Validation can now be optional for those with broken OpenSSL installations
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, S3::$useSSLValidation ? 2 : 0);
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, S3::$useSSLValidation ? 1 : 0);

			if (S3::$sslKey !== null) curl_setopt($curl, CURLOPT_SSLKEY, S3::$sslKey);
			if (S3::$sslCert !== null) curl_setopt($curl, CURLOPT_SSLCERT, S3::$sslCert);
			if (S3::$sslCACert !== null) curl_setopt($curl, CURLOPT_CAINFO, S3::$sslCACert);
		}

		curl_setopt($curl, CURLOPT_URL, $url);

		if (S3::$proxy != null && isset(S3::$proxy['host']))
		{
			curl_setopt($curl, CURLOPT_PROXY, S3::$proxy['host']);
			curl_setopt($curl, CURLOPT_PROXYTYPE, S3::$proxy['type']);
			if (isset(S3::$proxy['user'], S3::$proxy['pass']) && S3::$proxy['user'] != null && S3::$proxy['pass'] != null)
				curl_setopt($curl, CURLOPT_PROXYUSERPWD, sprintf('%s:%s', S3::$proxy['user'], S3::$proxy['pass']));
		}

		// Headers
		$headers = array(); $amz = array();
		foreach ($this->amzHeaders as $header => $value)
			if (strlen($value) > 0) $headers[] = $header.': '.$value;
		foreach ($this->headers as $header => $value)
			if (strlen($value) > 0) $headers[] = $header.': '.$value;

		// Collect AMZ headers for signature
		foreach ($this->amzHeaders as $header => $value)
			if (strlen($value) > 0) $amz[] = strtolower($header).':'.$value;

		// AMZ headers must be sorted
		if (sizeof($amz) > 0)
		{
			//sort($amz);
			usort($amz, array(&$this, '__sortMetaHeadersCmp'));
			$amz = "\n".implode("\n", $amz);
		} else $amz = '';

		if (S3::hasAuth())
		{
			// Authorization string (CloudFront stringToSign should only contain a date)
			if ($this->headers['Host'] == 'cloudfront.amazonaws.com')
				$headers[] = 'Authorization: ' . S3::__getSignature($this->headers['Date']);
			else
			{
				$headers[] = 'Authorization: ' . S3::__getSignature(
					$this->verb."\n".
					$this->headers['Content-MD5']."\n".
					$this->headers['Content-Type']."\n".
					$this->headers['Date'].$amz."\n".
					$this->resource
				);
			}
		}

		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
		curl_setopt($curl, CURLOPT_WRITEFUNCTION, array(&$this, '__responseWriteCallback'));
		curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this, '__responseHeaderCallback'));
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);

		// Request types
		switch ($this->verb)
		{
			case 'GET': break;
			case 'PUT': case 'POST': // POST only used for CloudFront
				if ($this->fp !== false)
				{
					curl_setopt($curl, CURLOPT_PUT, true);
					curl_setopt($curl, CURLOPT_INFILE, $this->fp);
					if ($this->size >= 0)
						curl_setopt($curl, CURLOPT_INFILESIZE, $this->size);
				}
				elseif ($this->data !== false)
				{
					curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->verb);
					curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data);
				}
				else
					curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->verb);
			break;
			case 'HEAD':
				curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'HEAD');
				curl_setopt($curl, CURLOPT_NOBODY, true);
			break;
			case 'DELETE':
				curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
			break;
			default: break;
		}

		// Execute, grab errors
		if (curl_exec($curl))
			$this->response->code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		else
			$this->response->error = array(
				'code' => curl_errno($curl),
				'message' => curl_error($curl),
				'resource' => $this->resource
			);

		@curl_close($curl);

		// Parse body into XML
		if ($this->response->error === false && isset($this->response->headers['type']) &&
		$this->response->headers['type'] == 'application/xml' && isset($this->response->body))
		{
			$this->response->body = simplexml_load_string($this->response->body);

			// Grab S3 errors
			if (!in_array($this->response->code, array(200, 204, 206)) &&
			isset($this->response->body->Code, $this->response->body->Message))
			{
				$this->response->error = array(
					'code' => (string)$this->response->body->Code,
					'message' => (string)$this->response->body->Message
				);
				if (isset($this->response->body->Resource))
					$this->response->error['resource'] = (string)$this->response->body->Resource;
				unset($this->response->body);
			}
		}

		// Clean up file resources
		if ($this->fp !== false && is_resource($this->fp)) fclose($this->fp);

		return $this->response;
	}
1089269
function response()
    {
        if (!$this->response) {
            $settings = new DataParseResponsePhp;
            $response = new HttpResponse(
                new BuildHttpResponse( BuildHttpResponse::parseWith($settings) )
            );

            $this->response = $response;
        }

        return $this->response;
    }
790865
public function listAction()
    {
        $response = $this->getResponse();
        $response->setStatusCode(200);
        $headers = $response->getHeaders();
        $headers->addHeaderLine('Cache-Control', 'public, max-age=86400');
        $headers->addHeaderLine('Expires', date(DATE_RFC822, strtotime("1 day")));


        $key = strtolower($this->getEvent()->getRouteMatch()->getParam('key'));
        $locale = $this->getEvent()->getRouteMatch()->getParam('locale');

        if (strlen($key)<=2) {
            $response->setContent(json_encode(array('status' => 1, 'message' => "The key length should be greater than 3!")));
        
            return $response;
        }

        $translatesSelected = array();
        if (empty($locale)) {
            $locale = 'en_UK';
        }
        $translatesSelected = array();
        $translates = $this->getTranslateService()->readLanguageFile($locale);
        if ($translates) {
            foreach ($translates as $translateKey => $translateValue) {
                $pattern = "/^".$key."/";
                if (preg_match($pattern, strtolower($translateKey))) {
                    $translatesSelected[$translateKey] = $translateValue;
                }
            }
        }

        $return['status'] = 0;
        $return['translates'] = $translatesSelected;

        $response->setContent(json_encode($return));
        
        return $response;
    }
833590
public function getResponseData(): Response
    {
        $connectionResponse = new ConnectionResponseImpl();
        $errorResponse = $this->streamSocket->read();
        if ($errorResponse !== null) {
            $this->getLogger()->error('Send error: ' . $errorResponse);
            $this->streamSocket->disconnect();
            $response = @unpack('Ccommand/Cstatus/Nidentifier', $errorResponse);
            if (!empty($response)) {
                $connectionResponse->setErrorResponse($response);
            } else {
                $connectionResponse->setErrorResponse(null);
            }
        }

        return $connectionResponse;
    }