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

Other people are already asking how to do this from perl, java, bash, etc., but I need to do it in PHP, and I do not see the question that has already been asked regarding specifically (or with answers to) PHP.

My code is:

$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 does not work. Destination has print_r($_GET); print_r($_POST); print_r($_GET); print_r($_POST); , so when I look at $result , I should see the fields that are being sent. However, the $ _POST array is empty - I only see get variables. If I delete the query string ?... from $ url, then the POST array will be populated correctly. But now I have no GET parameters. How to do it?

In my particular case, I need to send too much data to match them in the query string, but I cannot send it all as POST, because the site I want to send to selects a handler for the published data based on the variable in the GET string . I can try and change this, but ideally I would like to be able to send and receive and send data in the same request.

+5
source share
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 did not decide to ignore the GET parameters if POST was executed. It will fill in $ _GET no matter what http verb was used to load the page - if the request parameters are specified in the URL, they will go to $ _GET.

If you do not get $ _POST and $ _GET with this, then something causes a redirect or something else. for example, you checked $_SERVER['REQUEST_METHOD'] to see if your code really works like a POST? PHP will not populate $ _POST if the message was not executed. Perhaps you sent a message to the server, but this does not mean that your code will actually be executed in POST mode - for example. redirect mod_rewrite.

Since you have FOLLOW_REDIRECT enabled, you simply ACCEPT that you are actually receiving a message when your code executes.

+9
source

I don’t know, maybe you already have it, but your $ url has the desired retrieval options? How:

 $url = "http://example.com/index.php?param1=value1&param2=value2"; 
+3
source

Source: https://habr.com/ru/post/1201741/


All Articles