I would like to perform a PUT operation on a webservice using CURL. Let's assume that:
webservice url: http://stageapi.myprepaid.co.za/api/ConsumerRegisterRequest/cac52674-1711-e311-b4a8-00155d4905d3
municipality= NMBM
sgc= 12345
I've written the code below, but it outputs this error message: "ExceptionMessage":"Object reference not set to an instance of an object.". Any help would be so much appreciated. Thanks!
<?php
function sendJSONRequest($url, $data)
{
$data_string = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json',
'X-MP-Version: 10072013')
);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
ob_start();
$result = curl_exec($ch);
$info = curl_getinfo($ch);
if ($result === false || $info['http_code'] == 400) {
return $result;
} else {
return $result;
}
ob_end_clean();
curl_close($ch);
}
$mun = $_GET['municipality'];
$sgc = $_GET['sgc'];
$req = $_GET['req']; //cac52674-1711-e311-b4a8-00155d4905d3
//myPrepaid PUT URL
echo $mpurl = "http://stageapi.myprepaid.co.za/api/ConsumerRegisterRequest/$req";
// Set Variables
$data = array("Municipality" => "$mun", "SGC" => "$sgc");
//Get Response
echo $response = sendJSONRequest($mpurl, $data);
?>
I copied your code, but changed it so it pointed at a very basic HTTP server on my localhost. Your code is working correctly, and making the following request:
PUT /api/ConsumerRegisterRequest/cac52674-1711-e311-b4a8-00155d4905d3 HTTP/1.1
Host: localhost:9420
Content-Type: application/json
Accept: application/json
X-MP-Version: 10072013
Content-Length: 37
{"Municipality":"NMBM","SGC":"12345"}
The error message you're receiving is coming from the stageapi.myprepaid.co.za server. This is the full response when I point it back to them:
HTTP/1.1 500 Internal Server Error
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 30 Aug 2013 04:30:41 GMT
Connection: close
Content-Length: 867
{"Message":"An error has occurred.","ExceptionMessage":"Object reference not set to an instance of an object.","ExceptionType":"System.NullReferenceException","StackTrace":" at MyPrepaidApi.Controllers.ConsumerRegisterRequestController.Put(CrmRegisterRequest value) in c:\\Workspace\\MyPrepaid\\Prepaid Vending System\\PrepaidCloud\\WebApi\\Controllers\\ConsumerRegisterRequestController.cs:line 190\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)"}
You may want to check out the API to make sure you're passing them the correct information. If you are, the problem could be on their end.
And while I realize this isn't part of your question and this is in development, please remember to sanitize any data from $_GET. :)
Try with:
curl_setopt($ch, CURLOPT_PUT, true);
Related
I've tried to send a CSV File to eBay FileExchange Service.
I'm writing an application to update a lot of products on eBay at the same time.
When I upload the test.csv by using the eBay CSV-Manager the update will be success, but with the script nothing will happens after post the data.
I've treid the following steps:
Create a separate token for FileExchange.
https://signin.ebay.de/ws/eBayISAPI.dll?SignIn&runame=F-FILEEXL51P1EHH6L899Q9B969GE134DK-FileUpload
Then I use the following script:
$token = 'AgAAAA**AQAAAA**aAAAAA************';
$ebay_url = 'https://bulksell.ebay.com/ws/eBayISAPI.dll?FileExchangeUpload';
$sendheaders = array(
'User-Agent: My Client App v1.0'
);
$fields = array(
'token' => $token,
'file' => '#test.csv'
);
$ch = curl_init($ebay_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 1); // set to 0 to eliminate header info from response
curl_setopt($ch, CURLOPT_NOBODY, 0); // set to 1 to eliminate body info from response
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); // use HTTP/1.0 instead of 1.1
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response. ###
curl_setopt($ch, CURLOPT_HTTPHEADER, $sendheaders);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); // use HTTP POST to send form data
$resp = curl_exec($ch); //execute post and get results
if(!curl_exec($ch)) {
die('Error: ' . curl_error($ch) . ' - Code: ' . curl_errno($ch));
}
curl_close ($ch);
I've used this csv File-format (test.csv)
Action;ItemID;DispatchTimeMax
Revise;28*********916;30
The results after post:
print_r($resp);
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: dp1=bu1p/QEBfX0BAX19AQA**617d3da3^bl/DE617d3da3^; Domain=.ebay.com; Expires=Sat, 30-Oct-2021 12:42:11 GMT; Path=/
Set-Cookie: s=CgAD4ACBdvCgjMjFkNjZkMDcxNmUwYTBmMTc1MTA0ZmEwZmZmYjEyZWFY39RE; Domain=.ebay.com; Path=/
Set-Cookie: nonsession=CgADKACBhfT2jMjFkNjZkMDcxNmUwYTBmMTc1MTA0ZmEwZmZmYjEyZWIAywABXbrdqzHTwXKU; Domain=.ebay.com; Expires=Sat, 30-Oct-2021 12:42:11 GMT; Path=/
Cache-Control: private
Pragma: no-cache
Content-Type: text/html;charset=UTF-8
Content-Length: 731
Date: Thu, 31 Oct 2019 12:42:11 GMT
Connection: keep-alive
File upload successful. Your ref # is .
Close
Thanks for helping me.
I have found a solution:
Obviously at php 7.1 the # has no effect, and the file post ist empty to ebay.
I use the curl_file_create function and it's work.
if (!function_exists('curl_file_create'))
{
function curl_file_create($filename, $mimetype = '')
{
return "#$filename;filename="
. ($mimetype ? ";type=$mimetype" : '');
}
}
$fields = array(
"token" => $token,
"file" => curl_file_create ($_GET['filename'], 'text/csv')
);
Hope that help's anybody.
I get an error response for missing parameter when posting cURL POST method,
I'm adding an array of parameters to CURLOPT_POSTFIELDS the following way:
$service = "AutoInsuranceFormPostService";
$method = "autoInsurancePublisherFormPost";
$userAgent = "Mozilla%2F5.0+%28Linux%3B+Android+4.4.4%3B+Z752C+Build%2FKTU84P%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F36.0.1985.135+Mobile+Safari%2F537.36";
$payload = $encodedPayLoad;
$parameters = array (
'service' => $service,
'method' => $method,
'UserAgent' => $userAgent,
'payload' => $payload
);
With:
curl_setopt($ch,CURLOPT_POSTFIELDS,$parameters);
Since the response is saying missing parameter "service", I figured I need to debug the request body.
I managed to get the headers with:
curl_getinfo($ch)
I also attempted to use:
curl_setopt($ch, CURLOPT_VERBOSE, true);
But unfortunately in both cases I only got the headers and not the body (the parameters values).
Full curl execution function:
function openurl($url, $postvars) {
$ch=curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $verbose);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_TIMEOUT, '3');
$result = curl_exec($ch);
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
echo "Verbose information:\n<pre>", htmlspecialchars($verboseLog), "</pre>\n";
return $result;
}
Verbos information:
Content-Length: 6659
Expect: 100-continue
Content-Type: application/x-www-form-urlencoded; boundary=------------------------45b2d9f6776306b0
< HTTP/1.1 100 Continue
< HTTP/1.1 200 OK
< Date: Thu, 12 Jul 2018 16:32:52 GMT
< Server: Apache
< Cache-Control: public
< ORIGIN: S_CACHE
< Vary: User-Agent,Accept-Encoding
< Set-Cookie: _qs_origin=s-cache; path=/;
< Set-Cookie: _qs_deviceType=; path=/;
< Content-Length: 141
< Content-Type: application/json;charset=ISO-8859-1
<
This output is useless for me since I cannot see how the parameters were sent and those cannot fix their format.
The response I get is:
{"Status":"Fail","StatusCode":"400","ResponseMessage":"\"service\" parameter empty! || \"method\" parameter empty! ","SkipMatchingFlag":"No"}
I have been searching for a solution all day long, I've seen a ton of answers on "How to see the RESPONSE body", and "How to see the request HEADERS".
But none for "How to see the request body", so any help would be much appreciated,
Best regards.
I want to integrate Superfeedr API using PubSubHubbub in PHP. I am following this and my code is:
<?php
require_once('Superfeedr.class.php')
$superfeedr = new Superfeedr('http://push-pub.appspot.com/feed',
'http://mycallback.tld/push?feed=http%3A%2F%2Fpush-pub.appspot.com%2Ffeed',
'http://wallabee.superfeedr.com');
$superfeedr->verbose = true;
$superfeedr->subscribe();
?>
And my subscribe() function is
public function subscribe()
{
$this->request('subscribe');
}
private function request($mode)
{
$data = array();
$data['topic'] = $this->topic;
$data['callback'] = $this->callback;
$post_data = array (
"hub.mode" => 'subscribe',
"hub.verify" => "sync",
"hub.callback" => urlencode($this->callback),
"hub.topic" => urlencode($this->topic),
"hub.verify_token" => "26550615cbbed86df28847cec06d3769",
);
//echo "<pre>"; print_r($post_data); exit;
// url-ify the data for the POST
foreach ($post_data as $key=>$value) {
$post_data_string .= $key.'='. $value.'&';
}
rtrim($fields_string,'&');
// curl request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->hub);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_USERPWD, 'USERNAME:PASSWORD');
$output = curl_exec($ch);
if ($this->verbose) {
print('<pre>');
print_r($output);
print('</pre>');
}
}
But after execution I am getting this error
HTTP/1.1 422 Unprocessable Entity
X-Powered-By: The force, Luke
Vary: X-HTTP-Method-Override, Accept-Encoding
Content-Type: text/plain; charset=utf-8
X-Superfeedr-Host: supernoder16.superfeedr.com
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization
Content-Length: 97
ETag: W/"61-db6269b5"
Date: Wed, 24 Aug 2016 14:01:47 GMT
Connection: close
Please provide a valid hub.topic (feed) URL that is accepted on this hub. The hub does not match.
Same data (topic and callback etc..) requesting from https://superfeedr.com/users/testdata/push_console
is working fine. But I don't know why I am getting this error on my local. If anyone has any experienced with same problom then please help me. Thanks.
You are using a strange hub URL. You should use HTTPS://push.superfeedr.com in the last param of your class constructor.
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 7 years ago.
I am trying to get the indications_and_usage part in the results section from the following JSON URL: https://api.fda.gov/drug/label.json?search=levodopa
Till now, I have
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$data = curl_exec($ch);
curl_close($ch);
in my php file. When I echo $data, it gives the entire json as output. How can I modify this to get the indications_and_usage part?
As none of the methods seem to be working, here is the beginning output when I do
echo $data;
HTTP/1.1 200 Connection established HTTP/1.1 200 OK Access-Control-Allow-Headers: X-Requested-With Access-Control-Allow-Origin: * Age: 0 Cache-Control: public, max-age=60 Content-Security-Policy: default-src 'none' Content-Type: application/json; charset=utf-8 Date: Sun, 21 Feb 2016 19:49:27 GMT ETag: W/"19923-bQuoDHROKCsX/qDsyE4GuA" Server: openresty Vary: Accept-Encoding Vary: Accept-Encoding Vary: Accept-Encoding Via: http/1.1 api-umbrella (ApacheTrafficServer [cSsSfU]) X-Cache: MISS X-Content-Type-Options: nosniff X-Frame-Options: deny X-XSS-Protection: 1; mode=block Content-Length: 104739 Connection: keep-alive { "meta": { "disclaimer": "openFDA is a beta research project and not for clinical use. While we make every effort to ensure that data is accurate, you should assume all results are unvalidated.", "license": "http://open.fda.gov/license", "last_updated": "2016-02-05", "results": { "skip": 0, "limit": 1, "total": 1400 } }, "results": [ { "effective_time": "20120305", "drug_interactions": [ "DRUG INTERACTIONS Few systemic data have been collected on the metabolism of bupropion following concomitant administration with other drugs or, alternatively, the effect of concomitant administration of bupropion on the metabolism of other drugs. ..... and so on
You have to remove curl_setopt($ch, CURLOPT_HEADER, 1); form your curl. Otherwise the http header is included in the variable $data.
Full Example Code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
//curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$result = json_decode($data, true);
$result_string = $result['results'][0]['indications_and_usage'][0];
echo $result_string;
$json = file_get_contents("https://api.fda.gov/drug/label.json?search=levodopa");
$obj = json_decode($json);
echo "<pre>";
print_r($obj->results[0]->indications_and_usage);
echo "</pre>";
If you do print_r or var_dump on the whole object, you'll see that results is one of its members, an array. The first index of the results array is another object, which has an indications_and_usage member, the one you want.
You should be able to access it with:
$decoded = json_decode($data, true);
echo $decoded->results[0]->indications_and_usage[0]
I need to post some data to a script on my server. I'm using curl with and verbose error reporting. Does anyone have any idea why this is not working please?
Thanks,
Posting script
function makePost($postvars, $count) {
$url = 'http://servername.something.org/php/callback-f.php';
$ch = curl_init();
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
$result = curl_exec($ch);
curl_close($ch);
}
The script which is posted to contains this line:
<?php log_error("success",ERROR_LOG_TO_STDERR); ?>
My post vars a string which look like this:
surname=smth&address1=No+Value&this=that
The result i get back is this:
Connected to myserver.org port 80
> POST /php/callback-f.php HTTP/1.1
Host: myserver.org
Pragma: no-cache
Accept: */*
Content-Length: 1510
Content-Type: application/x-www-form-urlencoded
< HTTP/1.1 301 Moved Permanently
< Location: https://myserver/php/callback-f.php
< Content-Length: 0
< Date: Wed, 16 Nov 2011 16:21:23 GMT
< Server: lighttpd/1.4.28
* Connection #0 to host left intact
* Closing connection #0
Could you try using:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
You are getting back a 301 error. Your attempted url is http://servername.something.org and the 301 is saying the page is to be found at https://myserver (note https protocol).
301 errors also are not supposed to redirect on POST without user assent.