JSON/CURL issue - php

My CURL request takes in two variables as shown below:
<?php
$id = $_GET["id"];
$review = $_GET["review"];
$url = 'http://edward/~treeves/ratingJSON.php';
$jsonData = array("id" => "$id", "review" => "$review");
$ch = curl_init($url);
$jsonDataEncoded = json_encode($jsonData);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('json' => $jsonDataEncoded));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
?>
And posts it to the web service shown below:
<?php
header("Content-type: application/json");
try {
$conn = new PDO("mysql:host=localhost;dbname=treeves;", "treeves", "oopheiye");
$json = $_POST["json"];
$data = json_decode ($json, true);
$result = $conn->query("INSERT INTO poi_reviews (poi_id, review)
VALUES ('$data[ID]', '$data[review]')");
} catch (Exception $e) {
echo $e->getMessage();
}
?>
However the data being inserted is blank. When I use var_dump($data) on the web service is shows 1 NULL. I think it's to do with the variables in the CURL file as the web service works. Any ideas?
Update
Taking out the HTTP header and using 'var_dump($data, $error === JSON_ERROR_UTF8)' is returning the following:
array(2) { ["id"]=> string(4) "1014" ["review"]=> string(1) "2" } bool(false)

Here you set up form encoded data with one key (json) that has a value (of JSON encoded data):
curl_setopt($ch, CURLOPT_POSTFIELDS, array('json' => $jsonDataEncoded));
Here you tell the server that you are sending JSON and not form encoded data.
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
One of the above has to be wrong, since they are contradictory.
Here you try to read form encoded data:
$_POST["json"];
So claiming you are sending plain JSON is wrong (your JSON is encapsulated in form encoding).
Remove this line:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

Related

Sending array using curl

I want to send data from server 1 to server 2, first I select necessary data from the database, but how to send data with curl? I understand that I cannot send $result parameter just like in my code, but how should I do this?
My Code server 1:
public function setDivisions(){
$result = $this->conn->query("SELECT *FROM data_divisions");
$ch = curl_init('https://example.com/api.php?siteid='.$this->site_key.'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $result);
curl_setopt($ch, CURLOPT_POST, 1);
$response = curl_exec($ch);
print_r($response);
}
Code on server 2:
$array = $_POST['result'];
//loop throw array and insert data into database
you can use it that way.
$ch = curl_init('https://upxxx.cod3fus1ontm.com/curl/json');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode((object)["records" => json_encode($result)]));
$response = curl_exec($ch);
var_dump($response);
on receipt, like this!
$json = file_get_contents("php://input");
$content = json_decode($json, true);
$records = json_decode($content['records'], true);
foreach($records as $record) {
echo $record['id'] . " - " . $record['text'] . "<br/>";
}
remember, that as you did to encode, you will have to do to decode
Come on, php://input returns all raw data after the request's HTTP headers, regardless of content type.
When we do this with file_get_contents (which reads the contents of a file and puts it into a variable of type string), we can read the content that was sent by curl.
Reviewing the code, you can optimize as follows, when sending to the server you placed, I suggested:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode((object)["records" => json_encode($result)]));
you can replace it with:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($result));
it's much simpler, but it's very important to put the query result inside a json_encode
finally, you can access the entire body of the message, through file_get_contents ("php://input") and put it inside a variable, which is nothing more than a JSON of the your query.
for you to understand how the parameters were passed, it is interesting to do the following:
$json = file_get_contents("php: // input");
var_dump($json); <- Here you see the thing as it is.
$records = json_decode($json, true); <- Here you generate an object with the content of json
var_dump($records);
With that, I think that solves the situation.
on server 1
$result = "result=".base64_encode($result)
curl_setopt($ch, CURLOPT_POSTFIELDS, $result);
...
on server 2
$array = base64_decode($_POST['result']);

Saving returning value from graphql in php variable

