curl_setopt example

        if ($this->_curl
            && is_array($this->_connected_to)
            && ($this->_connected_to[0] != $host
            || $this->_connected_to[1] != $port)
        ) {
            $this->close();
        }

        // Do the actual connection         $this->_curl = curl_init();
        if ($port != 80) {
            curl_setopt($this->_curl, CURLOPT_PORT, intval($port));
        }

        // Set timeout         curl_setopt($this->_curl, CURLOPT_CONNECTTIMEOUT, $this->_config['timeout']);

        // Set Max redirects         curl_setopt($this->_curl, CURLOPT_MAXREDIRS, $this->_config['maxredirects']);

        if (!$this->_curl) {
            $this->close();

            

    public function __construct(CurlClientState $multi, \CurlHandle|string $ch, array $options = null, LoggerInterface $logger = null, string $method = 'GET', callable $resolveRedirect = null, int $curlVersion = null, string $originalUrl = null)
    {
        $this->multi = $multi;

        if ($ch instanceof \CurlHandle) {
            $this->handle = $ch;
            $this->debugBuffer = fopen('php://temp', 'w+');
            if (0x074000 === $curlVersion) {
                fwrite($this->debugBuffer, 'Due to a bug in curl 7.64.0, the debug log is disabled; use another version to work around the issue.');
            } else {
                curl_setopt($ch, \CURLOPT_VERBOSE, true);
                curl_setopt($ch, \CURLOPT_STDERR, $this->debugBuffer);
            }
        } else {
            $this->info['url'] = $ch;
            $ch = $this->handle;
        }

        $this->id = $id = (int) $ch;
        $this->logger = $logger;
        $this->shouldBuffer = $options['buffer'] ?? true;
        $this->timeout = $options['timeout'] ?? null;
        


        $range = $size . '-' . ($totalSize - 1);

        if (!\function_exists('curl_init')) {
            throw new Exception('PHP Extension "curl" is required to download a file');
        }

        // Configuration of curl         $ch = curl_init();

        curl_setopt($ch, CURLOPT_RANGE, $range);
        curl_setopt($ch, CURLOPT_URL, $sourceUri);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_NOPROGRESS, false);

        curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function D$ch$dltotal$dlnow) use ($size) {
            if ($dlnow > 0) {
                $this->progress($dltotal$dlnow$size + $dlnow);
            }
        });
