How to Get an Option Previously Set with Curl_Setopt()

How to get an option previously set with curl_setopt()?

Pulled from various answers around the internets:

Question: Is there a way to get the
current curl option settings? Like a
curl_getopt() or curl_showopts()?

Answer: Yes and no. There is
curl_getinfo() which will show you some
info about the last connection, but I
suspect it's not what you're looking
for. It's a weakness in curl, IMHO.

My suggestion (and others) is to encapsulate cURL into a class where your $cURL->setOpt() function also stores the value for retrieval later.

The multirequest PHP library has this functionality (and then some!):

$request = new \MultiRequest\Request($url);
$request->setCurlOption(CURLOPT_PROXY, $proxy);
// ...
$curlOptions = $request->getCurlOptions();
list($proxyIp, $proxyPort) = explode(':', $curlOptions[CURLOPT_PROXY]);

How to switch from POST to GET in PHP CURL

Solved: The problem lies here:

I set POST via both _CUSTOMREQUEST and _POST and the _CUSTOMREQUEST persisted as POST while _POST switched to _HTTPGET. The Server assumed the header from _CUSTOMREQUEST to be the right one and came back with a 411.

curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'POST');

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

Following what curl does internally for the request (via the method outlined in this answer to "Php - Debugging Curl") answers the question: No.

No, it is not possible to use curl_setopt(PHP) with CURLOPT_HTTPHEADER more than once, passing it a single header each time, in order to set multiple headers.

A second call will overwrite the headers of a previous call (e.g. of the first call).

Instead the function needs to be called once with all headers:

$headers = [
'Content-type: application/xml',
'Authorization: gfhjui',
];
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

Related (but different) questions are:

  • How to send a header using a HTTP request through a curl call? (curl on the commandline)
  • How to get an option previously set with curl_setopt()? (curl PHP extension)

Default cURL option values

I have been researching the same problem today and came across this (rather old) post. Since it shows up pretty much at the top of Google, I thought this is the place to conclude my research.

In short: It's not possible.

It seems like most cURL options do not even have any default values. For example, timeouts. Or the user agent. But many others do have defaults, as the PHP manual states. I could not find any list of default values - neither for PHP's cURL extension, nor for cURL in general. Only individual defaults that are mentioned within said PHP manual or within the cURL API doc. However, I doubt that every single default is mentioned within those pages.

Unfortunately, finding them out programmatically is not possible, either. The idea would be to find out all options values before setting the first one. But there is no curl_getopt(). Not even in cURL itself. All solutions that emulate curl_getopt() can only retrieve those options that have been set manually.

After a (very) short glance at the cURL source code (the original C lib) I also suspect that sometimes there are no real defaults, but if an option is not set, some logic goes into figuring out which value to use. In that case, default values would not even be well-defined.

Lastly, chances are that PHP's cURL extension employs some different defaults than cURL itself.

So unless some cURL developer sheds some light on this - or at least someone who has the time and skill to really dive into the code - we are pretty much stuck on this.

Properly running a curl in php

Here is one way to do it with curl and an options array:

<?php

$curl = curl_init("https://secure.fusebill.com/v1/customers/{id}/Overview");

curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Basic {APIKey}",
"Content-Type: application/json"
)
));

$response = curl_exec($curl);
curl_close($curl);

You can alternatively set each option by calling curl_setopt($curl, OPTION_NAME, "value"); for each option in place of curl_setopt_array();:

$curl = curl_init("https://secure.fusebill.com/v1/customers/{id}/Overview");

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Authorization: Basic {APIKey}",
"Content-Type: application/json"
));

$response = curl_exec($curl);
curl_close($curl);

For this request in PHP, you initialize curl and store in a variable so you can add options to the request before executing.

Here is a breakdown of the options from the snippet above:

CURLOPT_RETURNTRANSFER - return data from the request as a string instead of outputting directly (useful if you need to use the data in another function somewhere).

CURLOPT_CUSTOMREQUEST - HTTP request method for the request

CURLOPT_HTTPHEADER - set headers for the request.

Here is how the PHP maps to the cURL above:

-X specifies the HTTP method and the URL. In PHP we set CURLOPT_CUSTOMREQUEST and set the URL when we initialize the cURL handler, you can optionally use CURLOPT_URL to set the URL instead.

-H - stands for headers for the request. In PHP we set CURLOPT_HTTPHEADER. We set the headers as an array since there are multiple headers.

Remember to replace {id} in the URL and {APIKey} in the authorization header of your request.

php curl get proxy

1. You tell curl what proxy to use, and not viaversa:

function wget($url)
{
$options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_PROXY => '...proxy.ip...',
CURLOPT_PROXYPORT => '...proxy.port...',
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.8.0.9) Gecko/20061206 Firefox/1.5.0.9',
);
$ch = curl_init();
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
$error = curl_error($ch);
return (!$error && $content) ? $content : null;
}

2. Another solution >

And look at this answer > How to get an option previously set with curl_setopt()?

3. Override curl_setopt() function

http://php.net/manual/en/function.override-function.php

p.s. you should probably need http://php.net/manual/en/function.rename-function.php

4. Use runkit to override functions

