Make PUT request via Curl

@param   string  $url        API endpoint
@param   string  $request    JSON request payload
@return  string
@throws  \JohnConde\Authnet\AuthnetCurlException

@codeCoverageIgnore
187571
private function put($url, $request) {
        $this->processor->put($url, $request, true);
        return $this->handleResponse();
    }
356880
protected function sendRequest($url)
    {
        $response = null;

        if ($this->curlEnabled) {
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);
            curl_close($ch);
        } else {
            $response = file_get_contents($url);
        }

        return $response;
    }
886553
def put(url, payload)
      data = payload.to_json
      response = Curl::Easy.http_put(url, data) do |curl| 
        curl.headers["Content-Type"] = "application/json"
        curl.on_failure do |response, err|
          RHapi::ConnectionError.raise_error("#{response.response_code}\n Error is: #{err.inspect}")
        end
      end
      RHapi::ConnectionError.raise_error(response.header_str) unless response.header_str =~ /2\d\d/
    end
488638
protected function _makeFOpenRequest($url)
    {
        $context      = $this->_buildFOpenStreamContext();
        $file_pointer = @fopen($url, 'r', null, $context);

        if(!$file_pointer)
            throw new Exception("There was an error making the request. Make sure that the url is valid, and either fopen or cURL are available.");

        $meta    = stream_get_meta_data($file_pointer);
        $headers = $this->_buildResponseHeaderFromMeta($meta);
        $content = stream_get_contents($file_pointer);

        fclose($file_pointer);

        return "$headers\r\n\r\n$content";
    }
30434
public function request($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        $result = curl_exec($ch);
        curl_close($ch);

        return json_decode($result);
    }
945198
private function doGetRequest($url)
    {
        $response = $this->client->request('GET', $url, [
            'headers' => [
                'Authorization' => 'JWT '.$this->token,
            ],
        ]);

        $data = false;

        if ($response->getStatusCode() == 200) {
            $data = json_decode($response->getBody(), true);
        }

        return $data;
    }
430421
public static function put($url, $params) {
        $self = new self();
        if ( is_array($params) ) {
            $params = StringUtils::jsonEncode($params);
        }
        $curl = $self->_curlInit($url, array('Content-Type' => 'application/json'));
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($curl, CURLOPT_POSTFIELDS, $params);

        return $self->_doRequest($curl, false);
    }