Iam making a mutation to graphql from php via cURL. My GraphQl query is:
mutation MyMutation {
insert_presentaciones(objects: {imagen: "logo.png", presentacion: "Ernesto", teatro_id: 3}) {
returning {
id
}
}
}
how I can store this returning value "id" into a variable in php. My entire code is this until now:
<?php
$service_url = 'http://100.100.100.175:8080/v1/graphql';
$curl = curl_init($service_url);
$curl_post_data = array("query" => 'mutation MyMutation {insert_presentaciones(objects: {imagen: "logo.png", presentacion: "Ernest", teatro_id: 3}){returning {id}}}');
$data_string = json_encode($curl_post_data);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('Hubo un error al ejecutar el cURL. Info Adicional: ' . var_export($info));
}
curl_close($curl);
echo $curl_response;
echo $info;
?>
It inserts correctly the data into the database but when it returns the Id I dont know how to store it.
It returns:
{"data":{"insert_presentaciones":{"returning" : [{"id":167}]}}}
i want to store that 167 into a variable.
Any help?? thanks a lot and sorry for my english
its a json object use json_decode (php.net/manual/en/function.json-decode.php)
the code should look like so first decode and then you can get the id
$decoded= json_decode($curl_response, true);
and then to get the data out of it you have a couple of ways.
$id=null; // default value
if(isset($decoded['data']['insert_presentaciones']['returning'][0]['id'])){
//check if the array element is set if yes asign value
$id=$decoded['data']['insert_presentaciones']['returning'][0]['id'];
}

Issue sending headers to Rest API

