json post with cURL from a while loop - php

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.

Related

PHP Simple Api post request

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

PHP send and receive XML

I've been working on an API for receiving a XML file which in turn gonna be read in our databse. The parsing and all worked with local XML files. Now the last step was to check if the receiving of the XML was working and there is where I hit a roadblock. Been trying a lot of different things up untill now, but can't seem to get it to work. We would prefer to work with the REST method, but if it's really not gonna work we're willing to switch it up. Seen a lot of questions for sending or receiving a XML file, but never in combination. So hope I can get a solid answer on this and didn't miss a question that is a duplicate.
TL;DR: Sending and receiving XML files through PHP, don't know where I'm making a error
The sending and receiving parts are in different scripts.
//Sending XML script.
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_MUTE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml',
'Content-length: '.strlen($xmlSend)));
curl_setopt($ch, CURLOPT_POSTFIELDS, array("recXML" => $xmlSend));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
//Receiving XML script
if(isset($_REQUEST['recXML'])){
$xmlTest = $_REQUEST['recXML'];
} else {
echo "NO REQUEST XML FOUND ";
}
if(isset($HTTP_RAW_POST_DATA)){
$xmlTest = $HTTP_RAW_POST_DATA;
} else {
echo " NO RAW DATA ";
}
if(isset($_POST['recXML'])){
$xmlTest = $_POST['recXML'];
}else{
echo " NO XML RECEIVED ";
}
if(!isset($xmlTest)){
return;
}
This is not the complete logic, but I think these are the parts that matter, if you want more code just ask.
EDIT:
after some changes and restarting my pc, it finally worked. So not exactly sure which change fixed the problem, but will post the code below in case anyone could ever find use for it.
//Sending script:
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml',
'Content-length: '.strlen($xml)));
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
//receiving script
$xmlTest = file_get_contents("php://input");
echo $xmlTest;
$res = simplexml_load_string($xmlTest);
if($res === false){
echo "Failed loading XML: ";
foreach(libxml_get_errors() as $error){
echo "<br>", $error->message;
}
return;
} else {
//print_r($res);
}
You should send content-Type as application/xml
so your code will become
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml',
'Content-length: '.strlen($xmlSend)));
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlSend);
and on receiving side you can use
$xml = file_get_contents("php://input");
For your current code you can set content-type as application/x-www-form-urlencoded the you can use $_POST['recXML']

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.

How to assign result fro curl to a variable?

I need to do a simple POST request and parse the result. For this i use curl in php. The problem is that i cant assign the result to a variable - it just prints .
My method:
private function sendRequest($data)
{
$ch = curl_init(self::IP . ':' . self::PORT);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch); // HERE IT PRINTS
curl_close($ch);
$parsed_result = #simplexml_load_string(trim($result)); // OR HERE IT
die(var_dump(isset($parsed_result->request_error)));
if (isset($parsed_result->request_error))
$this->AJAXResult(TRUE, (string) $parsed_result->request_error->text);
}
You must add:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1)
if you want curl_exec to return the result of the post request.

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