PHP Simple Api post request - php

Hi there I never develop in php but I have to create a small function to do a post request to my meteor node application. The end point works fine I have been testing it. I am trying to use the post request to get my login token back. Providing username and password it should return json data even it is incorrect it returns json data saying login refused.
It seem noting is happening tho. My return data seems to always be null.
As I said I never really used php nore do I plan on using it much. But here is my code probably very easy mistake to fix.
<?php
$ch = curl_init();
$params = array(
"username" => "apilogin",
"password" => "12345"
);
echo httpPost("http://127.0.0.1:3000/api/login", $params);
function httpPost($url,$params)
{
$postData = http_build_query($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
$output=curl_exec($ch);
// Check for errors
if($output === FALSE){
echo "false";
die(curl_error($ch));
}
// Decode the response
$output = json_decode($response, TRUE);
curl_close($ch);
return $output;
}
?>

change:
$output = json_decode($response, TRUE);
into:
$output = json_decode($output, TRUE);
you never made a variable $response

Related

JSON to PHP Array error

i am having trouble getting a JSON file to a php-array.
i got a json-file as response from an api (request done with curl)
and want to make an array out of it but it won't work.
Here is my code:
<?php
class modExpose{
public static function getFunction($id){
//In my code i am "preparing" the request here
// *********** cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url.$qry_str);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
}
$id = $_GET['id'];
$data = modExpose::getFunction($id);
$array = json_decode($data,true);
print_r($array);
?>
the print_r function only delivers: 1. (same does the var_dump() function).
I also tried adding html_entity_decode() but the problem still remains.
Thank's for helping!
That is probably because the return value of your curl_exec() call is true on success and that is all you are returning from your method.
If you want to get the data that was returned by the curl call, you need to set the CURLOPT_RETURNTRANSFER option:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url.$qry_str);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// Return the result on success
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
// Now response will contain the results of your curl call
$response = curl_exec($ch);
Apart from that I assume you have checked the variables that seem to be undefined in your example code.

PHP PUT Request

I have some documentation for an API system and it is telling me to send a PUT Request to a service URL, they have provided this:
PUT /domain/manage/renew/{domain_name}/{period}
along with the main URL to send the request to.
I thought to do this i would need to use cURL so I created the following:
$data = array("a" => $a);
$ch = curl_init($this->_serviceUrl . $id);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$response = curl_exec($ch);
if(!$response) {
return false;
}
but they have also said:
The HTTP request header must contain the User, Hash and Encryption.
User: <username>
Hash: <authentication_hash>
Encryption: SHA-512
My question is:
How do i include this in the call?
and how do i sent both {domain_name} and {period} as per the url above?
** UPDATED **
Send the headers like this:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'User: '.$user, // change the variables to whatever you need, i.e. $this->user or whatever
'Hash: '.$hash, // same here
'Encryption: SHA-512'
]);
$response = curl_exec($ch);
if(!$response) {
return false;
}
As for the URL, do something like this:
$ch = curl_init('http://www.example.com/domain/manage/renew/'.urlencode($domain_name).'/'.urlencode($period));

PUT Request via CURL

