I'm trying to track my users' file changes with Dropbox's Webhooks interface. I expected the call to include POST data, but there doesn't seem to be POST data (or GET data, for that matter). Here is my PHP code, where the if part is for Dropbox to validate the webhook, and the else part saves the $_POST and $_GET variables to a file.
<?php
if( isset( $_GET['challenge'] ) ) {
echo $_GET['challenge'];
} else {
$output = print_r($_POST, true);
file_put_contents('file.txt', $output, FILE_APPEND );
$output = print_r($_GET, true);
file_put_contents('file.txt', $output, FILE_APPEND );
}
?>
After a short while, file.txt fills up with this:
Array
(
)
Array
(
)
Following this answer to a related question, you need to get the JSON data like this:
$output = file_get_contents('php://input');
Or, since it's JSON:
$output = json_decode( file_get_contents('php://input') );
Related
for 8 hours now I have been trying to parse this jSON response data
{"status":"200","message":"Welcome to spakkolos.com! You are welcome. Stay tuned"}
I have tried the followig, no luck:
$response = wp_remote_request( "https://loopwi.com/json");
$body = wp_remote_retrieve_body($response);
$json = json_decode($body);
echo $json->message; //I got NULL
echo $json['message']; // I got NULL
I tried several methods, I explored unserialized function of WordPress - all didn't work. But this works very excellently perfect outside WordPress. I don't know why WordPress made this so difficult a simple process!
I have done many research still no straight forward example. Please guys I need your help?
Thanks
Can you try the below code, I have used php file_get_contents instead of wordpress finction, I hope that will make sense to you
$body = trim(file_get_contents('https://loopwi.com/json'), "\xEF\xBB\xBF");
$json = json_decode($body);
echo $json->message;
echo $json['message'];
Refer link for explanation
Thanks guys for your replies. As #Ajith pointed out regarding trim(); by using
trim();
function on the response body, the problem solves.
There are ways to achieve this:
$response = wp_remote_request( "https://loopwi.com/json");
$body = trim(wp_remote_retrieve_body($response), "\xEF\xBB\xBF");
$body = trim($body, "\xEF\xBB\xBF");
$json = json_decode($body);
echo $json->message;
Or by this:
$url = "https://loopwi.com/json";
$response = wp_remote_get( $url );
if ( is_array( $response ) && ! is_wp_error( $response ) ) {
$headers = $response['headers']; // array of http header lines
$body = trim($response['body'], "\xEF\xBB\xBF"); // use the content
$json = json_decode($body);
echo $json->status;
echo $json->message;
}
These are functions in the WordPress WordPress's
HTTP API - wp_remote_get, wp_remote_request
Your project may get rejected if you use file_get_contents() in WordPress. Use the HTTP API functions instead.
Thanks for all those who answered and commented. Cheers!
I have no knowledge of php, but from an iOS app I am trying to pass variables to json which can be accessible later, each time user complete level the post method push 3 variables and its value which adds that info into file like this
php code:
<?php
header ('Location: ');
$handle = fopen("data.json", "a");
foreach($_POST as $variable => $value) {
fwrite($handle, $variable);
fwrite($handle, ":");
fwrite($handle, $value);
fwrite($handle, "\r\n");
}
fwrite($handle, "\r\n");
fclose($handle);
exit;
?>
and I get the output like this after two users used post method:
Name:user1
Points:100
Level:1
Name:user2
Points:200
Level:2
can someone please help me to get json format output, with every time user push data with the post method it adds info to existing data instead of overwriting it?
I want output like this:
[
{"Name":"user1","Score":"100","Level":"1"},{"Name":"user2","Score":"200","Level":"2"}
]
<?php
$json = json_decode(file_get_contents("data.json"), true);
$json[] = json_encode($_POST);
file_put_contents("data.json", $json);
This decodes the current JSON file, then appends the new information and then saves over the existing JSON file.
I've been trying to do this for a couple of days through trial and error etc, but getting absolutely nowhere. PHP isn't my strong point, but I'm generally comfortable with it that I can learn as I go when I need to do specific things.
What I'm trying to do, is take the API from one platform that is used, and input it into another platform that is used. I can get the data from the API easily enough via a URL, and it runs fine on a different server so I'm pretty sure everything is fine on that side of things.
The issue is, that when I do manage to get it from a URL, it comes out looking quite messy. Nothing I've tried so far will display it as a nice tidy block. Furthermore, I'd like to be able to pull specific data from the result and display just that. The data comes out as follows when visited via the URL (have changed values for privacy etc, but the integrity should remain):
{"Data":[{"DeviceID":"1","DeviceName":"Phone 1","Platform":"Phone OS","Edition":"Deluxe","State":"0","Time":"2016-03-16T13:47:44+01:00"}]}
Essentially, what I'm trying to do is:
Display the data in a block list, as opposed to long lines
Allow selection of a specific device through "Device Name", and then display the information relevant to that device
I've tried the following scripts so far:
1:
<?php
$json = file_get_contents('URLHERE');
$obj = json_decode($json);
echo $obj->DeviceID;
?>
2:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'URLHERE');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
echo $result->DeviceName;
?>
3:
<?php
$url = 'URLHERE';
$obj = json_decode(file_get_contents($url), true);
echo $obj['DeviceID'];
?>
4:
<?php
$url = "URLHERE";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "Device: ". $json_data["DeviceID"];
?>
5:
<?php
$json = file_get_contents('URLHERE');
$encodeJ = utf8_encode($json);
$obj = json_decode($encodeJ);
var_dump($obj-> DeviceID);
?>
The fourth one is the closest I've managed to get to it displaying data using these methods, but rather than any information I just get "Device: NULL"
Any help would be appreciated. Starting to pull my hair out here!
UPDATE:
Have managed to make some progress with the following:
<?php
$data = file_get_contents('URLHERE');
$response = json_decode($data, true);
echo 'Device: ' . $response['Data']['0']['DeviceName'];
echo 'Device: ' . $response['Data']['1']['DeviceName'];
?>
This is displaying the device names from the array for value 0 and 1. So now I need to figure out how to iterate through the array and display each one in sequence, as opposed to hard coding each one.
Your DeviceID is in Data & it's an array so you can't access directly. When you
$data = json_decode('{"Data":[{"DeviceID":"1","DeviceName":"Phone 1","Platform":"Phone OS","Edition":"Deluxe","State":"0","Time":"2016-03-16T13:47:44+01:00"}]}', true);//I am using array so second parameter is true to easily demonstrate
Your structure is
[
"Data" => [
[
"DeviceID" => "1",
"DeviceName" => "Phone 1",
"Platform" => "Phone OS",
"Edition" => "Deluxe",
"State" => "0",
"Time" => "2016-03-16T13:47:44+01:00",
],
],
]
So to get only first DeviceID if you want then
$deviceID = isset($data['Data'][0]['DeviceID']) ? $data['Data'][0]['DeviceID'] : null;
or if you want all the DeviceIDs then
$deviceIds = [];
if (isset($data['Data']) && is_array($data['Data']))
{
foreach ($data['Data'] as $row)
{
if (isset($row['DeviceID']))
{
$deviceIds[] = $row['DeviceID'];
}
}
}
or you can use array_column if your php version is >= 5.5.0 or php 7
$deviceIds = [];
if (isset($data['Data']) && is_array($data['Data']))
{
$deviceIds = array_column($data['Data'], 'DeviceID');
}
To get the data, use:
$json = file_get_contents( $url );
Then get it into an array, as:
$arr = json_decode( $json, TRUE );
To "Display the data in a block list, as opposed to long lines", use:
foreach ( $arr AS $element ) {
foreach ( $element AS $e ) {
echo $e['DeviceName'] . '<br>';
}
}
To "Allow selection of a specific device through "Device Name", and then display the information relevant to that device", use:
$deviceName = "Phone 1"; // depending upon your use case, you'll need to decide how you want to set this variable; it's hard coded here for the sake of example
foreach ( $arr AS $element ) {
foreach ( $element AS $e ) {
if ( $e['DeviceName'] = $deviceName ) {
echo '<pre>';
print_r( $e );
echo '</pre>';
}
}
}
While it's not entirely clear what you mean by "Allow selection of a specific device through "Device Name"", I'm inclined to believe you're looking for a way to let a user select a device from the list of device names. That's not a task you can accomplish with PHP alone. You'll need to build something for the front end in HTML or Javascript that interacts with your PHP on the back end.
I'm using curl in php to communicate between two servers. We have it working properly for POST and multi-dimensional arrays, but it didn't work for files. We got it working for files, but then it didn't work for multi-dimensional arrays. The two ways are using,
$post = $_POST;
//get files and include in data
foreach($_FILES as $name=>$info)
{
if( strlen($info['tmp_name']) )
{
$post[$name] = "#{$info['tmp_name']};filename={$info['name']};type={$info['type']}";
}
}
//$post = http_build_query( $_POST ); //works for multi-dimensional arrays (not files) and not doing this works for files and 1-d data
//use curl to pass information
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //string vs array
//test on recieving end
die(print_r($_POST, true) . print_r($_FILES,true));
Is there a way to handle both files and single/multi-dimensional post data?
You could try to put the file in base64, this way it becomes a string instead of binary data.
Ran a couple tests, and saw information on PHP website where someone commented on how it doesn't work for both (php,apache,curl). There solution showed a specific example with hardcoded results to meet their needs, but I expanded the concept to be more generic and handle both single d, multi-d, and file data.
//encode function found online for specific CURL use (on curl side)
function _encode($arrays, &$new = array(), $prefix = null)
{
if ( is_object( $arrays ) )
{
$arrays = get_object_vars( $arrays );
}
foreach ( $arrays as $key => $value ) {
$k = isset( $prefix ) ? $prefix . '[' . $key . ']' : $key;
if ( is_array( $value ) OR is_object( $value ) ) {
$this->_encode( $value, $new, $k );
} else {
$new[$k] = $value;
}
}
}
//use on curl side
$post = $_POST;
//get files and include in data
foreach($_FILES as $name=>$info)
{
if( strlen($info['tmp_name']) )
{
$post[$name] = "#{$info['tmp_name']};filename={$info['name']};type={$info['type']}";
}
}
//encode post generically to cover every use case (files, single d, multi-d, any form setup without hardcoding)
$encoded = array();
_encode( $post, $encoded );
//use curl to pass information
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //pass as an array
//test on recieving end
die(print_r($_POST, true) . print_r($_FILES,true)); //everything as expected
I want to fetch data from a facebook event using graph API. I wrote the following code :
<?php
$url = 'https://graph.facebook.com/events/1588093858105216';
$contents = file_get_contents( $url );
if( $contents )
{
$data = json_decode( $contents, true );
echo '<pre>';
print_r( $data );
echo '</pre>';
}
?>
My event page address URL is https://www.facebook.com/events/1588093858105216/.
The above code is not working properly. When I am using the same code for a page,e.g., https://www.facebook.com/TangeloTown , it works fine.
<?php
$url = 'https://graph.facebook.com/TangeloTown';
$contents = file_get_contents( $url );
if( $contents )
{
$data = json_decode( $contents, true );
echo '<pre>';
print_r( $data );
echo '</pre>';
}
?>
Also, I am unable to run it on localhost. Please help me to solve this or please tell me any other method to solve this.
Generally, you need an access token to access all graph api. Please check the doc here for event api: https://developers.facebook.com/docs/graph-api/reference/v2.3/event
In your case, if you want to access event, you need a user access token or app access token. To get user access token you check this doc: https://developers.facebook.com/docs/facebook-login/access-tokens in this way, you need to ask user for authorization. But if you only want to access public event, you can simply use your app access token, which can be found here: https://developers.facebook.com/tools/accesstoken/, but the prerequisite is that you need to register a FB app.