PHP - run GET curl, get result - php

I wanna run a GET curl in php A to get data from php B.
This is an example in php A (I got from here http://support.qualityunit.com/061754-How-to-make-REST-calls-in-PHP)
//next example will recieve all messages for specific conversation
$service_url = 'http://localhost/test/getFrom.php?id=1';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
curl_close($curl);
$decoded = json_decode($curl_response);
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
die('error occured: ' . $decoded->response->errormessage);
}
echo 'response ok!';
var_export($decoded->response);
And I tried this example as well (Trying to use curl to do a GET, value being sent is allows null)
In php B.
It will get the ID, run some script and will generate an ARRAY.
I want to get this ARRAY from B to A.
B will run only when A request GET from B.
The problem is I don't how the ARRAY can pass from B to A.
Please give some advice THANK YOU.

The code you provided is expecting back a JSON encoded array. The easiest way to do this is simply JSON encode your array in PHP B and echo it to the page.
Then CURL will be able to read the contents of PHP B, decode and process as required.
// PHP B
<?php
// Check for $_GET params
// Get ID
$id = $_GET['id'];
// Do processing, query etc
....
// Format and display array as JSON
echo(json_encode($result_array));
die();
?>
Also note:
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
die('error occured: ' . $decoded->response->errormessage);
}
The code is expecting the array to be formatted in a particular way. So either match your array in PHP B to the same format, or update the code to your needs.

Related

GoLang WebServer sends description of param's struct on Json Response

So here is the deal : I have been working on a huge system (PHP) for a couple years, and now, I decided to give up part of heavy jobs for golang scripts.
So far, I replicated a few php scripts to a go version. Then, I am able to benchmark which option is better ( ok, I know go is faster, but I need curl or sockets to comunication, so, I have to check if it is still worth ) .
One of the scripts just generate a random code, check if this new code is already in use ( on mysql db ), if not, record the new code and return it, if is already in use, just recursive call the function again until find an exclusive code. pretty simple one.
I already had this code generator in php, so, wrote new one in go to be called as http/post with json params.
Using linux terminal, I call it as
curl -H [headers] -d [jsondata] [host]
and I get back a pretty simple json
{"locator" : "XXXXXX"}
After, I wrote a simple php script to call the scripts and check how long each took to complete, something like :
<?php
public function indexAction()
{
$phpTime = $endPHP = $startPHP =
$goTime = $endGO = $startGO = 0;
// my standard function already in use
ob_start();
$startPHP = microtime(true);
$MyCodeLocator = $this->container->get('MyCodeLocator')->Generate(22, 5);
$endPHP = microtime(true);
ob_end_clean();
sleep(1);
// Lets call using curl
$data = array("comon" => "22", "lenght" => "5");
$data_string = json_encode($data);
ob_start();
$startGO = microtime(true);
$ch = curl_init('http://localhost:8888/dev/fibootkt/MyCodeGenerator');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
curl_close($ch);
$endGO = microtime(true);
ob_end_clean();
$result_rr = json_decode($result);
// tst just echo the variable in a nice way, second parameter means no kill execution
tst($result, 1); // HERE IS MY PROBLEM, please read below
tst($result_rr, 1); // IT SHOW NULL
sleep(1);
// just to have params for comparision, always try by shell script
ob_start();
$startShell = microtime(true);;
$exec = "curl -H \"Content-Type: application/json\" -d '{\"comon\":\"22\"}' http://localhost:8888/dev/fibootkt/MyCodeGenerator";
$output = shell_exec($exec);
$endShell = microtime(true);
ob_end_clean();
tst(json_decode($output),1); // here show a stdclass with correct value
tst($output,1); // here shows a json typed string ready to be converted
// and here it is just for show the execution time ...
$phpTime = $endPHP - $startPHP;
$goTime = $endGO - $startGO ;
$shellTime = $endShell - $startShell;
tst("php " . $phpTime, 1);
tst("curl ". $goTime, 1);
tst("shell " . $shellTime, 1);
And I get the results from GO :
By Shell Script :
{"locator" : "DPEWX22"}
So, this one is pretty and easy decode to a stdobj.
But, using curl, the operation is faster ! So, I want to use it.
But, the curl request responds something like :
{"Value":"string","Type":{},"Offset":26,"Struct":"CodeLocatorParams","Field":"lenght"}
{"locator":"DPEWX22"}
And when I try to decode it, I get a null as result !!!
CodeLocatorParams the struct type I use in go to get the post params, as show below
so, here is my question : Why GO is returning this ? how to avoid it.
I have another similar go script which take no params and responds a similar json ( but in this case, a qrcode image path ) and it works fine !
My go function:
type CodeLocatorParams struct {
Comon string `json:"comon"`
Lenght int `json:"lenght"`
}
func Generate(w http.ResponseWriter, r *http.Request) {
data, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil {
fmt.Println(err)
panic(err)
}
if err := r.Body.Close(); err != nil {
panic(err)
}
// retrieve post data and set it to params which is CodeLocatorParams type
var params CodeLocatorParams
if err := json.Unmarshal(data, &params ); err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
if err := json.NewEncoder(w).Encode(err); err != nil {
fmt.Println(err)
panic(err)
}
}
var result struct{
Locator string `json:"locator"`
}
// here actually comes the func that generates random code and return it as string, but for now, just set it static
result.Locator = "DPEWX22"
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
json.NewEncoder(w).Encode(result)
}
There is an error parsing the incoming JSON. This error is written to the response as {"Value":"string","Type":{},"Offset":26,"Struct":"CodeLocatorParams","Field":"lenght"}. The handler continues to execute and writes the normal response {"locator":"DPEWX22"}.
Here's how what to fix:
After writing error response, return from the handler.
The input JSON has lenght as a string value. Either change the struct field from int to string or modify the input to pass an integer.