I have to write to an API, and nothing seems to work. When I use apitester.com it works though. When I use my app, it doesn't. I output the headers and payload and they look the same between the two, so I am assuming I'm doing something wrong. Here is my PHP to send data to the API
<?php
$email = $_POST['email'];
$expired = NULL;
$funded = TRUE;
$data = array(
"email" => $email,
"expired" => $expired,
"funded" => $funded
);
$url = 'https://my.rest.api';
$json_string = json_encode($data);
$headers = array (
"Content-Type: application/json",
"Authorization: Bearer xxx"
);
$channel = curl_init($url);
curl_setopt($channel, CURLOPT_RETURNTRANSFER, true);
curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($channel, CURLOPT_HTTPHEADER, $headers);
curl_setopt($channel, CURLOPT_POSTFIELDS, $json_string);
curl_setopt($channel, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($channel, CURLOPT_CONNECTTIMEOUT, 10);
$statusCode = curl_getInfo($channel, CURLINFO_HTTP_CODE);
curl_exec($channel);
http_response_code($statusCode);
if ( $statusCode != 200 ){
echo "Data submitted was ".$json_string." Returned status code: {$statusCode} \n".curl_error($channel);
} else {
echo $response;
}
//I turn the below 2 lines on and off to see what I am actually sending
// print_r($headers);
// echo $json_string;
curl_close($channel);
?>
I get the returned status code of "0" on my app, but "200" using the tester. Is there something obviously wrong with the curl options I am sending?
If you got status 0, it means that the HTTP request didn't complete at all. You can use the following functions to find out what error happened:
curl_errno
curl_errstr
Sidesnotes:
You're echoing $response, but that variable doesn't exist.
Using CURLOPT_SSL_VERIFYPEER is a really bad idea. Make sure you remove it before you go to production.

How to store curl response in a variable in PHP?

I am working on an API. When I make request curl print the response on browser. So, my question is how to store response in variable? and How to insert it into database?
<?php
//API Url
$url = 'http://114.143.206.69:803/StandardForwardStagingService.svc/GetAWBNumberGeneratedSeries';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
"BusinessUnit" => "ECOM",
"ServiceType" => "FORWARD",
"BatchID" => "Jopu7E9821"
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//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','XBKey:******'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Execute the request
$result = curl_exec($ch);
$status = curl_getinfo($ch);
My Response after var_dump($result)
As described in the documentation ...
Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.
So your code has to look like this
$result = curl_exec($ch);
// as you mentioned the response is a json string (screenshot)
$decoded_result = json_decode($result);
// output it on the screen
echo "<pre>";
var_dump($result);
echo "</pre>";
// insert into database (in case $result is an array)
$sql = "INSERT INTO table (column1, column2) VALUES (:result1, :result2)";
$pdo = new \PDO(...);
$stmt = $pdo->prepare($sql);
$stmt->execute([
':result1' => $result['bla'],
':result2' => $result['blubb'],
]);
That should be all you have to do.

php curl help with google url shortner api

Im trying to shorten a url using ggole api's.Here is my php code .It gives a blank page when i load
<?php
define('GOOGLE_API_KEY', 'GoogleApiKey');
define('GOOGLE_ENDPOINT', 'https://www.googleapis.com/urlshortener/v1');
function shortenUrl($longUrl)
{
// initialize the cURL connection
$ch = curl_init(
sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
);
// tell cURL to return the data rather than outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// create the data to be encoded into JSON
$requestData = array(
'longUrl' => $longUrl
);
// change the request type to POST
curl_setopt($ch, CURLOPT_POST, true);
// set the form content type for JSON data
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
// set the post body to encoded JSON data
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
// perform the request
$result = curl_exec($ch);
curl_close($ch);
// decode and return the JSON response
return json_decode($result, true);
}
if (isset($_POST['url'])) {
$url = $_POST['url'];
$response = shortenUrl('$url');
echo sprintf(
$response['longUrl'],
$response['id']
);
}
?>
My html file:
<html>
<head>
<title>A BASIC HTML FORM</title>
</head>
<body>
<FORM NAME ="form1" METHOD =" " ACTION = "shortner.php">
<INPUT TYPE = "TEXT" VALUE ="Enter a url to shorten" name="url">
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Shorten">
</FORM>
</body>
</html
I think I have found a solution to your problem. Since you are connecting to a URL that uses SSL, you will need to add some extra parameters to your code for CURL. Try the following instead:
<?php
define('GOOGLE_API_KEY', 'GoogleApiKey');
define('GOOGLE_ENDPOINT', 'https://www.googleapis.com/urlshortener/v1');
function shortenUrl($longUrl)
{
// initialize the cURL connection
$ch = curl_init(
sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
);
// tell cURL to return the data rather than outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// create the data to be encoded into JSON
$requestData = array(
'longUrl' => $longUrl
);
// change the request type to POST
curl_setopt($ch, CURLOPT_POST, true);
// set the form content type for JSON data
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
// set the post body to encoded JSON data
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
// extra parameters for working with SSL URL's; eypeon (stackoverflow)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
// perform the request
$result = curl_exec($ch);
curl_close($ch);
// decode and return the JSON response
return json_decode($result, true);
}
if (isset($_POST['url'])) {
$url = $_POST['url'];
$response = shortenUrl('$url');
echo sprintf(
$response['longUrl'],
$response['id']
);
}
?>
I think it's coming form your html. You didn't put the form methode, so it send data by get.
And you show something only if you have post.
Try to do in the form method="post"
Edit
Bobby the main problem is that you don't have one problem but several in this code.
First if you don't do
<FORM NAME="form1" METHOD="POST" ACTION="shortner.php">
the if (isset($_POST['url'])) will never return true, because the variable send by the form will be GET (or do a if (isset($_GET['url']))).
Secondly you call the function with { $response = shortenUrl('$url'); }. Here you're not sending the url value but the string '$url'. So your variable $longUrl is always '$url'.
Thirdly you don't use sprintf like you should.
echo sprintf(
$response['longUrl'],
$response['id']
);
Sprintf need to take a string format:
echo sprintf("%s %s" // for example
$response['longUrl'],
$response['id']
);
But do you know that you can do directly
echo $response['longUrl'] . ' ' . $response['id'];
You can concatenate string directly with . in php
curl_exec() returns boolean false if something didn't go right with the request. You're not testing for that and assuming it worked. Change your code to:
$result = curl_exec($ch);
if ($result === FALSE) {
die("Curl error: " . curl_error($ch);
}
As well, you need to specify CURLOPT_RETURNTRANSFER - by default curl will write anything it receives to the PHP output. With this option set, it'll return the transfer to your $result variable, instead of writing it out.
You need to set CURLOPT_RETURNTRANSFER option in your code
function shortenUrl($longUrl)
{
// initialize the cURL connection
$ch = curl_init(
sprintf('%s/url?key=%s', GOOGLE_ENDPOINT, GOOGLE_API_KEY)
);
// tell cURL to return the data rather than outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// create the data to be encoded into JSON
$requestData = array(
'longUrl' => $longUrl
);
// change the request type to POST
curl_setopt($ch, CURLOPT_POST, true);
// set the form content type for JSON data
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
// set the post body to encoded JSON data
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// perform the request
$result = curl_exec($ch);
curl_close($ch);
// decode and return the JSON response
return json_decode($result, true);
}
if (isset($_POST['url'])) {
$url = $_POST['url'];
$response = shortenUrl('$url');
echo sprintf(
$response['longUrl'],
$response['id']
);
}
// Create cURL
$apiURL = https://www.googleapis.com/urlshortener/v1/url?key=gfskdgsd
$ch = curl_init();
// If we're shortening a URL...
if($shorten) {
curl_setopt($ch,CURLOPT_URL,$apiURL);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json"));
}
else {
curl_setopt($ch,CURLOPT_URL,$this->apiURL.'&shortUrl='.$url);
}
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// Execute the post
$result = curl_exec($ch);
// Close the connection
curl_close($ch);
// Return the result
return json_decode($result,true);

Categories