Oblivious References and cURL Adventures

PHP references are tricky. They’ve always been. People question their performance, compliance with modern software architecture practices and trends. However, show me a single PHP language construct people do not question and I’ll buy you a beer.

I have to admit, it’s been much better since PHP5 came out. We do not have myriad of unintentionally cloned objects anymore, and the ampersand madness has stopped (however I know somebody who continues using it despite all the years passed since it lost its meaning):

$object =& new MyClass();

Don’t get me wrong, I love PHP, and I’ve been advocating its strength for years. Every time I heard somebody criticizing it I responded with a “You just don’t use it right” kind of answer, and was right every single time (well, you know, you can’t be wrong on the internet, it’s always the other guy who is wrong).

However, there are times when I stumble over little things that leave me crying “Why me!”. First time it happened short after long-awaited PHP 5 was introduced back in 2004:

$array = ['one', 'two', 'three', 'four'];
foreach ($array as $key => &$value) { }
foreach ($array as $key => $value) { }

// ['one', 'two', 'three', 'three']

That’s a classic example,  I won’t even explain it meaning. However, if you aren’t familiar with it yet, there is a good explanation by Johannes Schlüter.

But this time was different because I managed to jump over my head – I got troubles with references without using references at all:

$curl = curl_init();
$data = ['key1' => 'val1', 'key2' => ['subkey1' => 'subval1', 'subkey2' => 'subval2']];
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

// ['key1' => 'val1', 'key2' => 'Array']

As you see, the 'key2' array was converted to string 'Array', not only in the cURL query but in the original variable as well. Turns out that’s a long-known PHP bug #67585 first reported back in 2014. Such a disappointment since I’ve already named the bug after myself and even started writing my personal Wikipedia article. Turned out I haven’t become famous and still have to work for living, so I had to come up with a solution. Using http_build_query() to encode the array beforehand solves the problem just fine:

curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));

More PHP insides next time, stay tuned!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>