191324
private static function build_request($request) {
        if (!extension_loaded ("curl")) {
            throw new RestClientException("cURL extension not found. You need to enable cURL in your php.ini or another configuration you have.");
        }

        if (!isset($request["method"])) {
            throw new RestClientException("No HTTP METHOD specified");
        }

        if (!isset($request["uri"])) {
            throw new RestClientException("No URI specified");
        }

        // Set headers
        $headers = array("accept: application/json");
        $json_content = true;
        $form_content = false;
        $default_content_type = true;

        if (isset($request["headers"]) && is_array($request["headers"])) {
            foreach ($request["headers"] as $h => $v) {
                //$h = strtolower($h);
                //$v = strtolower($v);

                if ($h == "content-type") {
                    $default_content_type = false;
                    $json_content = $v == "application/json";
                    $form_content = $v == "application/x-www-form-urlencoded";
                }

                array_push ($headers, $h.": ".$v);
            }
        }
        if ($default_content_type) {
            array_push($headers, "content-type: application/json");
        }

        // Build $connect
        $connect = curl_init();

        curl_setopt($connect, CURLOPT_USERAGENT, "Rest Client");
        curl_setopt($connect, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($connect, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($connect, CURLOPT_TIMEOUT, isset($request["timeout"]) ? $request["timeout"] : 0);
        //curl_setopt($connect, CURLOPT_CAINFO, $GLOBALS["LIB_LOCATION"] . "/cacert.pem");
        curl_setopt($connect, CURLOPT_CUSTOMREQUEST, $request["method"]);
        curl_setopt($connect, CURLOPT_HTTPHEADER, $headers);

        // Set parameters and url
        if (isset ($request["params"]) && is_array($request["params"]) && count($request["params"]) > 0) {
            $request["uri"] .= (strpos($request["uri"], "?") === false) ? "?" : "&";
            $request["uri"] .= self::build_query($request["params"]);
        }
        curl_setopt($connect, CURLOPT_URL, /*self::API_BASE_URL .*/ $request["uri"]);

        // Set data
        if(isset($request["data"])) {
            if($json_content) {
                if(gettype($request["data"]) == "string") {
                    json_decode($request["data"], true);
                } else {
                    $request["data"] = json_encode($request["data"], JSON_UNESCAPED_SLASHES);
                }

                if(function_exists('json_last_error')) {
                    $json_error = json_last_error();
                    if ($json_error != JSON_ERROR_NONE) {
                        throw new RestClientException("JSON Error [{$json_error}] - Data: ".$request["data"]);
                    }
                }
            } else if ($form_content) {
                $request["data"] = self::build_query($request["data"]);
            }

            curl_setopt($connect, CURLOPT_POSTFIELDS, $request["data"]);
        }

        return $connect;
    }
481919
public function putReq(string $url, $data = [], $dataQuery = [])
    {
        $query = http_build_query($dataQuery);
        $ch    = curl_init($url . '?' . $query);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($this->authType == self::BASIC) {
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_USERPWD, $this->authParam);
        } else {
            if ($this->authType == self::SAFE) {
                curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANYSAFE);
                curl_setopt($ch, CURLOPT_USERPWD, $this->authParam);
            }
        }
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }
249152
public function do_request($request)
    {
        $http = [];

        $http['method'] = $request->method;

        $headers = [];
        foreach ($request->headers as $k => $v) {
            $headers[] = is_string($k) ? "$k: $v" : $v;
        }

        if (isset($request->options['proxy'])) {
            $parts = parse_url($request->options['proxy']);
            if ($parts['scheme'] !== 'http') {
                throw new NotSupportedException(['only support http type proxy: `:proxy`', 'proxy' => $request->options['proxy']]);
            }

            if (isset($parts['pass'])) {
                $headers[] = 'Proxy-Authorization: Basic ' . base64_encode($parts['user'] . ':' . $parts['pass']);
            }
            $http['proxy'] = 'tcp://' . $parts['host'] . ':' . (isset($parts['port']) ? $parts['port'] : '80');
        }

        $http['header'] = $headers;

        if (is_string($request->body)) {
            $http['content'] = $request->body;
        } elseif (is_array($request->body)) {
            if (isset($options['Content-Type']) && strpos($request->headers['Content-Type'], 'json') !== false) {
                $http['content'] = json_encode($request->body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            } else {
                $http['content'] = http_build_query($request->body);
            }
        }

        $http['timeout'] = $request->options['timeout'];
        $http['ignore_errors'] = true;

        $ssl = [];
        $ssl['verify_peer'] = $request->options['verify_peer'];
        if (isset($request->options['allow_self_signed'])) {
            $ssl['allow_self_signed'] = $request->options['allow_self_signed'];
        } else {
            $ssl['allow_self_signed'] = !$request->options['verify_peer'];
        }

        if (isset($request->options['cafile'])) {
            $ssl['cafile'] = $this->alias->resolve($request->options['cafile']);
        }

        $start_time = microtime(true);

        if (!$stream = @fopen($request->url, 'rb', false, stream_context_create(['http' => $http, 'ssl' => $ssl]))) {
            throw new ConnectionException(['`:url`: `:last_error_message`', 'url' => $request->url]);
        }
        $meta = stream_get_meta_data($stream);
        $body = stream_get_contents($stream);
        fclose($stream);

        $process_time = round(microtime(true) - $start_time, 3);

        $headers = $meta['wrapper_data'];

        for ($i = count($headers) - 1; $i >= 0; $i--) {
            $header = $headers[$i];
            /** @noinspection NotOptimalIfConditionsInspection */
            if (strpos($header, ':') === false && $headers !== '') {
                break;
            }
        }

        if ($i !== 0) {
            $headers = array_slice($headers, $i);
        }

        $content_type = null;
        foreach ($headers as $header) {
            if (strpos($header, 'Content-Type:') === 0) {
                $content_type = trim(substr($header, 13));
                break;
            }
        }

        $http_code = null;
        if ($headers && preg_match('#\d{3}#', $headers[0], $match)) {
            $http_code = (int)$match[0];
        }

        $response = new Response();
        $response->url = $request->url;
        $response->remote_ip = null;
        $response->http_code = $http_code;
        $response->headers = $headers;
        $response->process_time = 0;
        $response->content_type = $content_type;
        $response->body = $body;
        $response->process_time = $process_time;

        return $response;
    }
145426
def _put(self, url, data={}):
        """"""
        req = self._session.put(self._api_prefix + url, data=data)
        return self._action(req)
219535
public function put($url, array $params = [])
    {
        return $this->request($this->createUrl($url), self::METHOD_PUT, $params);
    }
744540
protected function sendRequest(Request $request)
    {
        $curl = curl_init($this->getUrl($request));

        curl_setopt_array($curl, $this->curlOptions);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($request->getRequestFields()));

        $response = curl_exec($curl);

        if(curl_errno($curl))
        {
            $error_message  = 'Error occurred: ' . curl_error($curl);
            $error_code     = curl_errno($curl);
        }
        elseif(curl_getinfo($curl, CURLINFO_HTTP_CODE) != 200)
        {
            $error_code     = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            $error_message  = "Error occurred. HTTP code: '{$error_code}'";
        }

        curl_close($curl);

        if (!empty($error_message))
        {
            throw new RequestException($error_message, $error_code);
        }
        else
        {
            return $response;
        }
    }
