problems getting curl / json work with php - php

I just wanted to ask one of my servers (let's call him mysql-server) a simple question to get some result out of a MySQL database.
This mysql-server provides the result as json decoded array in the form - e.g. like this:
$data = array("first_name" => "First name","last_name" => "last name");
$data_string = json_encode(array("customer" => $data));
echo $data_string;
which works pretty well and returns something like this:
{"customer":{"first_name":"First name","last_name":"last name"}}
Just to check that everything is fine I added a few lines:
echo "<pre>";
print_r(json_decode($data_string, true))."</pre>";
and got the following:
Array(
[customer] => Array
(
[first_name] => First name
[last_name] => last name
)
)
So everything seems to be fine on this server side.
If I now call the url of that script from the second-server using:
$data_string = json_encode(array('customer' => $customerNo));
$curlHandler = curl_init($url);
curl_setopt_array($curlHandler, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data_string,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_VERBOSE => true,
CURLOPT_STDERR => fopen($fp, 'w'),
//CURLOPT_SSL_VERIFYHOST == 2,
//CURLOPT_VERIFYPEER == true,
CURLOPT_HTTPHEADER => array(
'Accept: application/json',
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
]);
$response = curl_exec($curlHandler);
var_dump(json_decode($response, true));
I got NULL.
Instead of using
echo $response;
brings the following result to the screen:
{"customer":{"first_name":"First name","last_name":"last name"}}
and a
var_dump($response);
brings the following to the screen:
string(268) " {"customer":{"first_name":"First name","last_name":"last name"}} "
So the data is transfered back and stored in the variable $response as it should be, but may anyone give me please a hint, why I can't access it using json_decode?
Many thanks and best
Paul

Related

How Do You POST JSON Data In PHP? (Convert Raw cURL Code Into PHP) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am working with Facebook's API, and I'm trying to conduct a cURL request in PHP.
This request is a POST request and passes some JSON data.
I want this JSON data to be an array within PHP, then pass this into the cURL request.
Here is an example cURL request from FB's documentation.
curl -X POST \
-F 'data=[
{
"event_name": "PageView",
"event_time": 1610378833,
"user_data": {
"fbc": "fb.1.1554763741205.AbCdEfGhIjKlMnOpQrStUvWxYz1234567890",
"fbp": "fb.1.1558571054389.1098115397",
"em": "309a0a5c3e211326ae75ca18196d301a9bdbd1a882a4d2569511033da23f0abd"
}
}
]' \
-F 'access_token=<ACCESS_TOKEN>' \
https://graph.facebook.com/v9.0/<PIXEL_ID>/events
I have tried multiple attempts in PHP, but my array doesn't seem to be parsed correctly.
Here is my PHP Code:
$data = array("data" => array("event_name" => "Purchase", "event_time" => time()),
"access_token" => "EAADZAQ7wNP3UBAMjOcHJV1dvgRYPoyarnLPO5Rr6cwRiOuF0biRTZCJWbCn000U9SD8hovXoKZB0zg1H8PoTI3d4RuvUZC1VQshieXSPcZABiCwqi1rgzzaYZBfMkD6qgAZBKikCtG3jO9SYWanuPUvctypbyoxQm4zVI5Cq8K"
);
$dataString = json_encode($data);
$ch = curl_init('https://graph.facebook.com/v9.0/229975271636842/events');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($dataString))
);
echo $result = curl_exec($ch);
Here is the error:
{"error":{"message":"(#100) param data must be an array.","type":"OAuthException","code":100,"fbtrace_id":"ACWsWbLVtlLZdbMyty_9VKA"}}
Here is Facebook's Documentation.
I would appreciate any help. Thank you.
As the error says, you don't need to json_encode the data.
$curl = curl_init();
$array = [
"data" => [[
"event_name"=> "PageView",
"event_time"=> 1610378833,
"user_data" => [
"fbc" => "fb.1.1554763741205.AbCdEfGhIjKlMnOpQrStUvWxYz1234567890",
"fbp" => "fb.1.1558571054389.1098115397",
"em" => "309a0a5c3e211326ae75ca18196d301a9bdbd1a882a4d2569511033da23f0abd"
]
]]
];
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://graph.facebook.com/v9.0/229975271636842/events',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => json_encode($array),
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
I think that the problem is that an array is missing. The "data" field is an array with an object inside.
Try this:
$data = array( // main object
"data" => array( // data array
array("event_name" => "Purchase", "event_time" => time()), // single data array entry
),
"access_token" => "..."
);
$array = [
"event_name"=> "PageView",
"event_name2"=> "PageView2",
// and so on ...
];
$object = json_decode(json_encode($array) );
$data = ['data'=> $object];
and then pass it to your curl function.
For Nico. Right. I forgort explanation: I think:
-F 'data=[
{
means Object inside array. And the FB Error Response tell us: "error":{"message":"(#100) param data must be an array. And Jack encode the whole data to a datastring.

PHP HTTP POST gets "This API does not support parsing form-encoded input."

Why doesn't this PHP-7 code snippet work properly?
$json = json_encode($data);
curl_setopt_array($this->ch, array(
CURLOPT_URL => '...',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $json,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json; charset=UTF8',
'Content-Length: ' . strlen($json),
),
));
Google's API complains: "This API does not support parsing form-encoded input."
But, what is the correct PHP-foo to specify the encoding that Google wants?
It might be possible that you have non-UTF8 encoded string?
This guy seems to have the same problem https://groups.google.com/forum/#!topic/google-content-api-for-shopping/5I8MHpfbH4A
Well, I found it!!
The subroutine which actually invokes the CURL call (not shown) issued its own curl_setopt of CURLOPT_HTTPHEADER, apparently superseding the option settings shown here.
The code that works looks like this: (with $headers being merged with a few other headers by the CURL-call routine, also not shown here, via CURLOPT_HTTPHEADER).
$json = json_encode($data);
$headers = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json),
'Accept: application/json'
);
curl_setopt_array($this->ch, array(
CURLOPT_URL => '...',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $json,
));
So, I was trying "the right PHP mojo," but failed to realize that some of the options weren't being set – that is, the settings didn't "stick" – because of another bug in my program which was never shown on this ticket.
Now we know: if you use these CURL options, and include these headers (Accept: is actually up to you ...), and be sure that CURL_POSTFIELDS is a string not an array, it will work. Whereas, if you do not do all of these things, cryptic messages will be the result.

