Convert terminal cURL command to PHP cURL request - php

I am trying to send a cURL request from PHP to Here Maps' RESTFUL Batch API.
The documentation states, that using this cURL script, I can send a data file with the data I need to them:
curl -X POST -H "Content-Type: text/plain" --data-binary #addresses.txt
"http://batch.geocoder.cit.api.here.com/6.2/jobs?
&app_code=AJKnXv84fjrb0KIHawS0Tg
&app_id=DemoAppId01082013GAL
&action=run
&header=true
&inDelim=;
&outDelim=,
&outCols=recId,latitude,longitude,locationLabel
&mailto=<my_email>
&outputcombined=true
&language=de-DE"
I am trying to convert this to PHP. I came up with the following code:
$cURLHandler = curl_init();
$url = "http://batch.geocoder.cit.api.here.com/6.2/jobs?&app_code=AJKnXv84fjrb0KIHawS0Tg&app_id=DemoAppId01082013GAL&action=run&mailto=trisztanthar#mailinator.com&outCols=recId,latitude,longitude,locationLabel&outputcombined=true&inDelim=;&outDelim=;";
if($cURLHandler) {
curl_setopt($cURLHandler, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
curl_setopt($cURLHandler, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($cURLHandler, CURLOPT_POST, 1);
curl_setopt($cURLHandler, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($cURLHandler, CURLOPT_POSTFIELDS, array('addresses' => new CurlFile("./batchjob.txt", 'text/plain', "batchjob.txt")));
curl_setopt($cURLHandler, CURLOPT_URL, $url);
curl_exec($cURLHandler);
curl_close($cURLHandler);
}
else {
throw new RuntimeException("Nem sikerült felvenni a kapcsolatot egy távoli szerverrel.");
}
When using it, I get the following error:
Only pipe (|), semicolon (;), colon (:), tab (' ') and comma (,)
delimiters allowed.
First I thought, that there was a problem with the file, however I tried to run the terminal command in a unix terminal with the same file I tried to use with PHP, and it went through without any problems, responded with a proper response, so its 100% that the PHP code I'm using isn't posting the file.
I'm currently developing on localhost, with MAMP Server (OSX). The batchFile.txt file is in the /Applications/Mamp/htdocs/php/ folder (localhost/php/batchfile.txt).
What am I doing wrong?

From your commandline you are directly posting the file as binary data. So send the content like below.
curl_setopt($cURLHandler, CURLOPT_POSTFIELDS, file_get_contents("batchjob.txt"));

Related

Firebase Cloud Messaging: Add a device to a topic using curl command

For now I can send a notification to a single device using the curl command:
curl --header "Authorization: key=AAAxxxxxE4:xxxxxxxuXog" --header Content-Type:"application/json; application/x-www-form-urlencoded;charset=UTF-8" -d '{"to":"DeviceToken","notification":{"title":"Test","body":"Test Message","icon":"icon-192x192.png"}}' https://fcm.googleapis.com/fcm/send
This works great. Now I try to scale the number of recipients by using the topic functionality.
I tried to add a device to the topic "svp" by using the curl command:
curl --header "Authorization: key=AAAxxxxxE4:xxxxxxxuXog" --header Content-Type:"application/json" https://iid.googleapis.com/iid/v1/DeviceToken/topics/svp
Here I get the error message:
{"error":"InvalidToken"}
But I'm sure, both, the Authorization key and the token are correct. (I still can send notifications with it).
Can anybody help me to find the solution for my problem?
I think you missed the rel in your cURL request, between the token and the topic name. As seen in the Instance ID docs, the format should be:
https://iid.googleapis.com/iid/v1/IID_TOKEN/rel/topics/TOPIC_NAME
For some reason, https://iid.googleapis.com/iid/v1/IID_TOKEN/rel/topics/TOPIC_NAME did not work for me. It seemed to me that I was doing everything correctly but what I decided to do was to try the equivalent of that by using https://iid.googleapis.com/iid/v1:batchAdd and sending only one token:
$curlUrl = "https://iid.googleapis.com/iid/v1:batchAdd";
$mypush = array("to"=>"/topics/toronto", "registration_tokens"=>array("acwAw4F8b0W:AMA91bEAKsN1aGjMm5xsobxBHxbYZLfioTPMEIN90njdiK5C2MnOYF4NcOy6ot6BFanMTBIoKRGcyev2RJuydGWt1XHwsniNZ6h8Pjvn9Fqth-Mqgj_5-YN9pt_nMAtgG8blc5bodWyA"));
$myjson = json_encode($mypush);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_POST, True);
curl_setopt($ch, CURLOPT_POSTFIELDS, $myjson);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'Authorization:key=[My authorization key]'));
//getting response from server
$response = curl_exec($ch);
I could add the token to the topic successfully. What was returned was this:
{"results":[{}]}
But then I went to confirm to the topics by using https://iid.googleapis.com/iid/info/IID_TOKEN that the token had been successfully added to the topic the way I wanted it and yes, everything worked correctly for me using https://iid.googleapis.com/iid/info/IID_TOKEN. So if you are having problems with https://iid.googleapis.com/iid/v1/IID_TOKEN/rel/topics/TOPIC_NAME, you can simply use https://iid.googleapis.com/iid/v1:batchAdd the way I did it.

PHP cURL POST Jenkins job with parameters

