PHP cUrl not posting - php

I want to send json data using cURL in php, but the problem is that cURL is not posting any data.
NOTICE: cURL is properly installed and configured.
$ch = curl_init($url);
//The JSON data.
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"text":"'.$message_to_reply.'"
}
}';
$jsonDataEncoded = $jsonData;
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, array($jsonDataEncoded));
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_exec($ch);
The json Data is working fine but the cURL post is not posting anything and also not giving any type of warnings/notice or error.

as far as i can see, you do 3 mistakes
1: don't do curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");, the correct way to tell curl that you want a POST request is curl_setopt($ch, CURLOPT_POST, true);
2: when you give CURLOPT_POSTFIELDS an array, its actually converted to a multipart/form-data encoding, which is not what you want (you want to transfer a json)
3: your $sender and $message_to_reply seem to be just inserted in to the json raw. what happens if your $message_to_reply contains an " or ' ? it will invalidate the json. consider encoding it properly, for example using json_encode, like
$jsonData = array (
'recipient' => array (
'id' => $sender
),
'message' => array (
'text' => $messaage_to_reply
)
);
$jsonDataEncoded = json_encode ( $jsonData, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
but, provided that $sender and $message_to_reply is already properly json encoded, the only reason your original code doesn't work, as far as i can see, is that you give CURLOPT_POSTFIELDS an array, thus, all that's needed to fix it would be to remove "array" from that line, like curl_setopt($ch, CURLOPT_POSTFIELDS,$jsonDataEncoded);

Try this;
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(json_decode($jsonDataEncoded)));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
You probably don't want to pass all data to one key.
Output of print_r(array($jsonDataEncoded))
Array ( [0] => { "recipient":{ "id":"me" }, "message":{ "text":"hello" } } )
Output of print_r(json_decode(array($jsonDataEncoded)))
Array ( [0] => stdClass Object ( [recipient] => stdClass Object ( [id] => me ) [message] => stdClass Object ( [text] => hello ) ) )

Well after all the try, Here is the answer:
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"text":"'.$message_to_reply.'"
}
}';
$jsonDataEncoded = $jsonData;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Here i removed the array//
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// By default in PHP7 CURL_SSL_VERIFYPEER, is true. You have to make it false//
$result = curl_exec($ch);

Related

Calling Azure Release Create with PHP

I'm trying to use pure PHP to call the Azure DevOps API REST to create a release pipeline. The json required for the body is working with POSTMAN but PHP returns this error:
Array ( [$id] => 1 [innerException] => [message] => VS402903: The specified value is not convertible to type ReleaseStartMetadata. Make sure it is convertible to type ReleaseStartMetadata and try again. [typeName] => Microsoft.VisualStudio.Services.ReleaseManagement.Data.Exceptions.InvalidRequestException, Microsoft.VisualStudio.Services.ReleaseManagement2.Data [typeKey] => InvalidRequestException [errorCode] => 0 [eventId] => 3000 )
It does not make any sense, but I think there is something regarding the return of the information instead of the information sent through the body.
Here's my code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$pat='hidden';
$url = 'https://vsrm.dev.azure.com/org-id/workspace-name/_apis/release/releases?api-version=6.0';
$body = '{
"definitionId": 1,
"description": "test",
"name": "test",
"isDraft": false,
"reason": "manual"
}';
$data_json = json_encode($body);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8; api-version=6.0','Authorization: Basic '.$pat));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$data = json_decode($response, true);
print_r ($data);
curl_close($ch);
?>
I found the answer, the error is because the json that I was sending through the body has some escaping characters \n\ etc.
With this, I have cleaned it up, and put it below the $data_json = json_encode($body);
$body_formatted=rtrim(ltrim(str_replace('\\', '', str_replace('\n', '', $data_json)), '"'), '"');
Use body_formatted on the post option curl_setopt($ch, CURLOPT_POSTFIELDS,$body_formatted);
Hope it's helps for anyone.

Could not parse the 'params' argument as valid JSON (PHP, cURL, REST)

