PHP: curl_setopt - Manual http://php.net/manual/en/function.curl-setopt.php

 

CURLOPT_POST TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.

 

CURLOPT_POSTFIELDS The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Typeheader will be set to multipart/form-dataAs of PHP 5.2.0, value must be an array if files are passed to this option with the @ prefix. As of PHP 5.5.0, the @ prefix is deprecated and files can be sent using CURLFile. The @ prefix can be disabled for safe passing of values beginning with @ by setting the CURLOPT_SAFE_UPLOAD option to TRUE.

 

 

php - CURLOPT_POST vs. CURLOPT_POSTFIELDS: Is CURLOPT_POST option required? - Stack Overflow https://stackoverflow.com/questions/26728740/curlopt-post-vs-curlopt-postfields-is-curlopt-post-option-required

 

 

1

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?

 

21down voteaccepted

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: