1

I'm trying to port this command to PHP:

curl -i -X POST http://website.com \
-H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" \
-H "Accept: Application/json" \
-H "X-Requested-With: XMLHttpRequest" --data "var1=output1&var2=output2"

From bash it works.. I get this JSON output.

This is what I wrote in PHP to try to get the same result:

<?php
function blabla() {

    $curl_parameters = array(
        'var1'    =>  "output1",
        'var2'    =>  "output2",
    );

    $ch = curl_init();

    curl_setopt($ch,CURLOPT_URL,"http://website.com");
    curl_setopt($ch,CURLOPT_POST,true);
    curl_setopt($ch,CURLOPT_HEADER,true);
    curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query( $curl_parameters ));
    curl_setopt($ch,CURLOPT_HTTPHEADER,array (
        "Content-Type"      => "application/x-www-form-urlencoded; charset=UTF-8",
        "Accept"            => "Application/json",
        "X-Requested-With"  => "XMLHttpRequest",
    ));

    $output=curl_exec($ch);

    curl_close($ch);
}

echo blabla();
?>

Unfortunately with this snippet I just get a 302 Found HTTP header as output (this).. seems like the variables are not passed (the --data part from the bash command).

3 Answers 3

1

The problem is with your CURLOPT_HTTPHEADER. It should be an array of strings like this:

curl_setopt($ch,CURLOPT_HTTPHEADER,array(
    'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
    'Accept: application/json',
    'X-Requested-With: XMLHttpRequest',
));
Sign up to request clarification or add additional context in comments.

1 Comment

... and yes!!!! :) Can't believe it was that simple :( I thought it was ok to have a "real" array.
0

How about just curl_setopt($ch,CURLOPT_POSTFIELDS, $curl_parameters);? I don't think you need to call http_build_query.

4 Comments

Nope.. still get just the "302 Found Header"
I added to the question the output I get with the PHP snippet.
I should have tested before answering; my bad.
passing an array results in multipart/form-data content instead of the desired application/x-www-form-urlencoded
0

Try add curl follow 302 redirect

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

Also make sure your http_build_query() function uses "&" as argument separator. On some PHP configurations it may be "& amp;" by default

$query = http_build_query($data, '', '&');

1 Comment

I tried with curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($curl_parameters, '', '&')); but still same output (just http header). :(

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.