I'm new to cURL in PHP. I have a question regarding usage of curl options.
Consider two script files: test1.php and test2.php both present in root www. I'm using Ubuntu 12.04 LTS. The libcurl version for PHP is 7.22.0.
Contents of test1.php
<?php $ch = curl_init(); $post_data = array( 'firstname' => 'John', 'lastname' => 'Doe' ); curl_setopt($ch, CURLOPT_URL, 'localhost/test2.php'); curl_setopt($ch, CURLOPT_POST, TRUE); //is it optional? curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); curl_exec($ch); curl_close($ch); ?>
Contents of test2.php
<?php var_dump($_POST); ?>
When I execute test1.php via browser, I can see results posted. Now if I remove curl option containing CURLOPT_POST, the example still works. Even if I set CURLOPT_POST to false, post is performed and result is displayed. So, is that CURLOPT_POST not required at all? It looks option CURLOPT_POSTFIELDS
takes care of sending data via POST without use of CURLOPT_POST
option. When I print $_SERVER
in test2.php, request method is always set to POST
(with or without option CURLOPT_POST
).
Could anyone please let me know the exact use of CURLOPT_POST
option? Is it neccessary required for sending data via POST
?
CURLOPT_POST: Set this option to a non-zero value if you want PHP to do a regular HTTP POST. This POST is a normal application/x-www-from-urlencoded kind, most commonly used by HTML forms.
Parameters ¶ A cURL handle returned by curl_init(). The CURLOPT_XXX option to set. The value to be set on option .
CURLOPT_RETURNTRANSFER: Converts output to a string rather than directly to the screen. CURLOPT_HTTPHEADER: Request header information with an array of parameters, as shown in the example of "Browser-based redirection"
curl_exec(CurlHandle $handle ): string|bool. Execute the given cURL session. This function should be called after initializing a cURL session and all the options for the session are set.
You are correct. CURLOPT_POSTFIELDS implies CURLOPT_POST. You don't need to use CURLOPT_POST while using CURLOPT_POSTFIELDS. The request method will always be set to POST in this case.
Note that this is in your case as long as you want it to be a POST request.
If you don't want to be it a POST request but set CURLOPT_POSTFIELDS, please see this related Q&A:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With