using CURL in php to retrieve data from an api - php

I have an api link which is working fine on terminal. I wand to use same api link to retrieve data using CURL in php. I tried below code:
<?php
// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, 'urlxxxxx');
// execute the request
$output = curl_exec($ch);
// output the profile information - includes the header
echo "curl response is : <br> ".($output). PHP_EOL;
// close curl resource to free up system resources
curl_close($ch);
?>
but I am getting response as :
curl response is :
{ "error" : "JSON syntax error: malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before \"(end of string)\") at /usr/share/perl5/JSON.pm line 171.\n" }
I am new to CURL guide me regarding the issue for resolving it.

Add:
curl_setopt($ch, CURLOPT_POSTFIELDS, "{}");
so you send an empty JSON object as the parameter. This is the PHP equivalent of
-d "{}"
from the command line.
To put some other array into the post data, use json_encode.
$data = array('userId' => array(),
'user_list' => array("1", "2", "3", "4", "5", "6", "7", "8")
);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data);

You either need to set the method to 'GET' by removing curl_setopt($ch, CURLOPT_POST, true);
Or supplying valid JSON curl_setopt($curl, CURLOPT_POSTFIELDS, "{}");

Related

Sending POST via curl to the server doesn't work

I am trying to send a POST request to the server (JBOSS) which is running on localhost:9090 as shown below but it doesn't seem to be working. I mean, I am not seeing my webservice getting executed. Am I doing everything right below?
Since $_POST["mydata"] contains the following :
[{ "name": "FirstName", "value": "Mickey" }, { "name": "LastName", "value": "Mouse" }]
which is the result of running JSON.stringify() on the javascript object (using serializeArray()), I am not sending application/json related thing in the header.
$urlTest = 'http://localhost:9090/JAXRS_POST_Request/rest/Request/insertDataToDB';
$rCURL = curl_init();
curl_setopt($rCURL, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($rCURL, CURLOPT_POSTFIELDS, $_POST["myData"]);
curl_setopt($rCURL, CURLOPT_URL, $urlTest);
curl_setopt($rCURL, CURLOPT_HEADER, 0);
curl_setopt($rCURL, CURLOPT_RETURNTRANSFER, 1);
$response_post = curl_exec($rCURL);
curl_close($rCURL);
But if I have to manually test the webservice using a client like POSTMAN, I have to specify under headers as Content-Type : application/json and send it like this through the Body and it works perfectly fine there :
But while sending the request via curl, since JSON.stringify() converts the javascript object to string to send it to the server, I am confused whether I need to use header thing in my POST request or not.
P.S. A simple curl based GET request has worked fine for me so my application is successfully contacting the server.
Try this:
$urlTest = 'http://localhost:9090/JAXRS_POST_Request/rest/Request/insertDataToDB';
$data = 'FirstName=Mickey&LastName=Mouse';
$rCURL = curl_init();
curl_setopt($rCurl, CURLOPT_POST, true);//
curl_setopt($rCURL, CURLOPT_POSTFIELDS, $data);
curl_setopt($rCURL, CURLOPT_URL, $urlTest);
curl_setopt($rCURL, CURLOPT_HEADER, 0);
curl_setopt($rCurl, CURLOPT_RETURNTRANSFER, true);
if(curl_exec($rCurl) === false){
echo 'Curl error: ' . curl_error($rCurl);
}else{
$response_post = curl_exec($rCURL);
}
curl_close($rCurl);

How can I verify that I make a proper POST via cURL in PHP?

I have a sample json object contain these data. I'm trying to store those data in a variable, and passing through curl POST
$json = '{
"mac": "1234567890",
"dns": "8.8.8.8,4.2.2.1",
"acl_mode": 1
}';
$url = 'http://my-site.com/api';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array('json' => $json)));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
dd($result);
My result is 500
{
"status": 500,
"error_code": 1005
}
Is the way I set up my curl post wrong ?
After testing with curl in the terminal we found out that the endpoint consumes the entire POST payload without a key.
This was used for testing
curl -X POST -d '{"mac": "1234567890","dns": "8.8.8.8,4.2.2.1","acl_mode": 1}' http://mysite/api
So sending the $json payload as it is, without the json_encode and the array encapsulation.
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
worked just fine.

