Search code examples
phpcurlphp-curl

Setting empty CURLOPT_POSTFIELDS


I am trying to use a common library function to send GET and POST requests using curl.

function myCurl($url, $postData = null) 
{
    // Sets some default curl options here
    $options = array(
        ...
        CURLOPT_POSTFIELDS => $postData,
        ...
    );

    $ch = curl_init();
    // this works and sends GET
    // unset($options[CURLOPT_POSTFIELDS]); 

    curl_setopt_array($ch, $options);

    curl_exec($ch);
    curl_close($ch);
}

I want this function to send a POST if $postData is set, otherwise consider it a GET. However, this is sending POST even when I set the CURL_POSTFIELDS to null. Unsetting the CURL_POSTFIELDS options array element works and sends a GET. However, is there a way to keep the CURL_POSTFIELDS curl option and set it a default empty value and make it send GET requests?


Solution

  • $options = array(
        ...
    );
    if(!empty($postData)){
        $options[CURLOPT_POSTFIELDS]=$postData;
    }
    

    alternatively the following approach should works, but it's stupid imo:

    $options = array(
        ...
        CURLOPT_POSTFIELDS => $postData,
        CURLOPT_HTTPGET => empty($postData)
        ...
    );