Triggering Jenkins job via following PHP script:
<?php
$testrun_id = "1744";
$cmd = "curl -X POST http://build:f9280f75396f83a0#mobile-jenkins.domain.com:8080/job/android-test/build --data-urlencode json='{\"parameter\": [{\"name\":\"POST_RESULTS\", \"value\":\"true\"}, {\"name\":\"RUN_ID\", \"value\":\"{$testrun_id}\"}, {\"name\":\"CHECK_NAME\", \"value\":\"SampleAutomatedPlan\"}]}'";
exec($cmd,$result);
?>
This script runs successfully on Mac and the jenkins job does get triggered. How do I make this script to work on Windows? I am getting following error when I run above PHP script on Windows?
curl is already installed on windows machine. Also, is there a better way to do cURL in PHP? Looking at this: http://php.net/manual/en/book.curl.php, can someone point me towards an example based on my curl command in the above PHP script(for Windows)? An example based on the curl command in my script would be ideal.
you should check examples from here http://php.net/manual/en/curl.examples.php
Bellow is the code for you case,
$url = "http://build:f9280f75396f83a0#mobile-jenkins.domain.com:8080/job/android-test/buildWithParameters";
$data = "POST_RESULTS=true&RUN_ID=".$testrun_id."&CHECK_NAME=SampleAutomatedPlan";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
You need to set the content type for JSON
curl -H "Content-Type: application/json" -X POST http://build:f9280f75396f83a0#mobile-jenkins.domain.com:8080/job/android-test/build --data-urlencode json='{\"parameter\": [{\"name\":\"POST_RESULTS\", \"value\":\"true\"}, {\"name\":\"RUN_ID\", \"value\":\"{$testrun_id}\"}, {\"name\":\"CHECK_NAME\", \"value\":\"SampleAutomatedPlan\"}]}'";
Just make sure you don't have any mix matched values.

php file with CURL commands not working on Server

I have php file which consist of curl code so as to access an api. But when I upload this file on server and try to execute it via url no output is shown. Also file symbol is not shown as it is shown for php file. Guide me how to solve this problem. The code in php file is :
<?php // set up the curl resource
$ch = curl_init(); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch,CURLOPT_POSTFIELDS,"{}"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, 'http://184.73.165.170:3000/api/3ace632b194e4366b821f7775b51cc4e/get-ibeacon-contents'); // execute the request
$output = curl_exec($ch);
// output the profile information - includes the header
//echo "curl response is :".($output). PHP_EOL; print($output);
// close curl resource to free up system resources
curl_close($ch); ?>
My server index shows as shown in image. As per my understanding a php file symbol is different than what it is shown in image I uploaded. Can anyone suggest about this ,if it helps me resolve my aim.
I tried on local and the cURL seems to work. If its working on local only and not on server then these are the things you should check:
Enable cURL on server ;extension=php_curl.dll and remove the semicolon; (uncomments) usually inside file php/php.ini
If you are working locally on Windows and trying to upload to a Linux server, then you might want to change EOL for UNIX/OSX Format. You can do this using Notepad++ by going to Edit -> EOL Conversion -> UNIX/OSX Format and then upload.
Try using your code this way
<?php
$json=json_encode(array('key1'=>'val1','key2'=>'val2'));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://184.73.165.170:3000/api/3ace632b194e4366b821f7775b51cc4e/get-ibeacon-contents');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$json);
$output = curl_exec($ch);
var_dump(curl_getinfo($ch));
echo curl_errno($ch) . '-' . curl_error($ch);
curl_close($ch);
?>

Load Json data from file into Parse.com backend via Rest API

Evening folks,
I am attempting to load data from a .json file into parse.com backend. I can get the rest api to load manually added json as per the example provided from Parse.com from the terminal on my Mac:
curl -X POST \
-H "X-Parse-Application-Id: removed" \
-H "X-Parse-REST-API-Key: removed" \
-H "Content-Type: application/json" \
-d '{"score":1337,"playerName":"Sean Plott","cheatMode":false}' \
https://api.parse.com/1/classes/Test
This works fine.
How can I read a saved .Json file with only these three parameters(Json is validated fine) and send the data to my Parse backend?
"score":1337,"playerName":"Sean Plott","cheatMode":false
I believe I have the option to use PHP/Jquery etc. however I have not used any of these languages extensively and a quick code example would be very much appreciated.
Thanks,
Gerard
Here is pure PHP solution:
$url = 'https://api.parse.com/1/classes/Test';
$fields_string = file_get_contents('file.json');
//open connection
$ch = curl_init();
//set the url, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
/* End of first request */

replicating command line cURL in PHP

I'm integrating with a 3rd party's API, I have to POST some XML and I get some XML back.
On the CLI this works, I get a positive response.
curl -X POST -d #/tmp/file http://url/to/endpoint --header "Content-Type:application/x-www-form-urlencoded"
This, however, does not work, the response contains an error telling me my that my request XML is invalid.
$ch = curl_init();
$post = array(
'file' => '#/tmp/file'
);
curl_setopt($ch, CURLOPT_URL, 'http://url/to/endpoint');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type:application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$this->responseBody = curl_exec($ch);
curl_close($ch);
It's the same file in both cases and it's on the same server. the file is just plain text XML. The only difference that I can see is that I'm specifying a fieldname in my HTTP headers on the PHP version.
How do I send that file over using PHP to exactly replicate the CLI version, e.g. without the formdata/fieldname bit?
FWIW I can't go back to the developer of the API for a few days to ask what he's defining as 'bad XML'
Try passing the file as raw data, not in an array, by for example using file_get_contents().
So instead of:
$post = array('file' => '#/tmp/file');
Like this:
$post = file_get_contents('#/tmp/file');

Categories