http://php.net/manual/en/book.runkit.php

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

If the cookie is generated from script, then you can send the cookie manually along with the cookie from the file(using cookie-file option). For example:

# sending manually set cookie
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: test=cookie"));

# sending cookies from file
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);

In this case curl will send your defined cookie along with the cookies from the file.

If the cookie is generated through javascrript, then you have to trace it out how its generated and then you can send it using the above method(through http-header).

The utma utmc, utmz are seen when cookies are sent from Mozilla. You shouldn't bet worry about these things anymore.

Finally, the way you are doing is alright. Just make sure you are using absolute path for the file names(i.e. /var/dir/cookie.txt) instead of relative one.

Always enable the verbose mode when working with curl. It will help you a lot on tracing the requests. Also it will save lot of your times.

curl_setopt($ch, CURLOPT_VERBOSE, true);

php cURL silent option?

You want to set the CURLOPT_MUTE setting when initializing the connection:

curl_setopt($curl_resource, CURLOPT_MUTE, 1);

Passing $_POST values with cURL

Should work fine.

$data = array('name' => 'Ross', 'php_master' => true);

// You can POST a file by prefixing with an @ (for <input type="file"> fields)
$data['file'] = '@/home/user/world.jpg';

$handle = curl_init($url);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
curl_exec($handle);
curl_close($handle)

We have two options here, CURLOPT_POST which turns HTTP POST on, and CURLOPT_POSTFIELDS which contains an array of our post data to submit. This can be used to submit data to POST <form>s.


It is important to note that curl_setopt($handle, CURLOPT_POSTFIELDS, $data); takes the $data in two formats, and that this determines how the post data will be encoded.

  1. $data as an array(): The data will be sent as multipart/form-data which is not always accepted by the server.

    $data = array('name' => 'Ross', 'php_master' => true);
    curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
  2. $data as url encoded string: The data will be sent as application/x-www-form-urlencoded, which is the default encoding for submitted html form data.

    $data = array('name' => 'Ross', 'php_master' => true);
    curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data));

I hope this will help others save their time.

See:

  • curl_init
  • curl_setopt

-w option in PHP curl?

After your curl_exec($ch) you can use curl_getinfo($ch, CURLINFO_*); to return the values of the CURLINFO_* constants.

http://php.net/manual/en/function.curl-getinfo.php

This may be one of the following constants:

CURLINFO_EFFECTIVE_URL - Last effective URL
CURLINFO_HTTP_CODE - Last received HTTP code
CURLINFO_FILETIME - Remote time of the retrieved document, if -1 is returned the time of the document is unknown
CURLINFO_TOTAL_TIME - Total transaction time in seconds for last transfer
CURLINFO_NAMELOOKUP_TIME - Time in seconds until name resolving was complete
CURLINFO_CONNECT_TIME - Time in seconds it took to establish the connection
CURLINFO_PRETRANSFER_TIME - Time in seconds from start until just before file transfer begins
CURLINFO_STARTTRANSFER_TIME - Time in seconds until the first byte is about to be transferred
CURLINFO_REDIRECT_COUNT - Number of redirects, with the CURLOPT_FOLLOWLOCATION option enabled
CURLINFO_REDIRECT_TIME - Time in seconds of all redirection steps before final transaction was started, with the CURLOPT_FOLLOWLOCATION option enabled
CURLINFO_REDIRECT_URL - With the CURLOPT_FOLLOWLOCATION option disabled: redirect URL found in the last transaction, that should be requested manually next. With the CURLOPT_FOLLOWLOCATION option enabled: this is empty. The redirect URL in this case is available in CURLINFO_EFFECTIVE_URL
CURLINFO_PRIMARY_IP - IP address of the most recent connection
CURLINFO_PRIMARY_PORT - Destination port of the most recent connection
CURLINFO_LOCAL_IP - Local (source) IP address of the most recent connection
CURLINFO_LOCAL_PORT - Local (source) port of the most recent connection
CURLINFO_SIZE_UPLOAD - Total number of bytes uploaded
CURLINFO_SIZE_DOWNLOAD - Total number of bytes downloaded
CURLINFO_SPEED_DOWNLOAD - Average download speed
CURLINFO_SPEED_UPLOAD - Average upload speed
CURLINFO_HEADER_SIZE - Total size of all headers received
CURLINFO_HEADER_OUT - The request string sent. For this to work, add the CURLINFO_HEADER_OUT option to the handle by calling curl_setopt()
CURLINFO_REQUEST_SIZE - Total size of issued requests, currently only for HTTP requests
CURLINFO_SSL_VERIFYRESULT - Result of SSL certification verification requested by setting CURLOPT_SSL_VERIFYPEER
CURLINFO_CONTENT_LENGTH_DOWNLOAD - content-length of download, read from Content-Length: field
CURLINFO_CONTENT_LENGTH_UPLOAD - Specified size of upload
CURLINFO_CONTENT_TYPE - Content-Type: of the requested document, NULL indicates server did not send valid Content-Type: header
CURLINFO_PRIVATE - Private data associated with this cURL handle, previously set with the CURLOPT_PRIVATE option of curl_setopt()


Related Topics



Leave a reply



Submit