How to use -data curl in PHP

With curl from linux bash I can download a webpages passing some variables
curl --data "var1=val1&var2=val2&var3=&var4=val4&btnSubmit=btnName" https://<url> -o "<fileToSave>"
I need to do the same things but to get the full html code of that page into a php variable.
I'm trying with this:
<?php $ch = curl_init();
$post_data = array (
"var1" => "val1",
"var2" => "val2",
"var3" => "",
"var4" => "val4",
"btnSubmit" => "btnName"
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$response = curl_exec($ch);
?>
The problem is that from bash I can retrieve the html pages and save it with this code my $response value is empty.
What's wrong?
Use http_build_query() over the $post_data, otherwise curl will assume to POST multipart/form-data posting based on the Array Data type(that's why it is not working for you).
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
http_build_query() converts the array into key1=value1&key2=value2 formated string with automatic urlencode().
Seems like you are connecting to a HTTPs URL. You should enable this cURL parameter.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

CURL,JSON and PHP

I am working to connect with an API using curl and PHP
I have this CURL statement
curl -i --user api:YXBpOmFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6MDEyMzQ1 --data-binary #test.png https://api.blahblah.com/blah
where YXBpOmFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6MDEyMzQ1 is the api key and #test.png is the image file I need to transfer to the API for upload. What I don't get is how to write the curl for the link above
and I also have this Example Statement as given by the site for developers(looks a JSON)
POST /blah HTTP/1.1
Host: api.blahblah.com
Authorization: Basic YXBpOmFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6MDEyMzQ1
Till now, I have written this up,
$url = 'https://api.tinypng.com/shrink';
$image = 'bf4lwp2.png';
$key = 'YXBpOmFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6MDEyMzQ1';
$jsonscript = array(
'Host' => 'api.tinypng.com',
'Authorization' => $key );
$json_string = json_encode($jsonscript);
$ch = curl_init($url);
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'api:'.$key);
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $image);
// Execute
$result=curl_exec($ch);
Also, if my request is a success, I get this...
HTTP/1.1 201 Created
Location: https://api.blahblah.com/blahblah.png
Content-Type: application/json; charset=utf-8
{
"input": {
"size": 87654
},
"output": {
"size": 102020,
"ratio": 0.236
}
}
I know I have to use file_get_contents() to get all that, but I don't know what URL to put in that function.
To get data from json first you can use json decode and than use foreach loop to
parse those data into variables

Neo4j using Traverser via REST HTTP

I'm trying to use Neo4js Traverser via the HTTP API.
If I use it via curl on the command line it works fine, but when I try to use it via curl through PHP I get an error all the time.
This is curl command:
curl -H Accept:application/json -H Content-Type:application/json -X POST -d '{"order":"depth first"}' http://localhost:7474/db/data/node/5/traverse/node
And this is my PHP Code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost:7474/db/data/node/5/traverse/node");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept:application/json',
'Content-Type:application/json'
));
curl_setopt($ch, CURLOPT_POSTFIELDS, '"{"order": "depth first"}"');
$output = curl_exec($ch);
echo '<pre>';
var_dump(curl_getinfo($ch));
var_dump($output);
curl_close($ch);
This is the error I get:
HTTP ERROR 500
Problem accessing
/db/data/node/5/traverse/node. Reason:
java.lang.String cannot be cast to java.util.Map
Any Ideas?
Looks like you have quotes before the JSON string:
curl_setopt($ch, CURLOPT_POSTFIELDS, '"{"order": "depth first"}"');
Might want to try this:
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"order": "depth first"}');
EDIT: Although better yet, I'd use json_encode with an associative array to ensure proper escaping if necessary:
$json_data = array("order" => "depth first");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json_data));

Categories