How to store curl response in a variable in PHP? - 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.

Related

Why does my cURL fails? I'm trying to verify user identity on an API

Here are the codes:
<?php
class General{
#to verify user password with api
public static function verifyUser($user,$pswd){
#url
$url = 'https://api.hp.upm.edu.my/cron/request/verify.php';
# initiate cur
$ch = curl_init($url);
# create json data
$jsonData = array(
'jtoken' => "test123",
'id' => "$user",
'pass'=> "$pswd"
);
#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'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
#Execute the request
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
}
?>
The passed data are username and password, identified by $user and $pswd respectively
The problem is, the end result should return something.
But I found it empty, after checking.
So, what I learned so far are:
I checked the user and password, they are all intact
when I print $ch during "initiate cur", it prints something
when I printed $ch
However, when I printed $result after curl_exec, it is empty.
What do I do? Where is my mistake? Is it the problem of the api url or soemthing else? Please, I need your help
Edit:
Someone suggested that using json_decode will help with this. But, I have already implemented json_decode, after $result is returned.
$result = General::verifyUser($_POST['user'], $_POST['pass']);
$obj = json_decode($result, true);
Above is the method call that passes the username and password to the "General" class.
I have printed curl_error for $ch and it says:
"Could not resolve host: api.hp.upm.edu.my"

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']);

Curl api call return empty array

If I make this call with file_get_contents, it is returning the data, but with curl it show error true, code: 204, with all empty arrays, I m making post of single query string, I am just a novice in programming any help, thanks.
Array ( [error] => 1 [dname_avail] => [domname] => Array ( [tld_code] => )
<?php
$json = '';
if(isset($_POST['querystring'])){
$string_sanitised = $_POST['querystring'];
$query_var= str_replace(" ","",$string_sanitised);
// set HTTP header
$headers = array('Content-Type: application/json',);
// *** create the call to the API and pass parameters along
//apikey =xx67676876868686868686
$url = 'http://api.mydomain.com/domlook/domname/'.$query_var.'/apikey/xx67676876868686868686/';
// Open connection
$ch = curl_init();
// Set the url, number of GET vars, GET data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Execute request
$result = curl_exec($ch);
// Close connection
curl_close($ch);
// get the result and parse to JSON
$result_arr = json_decode($result, true);
print_r($result_arr);
}else{
echo "error";
}
?>

JSON/CURL issue

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'));

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