Search code examples
phpcurlopenhab

cURL with PHP / Working with PUT and GET


can anyone help me to translate this to a PHP Code:

curl -X GET --header "Accept: text/plain" "https://test:[email protected]:1443/rest/items/test/state"

and:

curl -X PUT --header "Content-Type: text/plain" --header "Accept: application/json" -d "OFF" "https://test:[email protected]:1443/rest/items/test/state"

My attempt failed. Usually I would use this:

function sendCommand($item, $data) {
  $url = "http://192.168.1.121:8080/rest/items/" . $item;

  $options = array(
    'http' => array(
        'header'  => "Content-type: text/plain\r\n",
        'method'  => 'POST',
        'content' => $data  //http_build_query($data),
    ),
  );

  $context  = stream_context_create($options);
  $result = file_get_contents($url, false, $context);

  return $result;
}

But I don't know how to add SSL Support and authentication to the script and I know that is easier with cUrl.


Solution

  • function sendCommand($item,$itemValue){
            $ch = curl_init("http://[IP from openHAB2]:8080/rest/items/".$item."/state");
            $curlOptions = array(
                CURLOPT_RETURNTRANSFER => TRUE,
                CURLOPT_HTTPHEADER => array('Content-Type: text/plain','Accept: application/json'),
                CURLOPT_CUSTOMREQUEST => 'PUT',
                CURLOPT_POSTFIELDS => NULL,
                CURLOPT_POSTFIELDS => $itemValue
            );
            curl_setopt_array($ch, $curlOptions);
            if(curl_exec($ch) === false){
                $this->updateDatabase(curl_error($ch));
                echo 'Curl-Fehler: ' . curl_error($ch);
                exit();
            }else{
                curl_exec($ch);
                return true;
            }
            curl_close($ch);
        }