Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a request with both GET and POST parameters in PHP with cURL?

Tags:

post

php

curl

get

Other people have already asked how to do this from perl, java, bash, etc. but I need to do it in PHP, and I don't see any question already asked relating specifically to (or with answers for) PHP.

My code:

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);

This doesn't work. The destination site has print_r($_GET); print_r($_POST);, so when I examine the $result I should be able to see the fields that are being sent. However, the $_POST array is empty - I only see the get variables. If I remove the ?... query string from the $url, then the POST array is populated correctly. But now I don't have the GET params. How do I do this?

My specific case is, I need to send too much data to fit it in the query string, but I can't send it all as POST because the site I want to submit to is selecting a handler for the posted data based on a variable in the GET string. I can try and have that changed, but ideally I would like to be able to send both get and post data in the same query.

like image 287
Benubird Avatar asked Sep 03 '14 14:09

Benubird


2 Answers

# GET query goes in the URL you're hitting
$ch = curl_init('http://example.com/script.php?query=parameter');
# POST fields go here.
curl_setopt($ch, CURLOPT_POSTFIELDS, array('post' => 'parameter', 'values' => 'go here'));

PHP itself wouldn't decide to ignore the GET parameters if a POST is performed. It'll populate $_GET regardless of what kind of http verb was used to load the page - if there's query parameters in the URL, they'll go into $_GET.

If you're not getting $_POST and $_GET with this, then something is causing a redirect or otherwise killing something. e.g. have you check $_SERVER['REQUEST_METHOD'] to see if your code is actually running as a POST? PHP won't populate $_POST if a post wasn't actually performed. You may have sent a post to the server, but that doesn't mean your code will actually be executed under a POST regime - e.g. a mod_rewrite redirect.

Since you have FOLLOW_REDIRECT turned on, you're simply ASSUMING you're actually getting a post when your code executes.

like image 162
Marc B Avatar answered Sep 23 '22 14:09

Marc B


i don't know maybe you already have but is your $url has the desired get parameters? Like:

$url = "http://example.com/index.php?param1=value1&param2=value2";
like image 20
Santa's helper Avatar answered Sep 25 '22 14:09

Santa's helper