// Construct Cookie: header if any cookies are set.         WP_Http::buildCookieHeader( $parsed_args );

        $handle = curl_init();

        // cURL offers really easy proxy support.         $proxy = new WP_HTTP_Proxy();

        if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {

            curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
            curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() );
            curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() );

            if ( $proxy->use_authentication() ) {
                curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
                curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
            }
        }

        $is_local   = isset( $parsed_args['local'] ) && $parsed_args['local'];
        $ssl_verify = isset( $parsed_args['sslverify'] ) && $parsed_args['sslverify'];
        

    private $response_byte_limit;

    /** * Constructor */
    public function __construct() {
        $curl          = curl_version();
        $this->version = $curl['version_number'];
        $this->handle  = curl_init();

        curl_setopt($this->handle, CURLOPT_HEADER, false);
        curl_setopt($this->handle, CURLOPT_RETURNTRANSFER, 1);
        if ($this->version >= self::CURL_7_10_5) {
            curl_setopt($this->handle, CURLOPT_ENCODING, '');
        }

        if (defined('CURLOPT_PROTOCOLS')) {
            // phpcs:ignore PHPCompatibility.Constants.NewConstants.curlopt_protocolsFound             curl_setopt($this->handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
        }

        if (defined('CURLOPT_REDIR_PROTOCOLS')) {
            
$pushedResponse = null;
            }
        }

        if (!$pushedResponse) {
            $ch = curl_init();
            $this->logger?->info(sprintf('Request: "%s %s"', $method$url));
            $curlopts += [\CURLOPT_SHARE => $this->multi->share];
        }

        foreach ($curlopts as $opt => $value) {
            if (null !== $value && !curl_setopt($ch$opt$value) && \CURLOPT_CERTINFO !== $opt && (!\defined('CURLOPT_HEADEROPT') || \CURLOPT_HEADEROPT !== $opt)) {
                $constantName = $this->findConstantName($opt);
                throw new TransportException(sprintf('Curl option "%s" is not supported.', $constantName ?? $opt));
            }
        }

        return $pushedResponse ?? new CurlResponse($this->multi, $ch$options$this->logger, $method, self::createRedirectResolver($options$host$port), CurlClientState::$curlVersion['version_number']$url);
    }

    public function stream(ResponseInterface|iterable $responses, float $timeout = null): ResponseStreamInterface
    {
        if ($responses instanceof CurlResponse) {
            
$hooks->register('fsockopen.after_headers', [$this, 'fsockopen_header']);
        }
    }

    /** * Set cURL parameters before the data is sent * * @since 1.6 * @param resource|\CurlHandle $handle cURL handle */
    public function curl_before_send(&$handle) {
        curl_setopt($handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
        curl_setopt($handle, CURLOPT_PROXY, $this->proxy);

        if ($this->use_authentication) {
            curl_setopt($handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
            curl_setopt($handle, CURLOPT_PROXYUSERPWD, $this->get_auth_string());
        }
    }

    /** * Alter remote socket information before opening socket connection * * @since 1.6 * @param string $remote_socket Socket connection string */
if (!$force_fsockopen && function_exists('curl_exec'))
            {
                $this->method = SIMPLEPIE_FILE_SOURCE_REMOTE | SIMPLEPIE_FILE_SOURCE_CURL;
                $fp = curl_init();
                $headers2 = array();
                foreach ($headers as $key => $value)
                {
                    $headers2[] = "$key: $value";
                }
                if (version_compare(SimplePie_Misc::get_curl_version(), '7.10.5', '>='))
                {
                    curl_setopt($fp, CURLOPT_ENCODING, '');
                }
                curl_setopt($fp, CURLOPT_URL, $url);
                curl_setopt($fp, CURLOPT_HEADER, 1);
                curl_setopt($fp, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($fp, CURLOPT_FAILONERROR, 1);
                curl_setopt($fp, CURLOPT_TIMEOUT, $timeout);
                curl_setopt($fp, CURLOPT_CONNECTTIMEOUT, $timeout);
                curl_setopt($fp, CURLOPT_REFERER, SimplePie_Misc::url_remove_credentials($url));
                curl_setopt($fp, CURLOPT_USERAGENT, $useragent);
                curl_setopt($fp, CURLOPT_HTTPHEADER, $headers2);
                foreach ($curl_options as $curl_param => $curl_value) {
                    

  protected function getHeaders($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, TRUE);
    curl_setopt($ch, CURLOPT_NOBODY, TRUE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_USERAGENT, drupal_generate_test_ua($this->databasePrefix));
    $output = curl_exec($ch);
    curl_close($ch);

    $headers = [];
    foreach (explode("\n", $output) as $header) {
      if (strpos($header, ':')) {
        [$key$value] = explode(':', $header, 2);
        
public function register(Hooks $hooks) {
        $hooks->register('curl.before_send', [$this, 'curl_before_send']);
        $hooks->register('fsockopen.after_headers', [$this, 'fsockopen_header']);
    }

    /** * Set cURL parameters before the data is sent * * @param resource|\CurlHandle $handle cURL handle */
    public function curl_before_send(&$handle) {
        curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($handle, CURLOPT_USERPWD, $this->getAuthString());
    }

    /** * Add extra headers to the request before sending * * @param string $out HTTP header string */
    public function fsockopen_header(&$out) {
        $out .= sprintf("Authorization: Basic %s\r\n", base64_encode($this->getAuthString()));
    }

    
/** * @param array<mixed> $logs */
    private function sendLogs(array $logs): void
    {
        if ($logs === []) {
            return;
        }

        $ch = \curl_init('https://http-intake.logs.datadoghq.eu/v1/input');
        \assert($ch instanceof \CurlHandle);
        \curl_setopt($ch, \CURLOPT_CUSTOMREQUEST, 'POST');
        \curl_setopt($ch, \CURLOPT_POST, true);
        \curl_setopt($ch, \CURLOPT_POSTFIELDS, \json_encode($logs, \JSON_THROW_ON_ERROR));
        \curl_setopt($ch, \CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'DD-API-KEY: ' . $_SERVER['DATADOG_API_KEY'],
        ]);

        \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true);
        \curl_exec($ch);
        \curl_close($ch);
    }

    

        if (!\in_array($method$this->validMethods)) {
            throw new ClientException('Invalid HTTP-METHOD: ' . $method);
        }

        if (!filter_var($url, FILTER_VALIDATE_URL)) {
            throw new ClientException('Invalid URL given');
        }

        // Initializes the cURL instance         $curl = curl_init();
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

        $content = curl_exec($curl);

        $error = curl_errno($curl);
        $errmsg = curl_error($curl);
        

        $resource = $easy->handle;
        unset($easy->handle);

        if (\count($this->handles) >= $this->maxHandles) {
            \curl_close($resource);
        } else {
            // Remove all callback functions as they can hold onto references             // and are not cleaned up by curl_reset. Using curl_setopt_array             // does not work for some reason, so removing each one             // individually.             \curl_setopt($resource, \CURLOPT_HEADERFUNCTION, null);
            \curl_setopt($resource, \CURLOPT_READFUNCTION, null);
            \curl_setopt($resource, \CURLOPT_WRITEFUNCTION, null);
            \curl_setopt($resource, \CURLOPT_PROGRESSFUNCTION, null);
            \curl_reset($resource);
            $this->handles[] = $resource;
        }
    }

    /** * Completes a cURL transaction, either returning a response promise or a * rejected promise. * * @param callable(RequestInterface, array): PromiseInterface $handler * @param CurlFactoryInterface $factory Dictates how the handle is released */

    $retries = 0;
    $max_retries = static::$retry ? 10 : 1;
    while ($retries < $max_retries) {
      try {
        $customHeaders = [
          'Content-Type: application/json;charset=UTF-8',
          'Accept: application/json;charset=UTF-8',
        ];

        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);

        switch ($requestMethod) {
          case 'GET':
            break;

          case 'POST':
            if ($parameters && is_array($parameters)) {
              curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($parameters));
            }
            else {
              $customHeaders[] = 'Content-Length: 0';

              
Home | Imprint | This part of the site doesn't use cookies.