After executing the PHP Script, I am getting the following error – Any help is appreciated. Based on my understanding, I created an array based on the bugzilla documentation - Thanks in advance
https://bugzilla.readthedocs.io/en/5.0/api/core/v1/bug.html#create-bug
{"code":32000,"error":true,"message":"Could not parse the 'params' argument as valid JSON. Error: malformed number (no digits after initial minus), at character offset 1
$url ="http://localhost:8080/bugzilla/rest/bug";
$data = array(
"product" => "TestProduct",
"component" => "TestComponent",
"version" => "unspecified",
"summary" => "'This is a test bug - please disregard",
"alias" => "SomeAlias",
"op_sys" => "All",
"priority" => "P1",
"rep_platform" => "All"
);
$str_data = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array("Content-Type: application/json", "Accept: application/json"));
$username = 'ashish.sureka#in.abb.com';
$password = 'incrc';
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
$result = curl_exec($ch);
curl_close($ch);
echo $result
You have this:
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
which sends your array of data as a conventional key=value form submission, when you should have
curl_setopt($ch, CURLOPT_POSTFIELDS, $str_data);
^^^^^
which would send your JSON-encoded array instead.
You send $data in CURLOPT_POSTFIELDS but I think you need to give it $str_data which is encode in JSON
I think you have to replace
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
with
curl_setopt($ch, CURLOPT_POSTFIELDS, $str_data);
to transfer the json encoded array instead of the raw php array.

Accessing Results of CURL request + PHP

I'm executing a curl request using php:
//Initiate cURL.
$ch = curl_init($url);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($data);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);
The browser returns:
{"success":"true","lead_id":"141872","code":201}
OR
{"error":true,"duplicate":true,"message":"Duplicate: This has already been submitted to the API.","code":400}
How do I access the data in $result it current only returns 1
Set return transfer to true to get the page response in $result
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$options = array (
CURLOPT_CONNECTTIMEOUT => 1, // timeout on connect
CURLOPT_TIMEOUT => 1, // timeout on response
CURLOPT_MAXREDIRS => 1 ,
CURLOPT_HTTPHEADER => array("REMOTE_ADDR: $proxy", "HTTP_X_FORWARDED_FOR: $proxy"),
CURLOPT_URL => $url
);
$ch = curl_init();
curl_setopt_array ( $ch, $options );
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
your solution :

Todoist API - convert output from a string to array

Good evening, I have an account on Todoist. I would use the Todoist API to get all the projects. I wrote the following code:
$url = "https://todoist.com/API/v6/sync";
$post_data = array(
'token' => "12345678901234567890abcdefabcdef01234567",
'seq_no' => "0",
'resource_types' => '["projects"]'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
print_r($output);
curl_close($ch);
The output is a string like this:
{"TempIdMapping":{},"seq_no_global":6201059540,"seq_no":6201059540,"UserId":7179424,"Projects":[{"user_id":7179424,"name":"Project1","color":1,"is_deleted":0,"collapsed":0,"id":165361294,"archived_date":null,"item_order":1,"indent":1,"archived_timestamp":0,"shared":false,"is_archived":0},{"indent":1,"name":"Inbox","user_id":7179424,"color":7,"is_deleted":0,"collapsed":0,"inbox_project":true,"archived_date":null,"item_order":0,"is_archived":0,"archived_timestamp":0,"shared":false,"id":165339673}]}
Is there a way to convert this output into an array?
Example:
TempIdMapping => {},
seq_no_global => 6201059540,
seq_no => 6201059540
and so on...
Your output is JSON formated, so you can use json_decode like so
json_decode($output, true);
The second parameter convert the result to an associative array instead of an stdObject

Why is this PHP script the JSON results when I haven't told it to?

So I'm using the only source I've found for sending a post request to Google QPX API. I want to save it in a json_decoded PHP array, but for some reason the $result = curl_exec($ch); line doesn't work, and the json prints onscreen anyways.
Is there something I'm not understanding that is happening in the cURL? Thanks!
$data = array ( "request" => array(
"passengers" => array(
adultCount => 1
),
"slice" => array(
array(
origin => "BOS",
destination => "LAX",
date => "2015-09-09"),
array(
origin => "LAX",
destination => "BOS",
date => "2015-09-10"),
),
solutions => "10"
),
);
$data_string = json_encode($data);
$ch = curl_init('https://www.googleapis.com/qpxExpress/v1/trips/search?key=MY-API-KEY');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
This:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
CURLOPT_RETURNTRANSFER - TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
http://php.net/curl_setopt
Set this option to true if you want to save the result in a variable.

Categories