0

I'm making a library that allows a user to dynamically add/remove cURL options before a request is made. The foreach loop looks like this:

$ch = curl_init($url);

// Cycle through each option and set them
foreach($setup['curl_options'] as $option => $value)
{
    echo '<p>' . $option . ' = ' . $value . '</p>';
    curl_setopt($ch, $option, $value);
}

The array key/values display correctly in the paragraphs, however when it comes to adding the values to the curl_setopt, I get the error:

curl_setopt() expects parameter 2 to be long, string given.

What am I doing wrong here?

3 Answers 3

1
curl_setopt($ch, $option, $value);

Let's say $option is 'CURLOPT_HEADER'. Your code boils down to:

curl_setopt($ch, 'CURLOPT_HEADER', $value);

the name of the constant is now a string, not an actual constant. What you need to do is store the value of what the constant represents in your array when you build it:

$setup['curl_options'][] = array('CURLOPT_HEADER', true); // wrong
$setup['curl_options'][] = array(CURLOPT_HEADER, true); // right
Sign up to request clarification or add additional context in comments.

3 Comments

This seems to work :) However a funny thing pops up now when I loop the key/value pairs through paragraphs. If I loop through: CURLOPT_SSL_VERIFYPEER => FALSE and CURLOPT_SSL_VERIFYHOST => FALSE, the $option parameter now contains numbers? 64 for HOST and 81 for PEER ?
That's the raw values of those constants. somewhere inside the php curl library, there's what amounts to define('CURLOPT_SSL_VERIFYPEER', 81).
That's all those constant "strings" are - just a mapping from a friendly semi-readable string to the numbers that curl uses internally.
1

Second parameter (your $option) have to be a constant value.

Here http://php.net/manual/en/function.curl-setopt.php you have definition of all available constans.

If you already use that values of constans, you should parse it to (long) type.

If you just have names of that constans, use constant($option) but be sure that values are also uppercase and correct.

2 Comments

However, constant() simply returns the value of a constant. problem is that he's passing a string into the second argument $option, not the constant name itself.
Exacly. He should pass constant's value. When you use curl_setopt($ch, CURLOPT_AUTOREFERER, true), you pass to function a value that is hidden in called constant. You can also look into PHP source code and check what value it is: define ('CURLOPT_AUTOREFERER', 58); and pass to the function just 58 instead of constant.
0

Try with

curl_setopt($ch, constant($option), $value);

1 Comment

eval is evil. There is in PHP dedicated function for that operation called constant().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.