-2

I want the following cURL command to be converted to PHP

curl -X PUT -H 'Content-Type: application/json' -d '{"on":true,"bri":255,"sat":255,"hue":20000}' http://MYSITE:PORT/api/HASH/lights/1/state

I did the following but it is just timing out.

$data_json = '{"on":true,"bri":255,"sat":255,"hue":20000}';
$url = "http://MYSITE:PORT/api/HASH/lights/1/state";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);

$response  = curl_exec($ch);
echo $response;
curl_close($ch);
Bijan
  • 7,737
  • 18
  • 89
  • 149

2 Answers2

1

you can set the curl timeout like so

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0); curl_setopt($ch, CURLOPT_TIMEOUT, 400); //timeout in seconds

you might want to increase the php timeout in php.ini too

andylondon
  • 176
  • 6
  • The problem I have is that the curl command works fine. But when I convert it to PHP, it does not do like it is supposed to. is the problem in my conversion? – Bijan May 01 '15 at 16:11
0

I would try to debug the Curl request using the technique mentioned here, this should give you more information about what Curl is doing.

Also if you are willing to use a library I would recommend using Guzzle, it's well documented and makes these types of operation less painful in my experience.

<?php

use GuzzleHttp\Client;

require 'vendor/autoload.php';

$url = "http://jsonplaceholder.typicode.com/posts";
$client = new Client();

$body['title'] = "json guzzle post";
$body['body'] = "carlton";
$body['userId'] = "109109101";

$res = $client->post($url, [ 'body' => json_encode($body) ]);

$code = $res->getStatusCode();
$result = $res->json();

var_dump($code);
var_dump($result);
Community
  • 1
  • 1
Carlton
  • 5,533
  • 4
  • 54
  • 73