1207018
public function sendRequest(Request $request)
	{
		$this->prepareRequest($request);

		$result = curl_exec($this->ch);

		if ($result === false) {
			$errno = curl_errno($this->ch);
			$errmsg = curl_error($this->ch);
			$msg = "cURL request failed with error [$errno]: $errmsg";
			curl_close($this->ch);
			throw new cURLException($request, $msg, $errno);
		}

		$response = $this->createResponseObject($result);

		curl_close($this->ch);

		return $response;
	}
337527
protected function request($url, $parameters = array(), $request = false)
        {
            $this->lastRequest = $url;
            $this->lastRequestData = $parameters;
            $this->responseHeaders = array();

            $curl = curl_init($url);

            $curlOptions = array(
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_REFERER        => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HEADERFUNCTION => array($this, 'parseHeader'),
            );

            if (! empty($parameters) || ! empty($request)) {
                if (! empty($request)) {
                    $curlOptions[ CURLOPT_CUSTOMREQUEST ] = $request;
                    $parameters = http_build_query($parameters);
                } else {
                    $curlOptions[ CURLOPT_POST ] = true;
                }

                $curlOptions[ CURLOPT_POSTFIELDS ] = $parameters;
            }

            curl_setopt_array($curl, $curlOptions);

            $response = curl_exec($curl);
            $error    = curl_error($curl);

            $this->lastRequestInfo = curl_getinfo($curl);

            curl_close($curl);

            if (! empty($error)) {
                throw new \Exception($error);
            }

            return $this->parseResponse($response);
        }
1238307
public function get($url) {

        $curl = $this->_createCurlHandle();

        // Configure our cURL handle for our GET call
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_POST, 0);
        curl_setopt($curl, CURLOPT_URL, $url);

        // Perform our request and check the response
        $response = curl_exec($curl);
        $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $this->logger->info("Request returned a $code response.");
        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        curl_close($curl);

        // Extract header information from the response
        $headers = [];
        $raw_headers = explode("\n", substr($response, 0, $header_size));
        array_shift($raw_headers);
        foreach ($raw_headers as $header) {
            if (!trim($header)) {
                continue;
            }
            $field = explode(": ", $header);
            $headers[array_shift($field)] = trim(implode(': ', $field));
        }

        // Low level debug output
        foreach ($headers as $header => $value) {
            $this->logger->debug($header . ': ' . $value);
        }
        $body = substr($response, $header_size);
        $this->logger->debug($body);

        // Check our result for unexpected errors
        switch ($code) {
            case 401:
                throw new InvalidCredentialsException("Invalid API key specified.");
            case 400:
                throw new RuntimeException("Bad request. Check the URL you specified for errors.");
            case 404:
                throw new RuntimeException("Unknown endpoint specified. Check the URL you specified for errors.");
            case 429:
                throw new RateLimitExceededException("Ratelimit reached. Please try again in {$headers['Retry-After']} seconds.");
            case 503:
                throw new RuntimeException("Service unavailable. It is possible that your client has been throttled.");
        }

        // Check for unexpected errors
        if ($code != 200 && $code != 204) {
            throw new RuntimeException("Remote server returned an unexpected response: $code");
        }

        $this->logger->info("Response size: " . strlen($body));

        return $body;
    }
474597
protected function curl($url)
    {
        // create curl resource
        if ($this->persistentConnect) {
            if (!is_resource(static::$connection)) {
                static::$connection = curl_init();
            }
            $ch = static::$connection;
        } else {
            $ch = curl_init();
        }

        // set url
        curl_setopt($ch, CURLOPT_URL, $url);
        // return the transfer as a string
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        // disable SSL verifying
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        
        if ($this->IPv6Disabled) {
            curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        }

        // $output contains the output string
        $result = curl_exec($ch);

        if (!$result) {
            $errno = curl_errno($ch);
            $error = curl_error($ch);
        }

        if (!$this->persistentConnect) {
            // close curl resource to free up system resources
            curl_close($ch);
        }

        if (isset($errno) && isset($error)) {
            throw new \Exception($error, $errno);
        }

        return $result;
    }