-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);
4

2 回答 2

1

你可以像这样设置卷曲超时

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0); curl_setopt($ch, CURLOPT_TIMEOUT, 400); //超时秒数

您可能还想增加 php.ini 中的 php 超时

于 2015-05-01T09:09:05.237 回答
0

我会尝试使用此处提到的技术来调试 Curl 请求,这应该可以为您提供有关 Curl 正在做什么的更多信息。

此外,如果您愿意使用我建议使用Guzzle的库,它有据可查,并且在我的经验中使这些类型的操作不那么痛苦。

<?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);
于 2015-05-01T08:10:19.770 回答