Record the result of a curl GET request using php & mysql

I'm trying to understand how to record the result of a curl GET request using php. I'm looking at outputing part or all of the result to mysql.
https://github.com/cloudtrax/docs/blob/master/api/code/php/simple_api_server_test_harness.php
function invoke_curl($method, $endpoint, $headers, $json) {
$api_server = 'https://api.cloudtrax.com';
try {
// get a curl handle then go to town on it
$ch = curl_init($api_server . $endpoint);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if ($result == FALSE) {
if (curl_errno($ch) == 0)
echo "#### NOTE ####: nil HTTP return: This API call appears to be broken" . "\n";
else
throw new Exception(curl_error($ch), curl_errno($ch));
}
else
echo "RESULT: \n" . $result . "\n";
}
The $result shows like this:
{
"clients": {
"ssid2": 4,
"ssid1": 10
},
"rows": [
{
"time": "2016-03-23T02:45:00Z",
"ssid2": {
"traffic": {
"unclassified": {
// etc...
How can I associate each part of the result too a variable so I can then input too mysql?
It looks like this result in json format. You can use json_decode to decode it:
$resultObject = json_decode($result);
$clients = $resultObject->clients;
// ... get other data from result
The code below will convert the json into a PHP array. You can then use the indexes of the array to pull out values.
$result = json_decode($result);
$clients = $result->clients;
// Some MySQL queries
If your response is a JSON response then you can simply use php's json_decode to get parsed object.
$result = curl_exec($ch);
//to get associative array passing true
$jsonObj = json_decode($result, true);
$clients = $jsonObj['clients'];
$rows = $jsonObj['rows'];
You can refer to these answers for more detail:
Parsing JSON object in PHP using json_decode and
Parsing JSON file with PHP

Getting JSON Object by calling a URL with parameters in PHP

I'm trying to get json data by calling moodle url:
https://<moodledomain>/login/token.php?username=test1&password=Test1&service=moodle_mobile_app
the response format of moodle system is like this:
{"token":"a2063623aa3244a19101e28644ad3004"}
The result I tried to process with PHP:
if ( isset($_POST['username']) && isset($_POST['password']) ){
// test1 Test1
// request for a 'token' via moodle url
$json_url = "https://<moodledomain>/login/token.php?username=".$_POST['username']."&password=".$_POST['password']."&service=moodle_mobile_app";
$obj = json_decode($json_url);
print $obj->{'token'}; // should print the value of 'token'
} else {
echo "Username or Password was wrong, please try again!";
}
Result is: undefined
Now the question:
How can I process the json response format of moodle system? Any idea would be great.
[UPDATE]:
I have used another approach via curl and changed in php.ini following lines: *extension=php_openssl.dll*, *allow_url_include = On*, but now there is an error: Notice: Trying to get property of non-object. Here is the updated code:
function curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$moodle = "https://<moodledomain>/moodle/login/token.php?username=".$_POST['username']."&password=".$_POST['password']."&service=moodle_mobile_app";
$result = curl($moodle);
echo $result->{"token"}; // print the value of 'token'
Can anyone advise me?
json_decode() expects a string, not a URL. You're trying to decode that url (and json_decode() will NOT do an http request to fetch the url's contents for you).
You have to fetch the json data yourself:
$json = file_get_contents('http://...'); // this WILL do an http request for you
$data = json_decode($json);
echo $data->{'token'};

PHP - How to check if Curl actually post/send request?

I basically created a script using Curl and PHP that sends data to the website e.g. host, port and time. Then it submits the data. How would I know if the Curl/PHP actually sent those data to the web pages?
$fullcurl = "?host=".$host."&time=".$time.";
Any ways to see if they actually sent the data to those URLs on My MYSQL?
You can use curl_getinfo() to get the status code of the response like so:
// set up curl to point to your requested URL
$ch = curl_init($fullcurl);
// tell curl to return the result content instead of outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// execute the request, I'm assuming you don't care about the result content
curl_exec($ch);
if (curl_errno($ch)) {
// this would be your first hint that something went wrong
die('Couldn\'t send request: ' . curl_error($ch));
} else {
// check the HTTP status code of the request
$resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($resultStatus == 200) {
// everything went better than expected
} else {
// the request did not complete as expected. common errors are 4xx
// (not found, bad request, etc.) and 5xx (usually concerning
// errors/exceptions in the remote script execution)
die('Request failed: HTTP status code: ' . $resultStatus);
}
}
curl_close($ch);
For reference: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
Or, if you are making requests to some sort of API that returns information on the result of the request, you would need to actually get that result and parse it. This is very specific to the API, but here's an example:
// set up curl to point to your requested URL
$ch = curl_init($fullcurl);
// tell curl to return the result content instead of outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// execute the request, but this time we care about the result
$result = curl_exec($ch);
if (curl_errno($ch)) {
// this would be your first hint that something went wrong
die('Couldn\'t send request: ' . curl_error($ch));
} else {
// check the HTTP status code of the request
$resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($resultStatus != 200) {
die('Request failed: HTTP status code: ' . $resultStatus);
}
}
curl_close($ch);
// let's pretend this is the behaviour of the target server
if ($result == 'ok') {
// everything went better than expected
} else {
die('Request failed: Error: ' . $result);
}
in order to be sure that curl sends something, you will need a packet sniffer.
You can try wireshark for example.
I hope this will help you,
Jerome Wagner

Accessing JS data from PHP

A remote site is supplying a data structure in a js file.
I can include this file in my page to access the data and display it in my page.
<head>
<script type="text/javascript" src="http://www.example.co.uk/includes/js/data.js"></script>
</head>
Does anyone know how I use PHP to take this data and store in it a database?
You should GET that file directly, via, for example, CURL. Then parse it, if it comes in JSON, you can use json-decode.
Simple example (slightly modified version of code found here):
<?php
$url = "http://www.example.co.uk/includes/js/data.js";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
...
$output = curl_exec($ch);
$info = curl_getinfo($ch);
if ($output === false || $info['http_code'] != 200) {
$error = "No cURL data returned for $url [". $info['http_code']. "]";
if (curl_error($ch))
$error .= "\n". curl_error($ch);
}
else {
$js_data = json_decode($output);
// 'OK' status; save $class members in the database, or the $output directly,
// depending on what you want to actually do.
...
}
//Display $error or do something about it
?>
You can grab the file via CURL or some other HTTP downloading library/function. Then, parse the data. If you're lucky, the data is in a JSON format and you can use a PHP function to convert it into a PHP array. Then, iterate through the items in the array, inserting each into your database.

Categories