CURL getting error:14094410:SSL

This is my code. Am trying get information from a server.
But I got stuck in the middle. Please help me.
Am getting error such as
[errors] => Array ( [0] => error:14094410:SSL
routines:SSL3_READ_BYTES:sslv3 alert handshake failure ) )
Below is the code that I have written please check and help me.
Will appreciate any help.
public function get_quotes(){
$reservation_obj->source = "test";
$reservation_obj->location_code = "test";
$reservation_obj->start_date = "2010-06-01 19:00";
$reservation_obj->end_date = "2010-06-04 13:50";
$reservation_obj->action = "get_quotes";
$json = json_encode($reservation_obj);
$curl_opts = array(
CURLOPT_HEADER => false,
CURLOPT_HTTPHEADER => array('Content-Type: text/json', 'Content-length: '.strlen($json)),
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $json,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => "https://myserver/test.php",
CURLOPT_VERBOSE => false,
CURLOPT_SSLCERT => getcwd()."/newfile.crt.pem",
CURLOPT_SSLCERTTYPE => "PEM",
CURLOPT_SSLKEY=> getcwd()."/newfile.key.pem",
CURLOPT_SSLKEYTYPE => "PEM",
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSLVERSION => 3
);
$curl = curl_init();
curl_setopt_array($curl, $curl_opts);
if(!$response = curl_exec($curl)){
$response->errors[] = curl_error($curl);
}
curl_close($curl);
if(count($response ->errors)){
print_r($response);
}else{
print_r($response);
}
}
comment out the CURLOPT_SSLVERSION => 3 line and try again.
They say the SSL v3 is vulnerable (idk much about that, sorry), so many of the servers do not allow it using the v3.
Here is an article if you are interested. https://access.redhat.com/articles/1232123
Please let me know the result after you try it. thanks.

get data from database using curl and json

Do any of you know a way to get datas from a database of a website? I already studied and made a program that POST data using json. It gets the shipment status of a certain tracking number and if it's shipped, it will be changed to delivered. And I already done that.
Now what I'm trying to do is get all the datas, or the row of that tracking number and then encode it to JSON. But I don't know what to do.
This is how I did the first program: on getting a specific tracking number and update the status to delivered.
<?php
$url='https://sample.com.ph';
$apikey='apikey';
$method ='SendPackageStatus';
$data = array(
'package' => array(
'tracking_number' => '735898532',
'package_status' => 'delivered',
'failed_reason' => '',
'updated_at' => '2014-01-01 07:02:14'
)
);
$check=json_encode($data);
$postdata = "&data=$check&apikey=$apikey&method=$method";
$ch = curl_init();
curl_setopt_array(
$ch,
array(
CURLOPT_URL => $url.'/webservice/',
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_VERBOSE => true,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $postdata,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => array('Content-type: application/x-www-form-urlencoded',
)
)
);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
Why not use mysql?... you can store json string on db (as..strings). I dont follow what you are trying to do.

PHP cURL Json Post - doing something wrong

I'm new to php and I'm trying to create a simple example for calling our company api. I got NetBeans IDE 7.1.2 to work last night (yay) but I cannot seem to get the following code to show me anything. I can run it in the debugger. I can step through it. I even get to the end without errors, but the curl_exec returns just 0. I have added the CURLOPT_PROXYPORT so that I can get fiddler to see the traffic, but fiddler sees nothing. I am also trying to run this as a php command line (if that has any bearing).
I know I'm doing something stupid... but that's the problem with stupid.
<?php
$url = 'https://target.boomerang.com/api/JobCreate';
$authToken = 'phptest';
$data = array(
"emailHTML" => "Howdy",
"jobKind" => "email",
"senderEmail" => "bob#boomerang.com",
"subject" => "My howdy email"
);
$data_string = json_encode($data);
$headers = array(
'Content-type: application/json',
'auth_token: ' . $authToken,
'Accept: application/json',
'Expect:'
);
$ch = curl_init();
$args = array(
CURLOPT_URL => $url,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $data_string,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_PROXYPORT => "localhost:8888"
);
curl_setopt_array($ch, $args);
$res = curl_exec($ch);
$res_data = json_decode($res, true);
print($res_data);
?>
Thanks for any help.
So the problem was caused by SSL certificate mismatch? I suppose it can be solved by adding this...
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
...into $args array.

Categories