I'm trying to make an CURL PUT REQUEST, my code looks like:
public function assignProfile($token, $organizationId, $profileId)
{
//define enviroment and path
$host = enviroment;
$path = "/admin/organizations/".$organizationId."/users";
$data_string = '["'.$profileId.'"]';
// set up the curl resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host.$path);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: Bearer '.$token.'',
'Content-Length: ' . strlen($data_string)
));
echo "<br>OK<br>";
// execute the request
$output = curl_exec($ch);
// return ID for a new case
$output = json_decode($output);
var_dump($output);
}
Each part looks correct, when I var_dump $path, $host, even $data_string looks correct. However var_dump() at the end throw just NULL
I expect I'm doing something wrong or missing something really important.
May I ask you for some advise?
Thanks
EDIT:
What i do with it:
// define
define("Audavin","here is some uniqe ID");
.
.
.
$Users = new Users;
// this return Auth token ( I verify this work with echo )
$token = $Users->authorization();
// Calling method mentioned above
$Users->assignProfile($token,"here is org id", Audavin);
I would start by making sure the URL you're making the request to actually works and returns a valid response, you can do so by using a simple REST client (like POSTMAN chrome extension for example)
If you do get a response back, try and see if it's indeed a valid JSON, if not, that could be why you're not getting anything back from json_decode (more on return values here: http://php.net/manual/en/function.json-decode.php)
Finally, It is suggested you add curl_close($ch) to the end of your code to make sure your release the curl handle.

json post with cURL from a while loop

I am trying to post json data with cURL. The idea is: In case the url is not accessible ( for example failure of internet connection) keep trying to post the json while you succeed. It works but when I put it in while loop it executes only once. What am I doing wrong:
$jsonDataEncoded = json_encode($event);
echo $jsonDataEncoded;
echo "\n";
$send_failure = true;
while ($send_failure) {
$url = "a";// intentionally inaccessible url
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($jsonDataEncoded)));
$result = curl_exec($ch);
if(curl_errno($ch)){
throw new Exception(curl_error($ch));
} else {$send_failure = false;}
return $result;
}
You must print and check the value in $result using var_dump($result); .
If there is any connection error it returns the error code which you can check manual in IF condition. Hope this might help you.

php - using curl to consume this web service

I saw this post on consuming a web service using CURL: Consume WebService with php
and I was trying to follow it, but haven't had luck. I uploaded a photo of the web service I'm trying to access. How would I formulate my request given the example below, assuming the URL was:
https://site.com/Spark/SparkService.asmx?op=InsertConsumer
I attempted this, but it just returns a blank page:
$url = 'https://xxx.com/Spark/SparkService.asmx?op=InsertConsumer?NameFirst=Joe&NameLast=Schmoe&PostalCode=55555&EmailAddress=joe#schmoe.com&SurveyQuestionId=76&SurveyQuestionResponseId=1139';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
$xmlobj = simplexml_load_string($result);
print_r($xmlobj);
Really, you should probably look at the SOAP extension. If it is not available or for some reason you must use cURL, here is a basic framework:
<?php
// The URL to POST to
$url = "http://www.mysoapservice.com/";
// The value for the SOAPAction: header
$action = "My.Soap.Action";
// Get the SOAP data into a string, I am using HEREDOC syntax
// but how you do this is irrelevant, the point is just get the
// body of the request into a string
$mySOAP = <<<EOD
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope>
<!-- SOAP goes here, irrelevant so wont bother writing it out -->
</soap:Envelope>
EOD;
// The HTTP headers for the request (based on image above)
$headers = array(
'Content-Type: text/xml; charset=utf-8',
'Content-Length: '.strlen($mySOAP),
'SOAPAction: '.$action
);
// Build the cURL session
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $mySOAP);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Send the request and check the response
if (($result = curl_exec($ch)) === FALSE) {
die('cURL error: '.curl_error($ch)."<br />\n");
} else {
echo "Success!<br />\n";
}
curl_close($ch);
// Handle the response from a successful request
$xmlobj = simplexml_load_string($result);
var_dump($xmlobj);
?>
The service requires you to do a POST, and you're doing a GET (curl's default for HTTP urls) instead. Add this:
curl_setopt($ch, CURLOPT_POST);
and add some error handling:
$result = curl_exec($ch);
if ($result === false) {
die(curl_error($ch));
}
This is the best answer because using this once you need to login then
get some data from webservices(third party site data).
$tmp_fname = tempnam("/tmp", "COOKIE"); //create temporary cookie file
$post = array(
'username=abc#gmail.com',
'password=123456'
);
$post = implode('&', $post);
//login with username and password
$curl_handle = curl_init ("http://www.example.com/login");
//create cookie session
curl_setopt ($curl_handle, CURLOPT_COOKIEJAR, $tmp_fname);
curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $post);
$output = curl_exec ($curl_handle);
//Get events data after login
$curl_handle = curl_init ("http://www.example.com/events");
curl_setopt ($curl_handle, CURLOPT_COOKIEFILE, $tmp_fname);
curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($curl_handle);
//Convert json format to array
$data = json_decode($output);
echo "Output : <br> <pre>";
print_r($data);
echo "</pre>";

Categories