cURL PHP RESTful service always returning FALSE
I am having some difficulties POSTing a json object to an API that uses REST. I am new to using cURL, but I have searched all over to try to find an answer to my problem but have come up short. My cURL request is always returning false. I know it isn’t even posting my json object because I would still get a response from the url. My code is below.
"; curl_setopt($ch, CURLOPT_POSTFIELDS, $authData); //make the request $result = curl_exec($ch); $response = json_encode($result); echo $response; curl_close() ?>
1 Answer 1
$response is likely false because curl_exec() returns false (i.e., failure) into $result . Echo out curl_error($ch) (after the call to curl_exec) to see the cURL error, if that’s the problem.
On a different note, I think your CURLOPT_POSTFIELDS is in an invalid format. You don’t pass a JSON string to that.
This parameter can either be passed as a urlencoded string like ‘para1=val1¶2=val2&. ‘ or as an array with the field name as key and field data as value.
— PHP docs for curl_setopt()
The quick way to avoid the SSL error is to add this option:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
You get an SSL verification error because cURL, unlike browsers, does not have a preloaded list of trusted certificate authorities (CAs), so no SSL certificates are trusted by default. The quick solution is to just accept certificates without verification by using the line above. The better solution is to manually add only the certificate(s) or CA(s) you want to accept. See this article on cURL and SSL for more information.
Curl выдает false. Что делать?
Есть вот такая функция работы со сбербанком. Выдает bool(false) . Самое странное, что на другом серваке работает нормально. Думал затык в https, но запросы со своих серваков по http и https забирает. В какую сторону можно покапать?
define('GATEWAY_URL', 'https://3dsec.sberbank.ru/payment/rest/'); function gateway($method, $data) < $curl = curl_init(); // Инициализируем запрос curl_setopt_array($curl, array( CURLOPT_URL =>GATEWAY_URL.$method, // Полный адрес метода CURLOPT_RETURNTRANSFER => true, // Возвращать ответ CURLOPT_POST => true, // Метод POST CURLOPT_POSTFIELDS => http_build_query($data) // Данные в запросе )); $response = curl_exec($curl); // Выполненяем запрос var_dump($response); $response = json_decode($response, true); // Декодируем из JSON в массив curl_close($curl); // Закрываем соединение return $response; // Возвращаем ответ >
function gateway($method, $data) < $context = stream_context_create(array( 'http' =>array( 'method' => 'POST', 'header' => 'Content-Type: application/x-www-form-urlencoded', 'content' => http_build_query($data), 'protocol_version' => 1.1, 'timeout' => 10, 'ignore_errors' => true ) )); $response = file_get_contents(GATEWAY_URL.$method, false, $context); $response = json_decode($response, true); // Декодируем из JSON в массив return $response; // Возвращаем ответ >
Спасибо за помощь, сам столкнулся с такой проблемой у Сбербанка, только я убрал protocol_version, иначе отдавал «Доступ запрещен».
Первый же сайт с Access-Control-Allow-Origin не * и все надежды, мечты, планы на счастливую и беззаботную жизнь — в миг рухнут как карточный домик.
А нужно было всего-то добавить:
CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false
PHP cURL returns FALSE on HTTPS
I’m trying to make a bot for: https://coinroll.it/api From the site:
The Coinroll API is a stateless interface which works over HTTPS. Requests are made using POST variables (application/x-www-form-urlencoded) while responses are encoded in JSON (application/json). A HTTPS connection is required for accessing the API. I have the following code:
$ch = curl_init(); $data = array('user' => 'xxx', 'password' => 'yyy'); curl_setopt($ch, CURLOPT_URL, 'https://coinroll.it'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded')); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); echo $result;
When I run this code, it returns a blank page, what am I doing wrong? EDIT
I don’t actually need to use cURl, if there is a better solution, please tell me.
Try removing the the CURLOPT_HTTPHEADER . By passing an array for the post fields, cURL will set the correct content-type automatically.
Try setting curl_setopt($ch, ‘CURLOPT_SSL_VERIFYPEER’, false); . This tells cURL not to try to verify the SSL certificate. Failing that, see what the output of echo curl_error($ch); is.
Without curl_setopt($ch, ‘CURLOPT_SSL_VERIFYPEER’, false); , echo curl_error($ch); prints SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed .