So I am creating a function in WordPress which counts and sets a user session and storing its values in the user's local storage. I was able to make it work perfectly by using cookies and when the site is hosted locally, for some reason, it is not working when I uploaded it on the staging site. So I am trying implement this function using another approach and decided to use local storage instead.
There's a problem with the Array values that the function is generating and I have spent almost the entire day trying to debug the problem. It is generating multi-dimensional instead of a single one.
Here's my function code:
function monitor_post_views() {
$page_id = 'page' . $_POST['page_id'];
$timestamp = time();
// 30 minutes timeout
$timeout = 1800;
// Serves as my guide for debugging, will not include in the final code
$message = '';
if ( ! empty($_POST['page_id_array']) ) {
//Checks if values from local storage exist
//Gets the stored Array coming from AJAX call
$page_id_array[] = json_decode(stripslashes($_POST['page_id_array']), true);
if ( in_array_r($page_id_array, $page_id) ) {
//Check if current page is found in array
$message = 'FOUND IN ARRAY CHECKING !!!!';
$temp= [];
$page_id_array_temp = array('id' => $page_id, 'expiration' => $timestamp, 'message' => $message);
$temp = $page_id_array_temp;
//Pushes the generated array inside the $page_id_array
array_push($page_id_array, $temp);
print_r(json_encode($page_id_array));
foreach ( $page_id_array as $page ) {
//If page is in array, check if the session is expired, if not, do nothing, if expired, update and then run the view function
}
} else {
// ID Not found in Array, Insert a new entry
$message = 'ID NOT FOUND IN ARRAY, CREATING ENTRY !!!';
$temp = [];
$page_id_array_temp = array('id' => $page_id, 'expiration' => $timestamp, 'message' => $message);
$temp = $page_id_array_temp;
//Pushes the generated array inside the $page_id_array
array_push($page_id_array, $temp);
print_r(json_encode($page_id_array));
//Set post view function here base on $_POST['page_id']
}
} else {
//Not found in local storage, need to create one
$message = 'CREATING A NEW ENTRY !!!!';
$temp = [];
$page_id_array = array('id' => $page_id, 'expiration' => $timestamp, 'message' => $message);
$temp = $page_id_array;
print_r(json_encode($temp));
//Set post view function here base on $_POST['page_id']
}
wp_die();
}
add_action('wp_ajax_monitor_post_views', 'monitor_post_views');
add_action('wp_ajax_nopriv_monitor_post_views', 'monitor_post_views');
Here's a screenshot of what this function generates
Array
Here's a sample JSON
[[{"id":"page1202","expiration":1551125579,"message":"FOUND IN ARRAY CHECKING !!!!"},{"id":"page1206","expiration":1551125613,"message":"ID NOT FOUND IN ARRAY !!!! INSERTING ENTRY !!!"}],{"id":"page1296","expiration":1551125624,"message":"ID NOT FOUND IN ARRAY !!!! INSERTING ENTRY !!!"}]
I was trying to generate a one dimensional but ended up with this.
Any thoughts? Thanks in advance
The problem is you are creating arrays too many times:
Change $page_id_array and $page_id_array_temp to
$page_id_array=new \stdClass();//no need to declare as an array
replace
$page_id_array_temp = array('id' => $page_id, 'expiration' => $timestamp, 'message' => $message);
with
$page_id_array->id=$page_id;
$page_id_array->expiration=$timestamp;
$page_id_array->message=$message;
also change
$temp = [];
you can use it directly
//no need to declare $temp as an array
$temp=$page_id_array;
Related
This is a function where i call 2 api, from first i get client_id which i used in second url. Problem is that after i call second url my page is loading without end.
Page image
public function getDevices(){
$route='http://localhost:8000/api/devices';
$device= new Client();
$answer= $device->request('GET', $route);
$body = $answer->getBody();
$status = 'true';
$message = 'Data found!';
$final= json_decode($body);
$id_array = array();
foreach ($finalas $item) {
// Add each id value in your array
$id_array[]= $item->clientId;
}
foreach($id_array as $my_id) {
$answer2= $client->request('GET', 'http://localhost:8080/api/devices/deviceAvailability/' . $my_id );
$body2 = $response2->getBody();
$final2= json_decode($body2);
}
return view('new.home', ['clients' => $final, 'status'=> $final2]);
I think
return view('new.home', ['clients' => $final, 'status'=> $final2])
is wrong. Because $final is decoded variable, maybe $final contains several types of variables.
In php, you can not set parameter that contains several types of variables.
Please do like that.
return view('new.home', ['clients' => $body, 'status'=> $final2]);
That's because json encoded variable is only a string.
I want your result.
I am having some trouble implementing the pushwoosh class http://astutech.github.io/PushWooshPHPLibrary/index.html. I have everything set up but i am getting an error with the array from the class.
This is the code i provied to the class:
<?php
require '../core/init.php';
//get values from the clientside
$sendID = $_POST['sendID'];
$memID = $_POST['memID'];
//get sender name
$qry = $users->userdata($memID);
$sendName = $qry['name'];
//get receiving token
$qry2 = $users->getTokenForPush($sendID);
$deviceToken = $qry2['token'];
//i have testet that $deviceToken actually returns the $deviceToken so thats not the problem
//this is the array that the php class requires.
$pushArray = array(
'content' => 'New message from ' . $sendName,
'devices' => $deviceToken,
);
$push->createMessage($pushArray, 'now', null);
?>
And this is the actually code for the createMessage() method
public function createMessage(array $pushes, $sendDate = 'now', $link = null,
$ios_badges = 1)
{
// Get the config settings
$config = $this->config;
// Store the message data
$data = array(
'application' => $config['application'],
'username' => $config['username'],
'password' => $config['password']
);
// Loop through each push and add them to the notifications array
foreach ($pushes as $push) {
$pushData = array(
'send_date' => $sendDate,
'content' => $push['content'],
'ios_badges' => $ios_badges
);
// If a list of devices is specified, add that to the push data
if (array_key_exists('devices', $push)) {
$pushData['devices'] = $push['devices'];
}
// If a link is specified, add that to the push data
if ($link) {
$pushData['link'] = $link;
}
$data['notifications'][] = $pushData;
}
// Send the message
$response = $this->pwCall('createMessage', $data);
// Return a value
return $response;
}
}
Is there a bright mind out there that can tell me whats wrong?
If I understand, your are trying to if your are currently reading the devices sub-array. You should try this:
foreach ($pushes as $key => $push) {
...
// If a list of devices is specified, add that to the push data
if ($key == 'devices') {
$pushData['devices'] = $push['devices'];
}
You iterate over $pushes, which is array('content' => ..., 'devices' => ...). You will first have $key = content, the $key = 'devices'.
It looks like the createMessage function expects an array of messages, but you are passing in one message directly. Try this instead:
$push->createMessage(array($pushArray), 'now', null);
The class is expecting an array of arrays; you are just providing an array.
You could do something like this
//this is the array that the php class requires.
$pushArrayData = array(
'content' => 'New message from ' . $sendName,
'devices' => $deviceToken,
);
$pushArray[] = $pushArrayData
Will you ever want to handle multiple messages? It makes a difference in how I would do it.
Hi I'm making a web service in cakephp for an android app. I am getting the request and the respose is being send but the response is not visible on the client's end. My code is as shown below. Can there be some other method to send the response.
public function AndroidApp() {
if (isset($_POST["myHttpData"])) {
$coupon = trim($_POST["myHttpData"]);
$couponId = $this->Code->find('all', array(
'conditions' => array(
'Code.coupon_code' => $coupon,
'Code.status' => 'Used'
),
'fields' => array('Code.id')));
$studentAssessmentId = $this->StudentAssessment->find('all', array(
'conditions' => array(
'StudentAssessment.code_id' => $couponId[0]['Code']['id'],
'StudentAssessment.status' => 'Complete'
),
'fields' => array('StudentAssessment.id')));
$scores = $this->AssessmentScore->find('all', array(
'conditions' => array(
'AssessmentScore.student_assessment_id' => $studentAssessmentId[0]['StudentAssessment']['id']
),
'fields' => array('AssessmentScore.score')));
$json = array();
$assessment_data = array();
//debug($scores);
$i = 0;
foreach ($scores as $score) {
$assessment_data[$i] = array("score" => $score['AssessmentScore']['score']);
$i+=1;
}
header('Content-type: application/json');
$json['success'] = $assessment_data;
$android = json_encode($json);
} else {
$json['error'] = "Sorry, no score is available for this coupon code!";
$android = json_encode($json);
}
echo $android;
code smell, non-cakephp standards
First of all, as mentioned in comments by others, you're not using the CakePHP request/response objects. Because of this, you're overly complicating things. See the documentation here;
http://book.cakephp.org/2.0/en/controllers/request-response.html
http://book.cakephp.org/2.0/en/controllers/request-response.html#dealing-with-content-types
And
http://book.cakephp.org/2.0/en/views/json-and-xml-views.html
The $scores loop to reformat the query results is probably redundant if you replace the find('all') with find('list'), using 'score' as display field. See the documentation here http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-list
bugs
There also seems to be some bugs in your code;
the content-type header is only sent if $_POST["myHttpData"] is present.
you're only checking if $_POST["myHttpData"] is present, not if it actually contains any data (empty)
you're not checking if the various queries return a result. This will cause errors in your code if a query did not return anything! For example, you assume that $couponId[0]['Code']['id'] is present (but it won't be if the coupon-code was not found)
possible answer
Apart from these issues, the most probable cause for your problem is that you did not disable 'autoRender'. Therefore CakePHP will also render the view after you've output your JSON, causing a malformed JSON response.
public function AndroidApp() {
$this->autoRender = false;
// rest of your code here
}
I'm trying to write to a json file, and want to be able to overwrite an object if certain fields match. Right now, I have code that gets whats currently in the JSON file, but that just adds the latest object to the end of it. What I need to do is that if the message fields match, then I need to replace the entry with the newer one. Know what I mean?
Thanks for the help!
PHP:
$file = file_get_contents('test.json');
$data = json_decode($file);
unset($file);//prevent memory leaks for large json.
//insert data here
$data[] = array("message" => $name, "latitude" => $lat, "longitude" => $lon, "it" => $it);
//save the file
file_put_contents('test.json',json_encode($data));
echo json_encode($data);
unset($data);//release memory
You can use array_filter to find the element with the matching name and update it in place. This will not remove any existing duplicates for you, though.
$datum = array_filter($data, function (&$elem) use ($name, $lat, $lon, $it) {
if ($elem['message'] === $name) {
$elem = array('message' => $name /* snip */)
return true;
}
});
if (!$datum) { /* append array */ }
assuming I understand correctly, you only need to check if two elements in your $data array are equal, based on the message. Easiest way to do that is use the key of the data array, and reset it afterwards. so something similar to :
$file = file_get_contents('test.json');
$data = json_decode($file);
unset($file);//prevent memory leaks for large json.
//insert data here
$data[$message] = array("message" => $name, "latitude" => $lat, "longitude" => $lon, "it" => $it);
//save the file
$data = array_values($data);
file_put_contents('test.json',json_encode($data));
echo json_encode($data);
unset($data);//release memory
this will increase memory consumption, so you can use md5() for the keys instead to keep it low.
If you use json_decode($string, true), you will get either an associative or numeric array. This array can be manipulated with standard php array methods.
$array = json_decode($string, true);
if(md5($data['message']) != md5($newMessage)) {
$array['message'] = $newMessage;
}
I used an md5, because i don't know how the message is structured.
i run a python script whitch cache some data
self.cache.set('test', 'my sample data', 300)
data = self.cache.get('test')
self.p(data)
this program will result in print of 'my sample data' ... everything its good, but when i try to access this key from php
$data = $this->cache->get('test');
print_r($test);
i only get empty result
so i check the server stats
$list = array();
$allSlabs = $this->cache->getExtendedStats('slabs');
$items = $this->cache->getExtendedStats('items');
foreach($allSlabs as $server => $slabs) {
foreach($slabs AS $slabId => $slabMeta) {
$cdump = $this->cache->getExtendedStats('cachedump',(int)$slabId);
foreach($cdump AS $server => $entries) {
if($entries) {
foreach($entries AS $eName => $eData) {
$list[$eName] = array(
'key' => $eName,
'server' => $server,
'slabId' => $slabId,
'detail' => $eData,
'age' => $items[$server]['items'][$slabId]['age'],
);
}
}
}
}
}
ksort($list);
print_r($list);
and this key 'test' is there ... but i cannot access it
if i cache something in php i get the result everytime, but somehow this python + php cache wont work
if someone has an idea where could be a problem plese advice ... i try everything
Could it be that the hashes don't match between PHP and Python? A solution is here: http://www.ruturaj.net/python-php-memcache-hash
Add the following to your Python script to change how hashes are calculated...
import memcache
import binascii
m = memcache.Client(['192.168.28.7:11211', '192.168.28.8:11211
', '192.168.28.9:11211'])
def php_hash(key):
return (binascii.crc32(key) >> 16) & 0x7fff
for i in range(30):
key = 'key' + str(i)
a = m.get((php_hash(key), key))
print i, a