PHP: How to get current memcached object persistence id - php

Is there any way to get current memcached instance persistence id in
PHP?
// Some place in code
$persistence = 'my servername_' . md5(unique());
$memcachedObject = new Memcached($persistence);
And then somewhere else something like:
$memcachedObject->getPersistenceId();

Related

How to Return List of Project Tasks in ActiveCollab

Sorry this may be a trivial question but I am new to PHP. In the documentation to retrieve project tasks, the following code is provided to connect to an Active Collab cloud account:
<?php
require_once '/path/to/vendor/autoload.php';
// Provide name of your company, name of the app that you are developing, your email address and password.
$authenticator = new \ActiveCollab\SDK\Authenticator\Cloud('ACME Inc', 'My Awesome Application', 'you#acmeinc.com', 'hard to guess, easy to remember');
// Show all Active Collab 5 and up account that this user has access to.
print_r($authenticator->getAccounts());
// Show user details (first name, last name and avatar URL).
print_r($authenticator->getUser());
// Issue a token for account #123456789.
$token = $authenticator->issueToken(123456789);
// Did we get it?
if ($token instanceof \ActiveCollab\SDK\TokenInterface) {
print $token->getUrl() . "\n";
print $token->getToken() . "\n";
} else {
print "Invalid response\n";
die();
}
This works fine. I can then create a client to make API calls:
$client = new \ActiveCollab\SDK\Client($token);
and get the list of tasks for a given project as shown in the documentation.
$client->get('projects/65/tasks'); // PHP object
My question is, what methods/attributes are available to get the list of tasks? I can print the object using print_r() (print will obviously not work), and what I really want is in the raw_response header. This is private however and I cannot access it. How do I actually get the list of tasks (ex: the raw_response either has a string or json object)?
Thanks in advance.
There are several methods to work with body:
$response = $client->get('projects/65/tasks');
// Will output raw JSON, as string.
$response->getBody();
// Will output parsed JSON, as associative array.
print_r($response->getJson());
For full list of available response methods, please check ResponseInterface.
If you wish to loop through tasks, use something like this:
$response = $client->get('projects/65/tasks');
$parsed_json = $response->getJson();
if (!empty($parsed_json['tasks'])) {
foreach ($parsed_json['tasks'] as $task) {
print $task['name'] . "\n"
}
}

how can I migrate to AS3 with code like this "l = new LoadVars ();"

i am a beginner. I'm starting to learn Adobe Flash. I followed the code on Google on AS2:
l = new LoadVars();
l.onLoad = function(ok) {
ttl0=l.ttlslv0; atc0=l.atcslv0;
ttl1=l.ttlslv1; atc1=l.atcslv1;
};
l.sendAndLoad("http:localhost/getdata.php", l, "POST");
with php like this:
<?php
include_once("koneksi.php");
$qr = mysqli_query($con,"SELECT title, article from $tabel");
$nr = 0;
while($kolom=mysqli_fetch_row($qr) )
{
$ttl=$kolom[0];
$atc=$kolom[1];
echo "&ttlslv$nr=$ttl&atcslv$nr=$atc";
$nr++;
}
echo "&nr=$nr&";
?>
with the results that I can specify "what row" and "what column" will I take.
can this be changed to AS3 with the same results?
I have difficulty studying AS3
anyone want to give me a solution? thanx...
In AS3 you use the URLLoader class to load text/binary data. To work with URL-encoded strings you need the URLVariables class.
Something like that (not tested, no error handling either, just a common guideline):
// URLRequest instance holds various information
// about what, where and how you send.
var aRequest:URLRequest = new URLRequest;
// URL address.
aRequest.url = "http://localhost/getdata.php";
// Request method (POST or GET mostly).
aRequest.method = URLRequestMethod.POST;
// URLLoader instance performs the requested operations:
// uploads the request and relevant data, reads the answer,
// and dispatches all the events about any status changes.
var aLoader:URLLoader = new URLLoader;
// Tell the URLLoader that the answer is
// an URL-encoded text of key=value pairs.
aLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
// This event handler function will be triggered
// upon successfully completed operation.
aLoader.addEventListener(Event.COMPLETE, onData);
// Start loading.
aLoader.load(aRequest);
// The COMPLETE event handler function.
function onData(e:Event):void
{
// Unsubscribe from the event. For the most part it is
// a GOOD idea NOT to re-use any network-related
// class instances once they've done their job.
// Just unsubscribe from all their events,
// dismantle their data structures, purge
// any references to them and let the
// Garbage Collector do his job.
aLoader.removeEventListener(Event.COMPLETE, onData);
// Retrieve the object that contains key=value pairs.
var anAnswer:URLVariables = aLoader.data as URLVariables;
// The data you wanted to get.
trace(anAnswer.ttlslv0);
trace(anAnswer.atcslv0);
trace(anAnswer.ttlslv1);
trace(anAnswer.atcslv1);
}
UPD: It seems that you are dealing with escaped text there. I composed a simple script that explains how it works:
import flash.net.URLVariables;
var V:URLVariables = new URLVariables;
var S:String = "a=1&b=2";
V.decode(S);
trace(V.a); // 1
trace(V.b); // 2
S = escape(S);
trace(S); // a%3D1%26b%3D2
trace(unescape(S)); // a=1&b=2
V.decode(S); // Error #2101
So, there are two options you can work on:
Figure out why server passes the escaped string and prevent it.
Load the server's answer as a plain text (URLLoaderDataFormat.TEXT instead of VARIABLES) so the URLLoader.data will be just a simple String, then unescape(...) it if necessary and feed to the URLVariables.decode(...).

How to create solr document with String type using solarium query

I' creating solr document via solarium plugin in php.
But the all document is stored text_general data type except id field. text_general is the default datatype in solr system.
My doubt is why id field is only to stored string type as default.
And If any possible to add document with string type using solarium plugin.
My code part is here,
public function updateQuery() {
$update = $this->client2->createUpdate();
// create a new document for the data
$doc1 = $update->createDocument();
// $doc1->id = 123;
$doc1->name = 'value123';
$doc1->price = 364;
// and a second one
$doc2 = $update->createDocument();
// $doc2->id = 124;
$doc2->name = 'value124';
$doc2->price = 340;
// add the documents and a commit command to the update query
$update->addDocuments(array($doc1, $doc2));
$update->addCommit();
// this executes the query and returns the result
$result = $this->client2->update($update);
echo '<b>Update query executed</b><br/>';
echo 'Query status: ' . $result->getStatus(). '<br/>';
echo 'Query time: ' . $result->getQueryTime();
}
The result document for the above code is here,
{
"responseHeader":{
"status":0,
"QTime":2,
"params":{
"q":"*:*",
"_":"1562736411330"}},
"response":{"numFound":2,"start":0,"docs":[
{
"name":["value123"],
"price":[364],
"id":"873dfec0-4f9b-4d16-9579-a4d5be8fee85",
"_version_":1638647891775979520},
{
"name":["value124"],
"price":[340],
"id":"7228e92d-5ee6-4a09-bf12-78e24bdfa52a",
"_version_":1638647892102086656}]
}}
This depends on the field type defined in the schema for your Solr installation. It does not have anything to do with how you're sending data through Solarium.
In the schemaless mode, the id field is always set as a string, since a unique field can't be tokenized (well, it can, but it'll give weird, non-obvious errors).
In your case i'd suggest defining the price field as an integer/long field (if it's integers all the way) and the name field as a string field. Be aware that string fields only generate hits on exact matches, so in your case you'd have to search for value124 with exact casing to get a hit.
You can also adjust the multiValued property of the field when you define the fields explicitly. That way you get only the string back in the JSON structure instead of an array containing the string.

aws elasticache with php - unable to set key/value pair

I am able to connect to my elasticache cluster like so:
$awsElasticache = new ElastiCacheClient(CredentialProvider::atsDefaultConfigConstructor(false, false));
$clusterResult = $awsElasticache->describeCacheClusters(array('CacheClusterId'=>'my_cluster'));
When I print $clusterResult, I get info about the cluster, good.
But how can I actually interact with the endpoint to set key/value pairs?
I am trying this without success:
$this->mem = new Memcached();
$this->mem->addServer($this->endPoint,11211);
$this->mem->set('myKey','myValue',3600);
$result = $this->mem->get('myKey');
echo $result;
I get nothing printed from $result.
I am confused about which object to use to set and get key/value pairs.
To set key/value pair in Memcached, always extend the time of expiry from current time.
Try this
$this->mem = new Memcached();
$this->mem->addServer($this->endPoint,11211);
$expires = Carbon::now()->addMinutes(10);
$this->mem->set('myKey','myValue', $expires);
$result = $this->mem->get('myKey');
echo $result;
NOTE: For some reason, Memcached works best with Carbon time
See https://artisansweb.net/work-php-datetime-using-carbon/ on how to setup and use Carbon on your current project

How to insert same `datetime` variable into different tables?

I'd like to store a datetime variable into different tables by using two functions. I use constraint in CI but still have no luck.
This is the constraint:
$date_now = date("ymdhis");
define('TODAY_DATE',$date_now);
These are the functions:
public function save_activity_m(){
foreach($details as $rows){
$stock_in = $rows['product']."_".TODAY_DATE;
$data['STOCK_IN'] = ($rows['product'] == "") ? NULL : $stock_in;
$this->MProduct->ins_product_m($data);
}
echo "<script type='text/javascript'>alert('New stock arrived');window.top.location.reload();</script>";
}
public function save_notifikasi(){
$lampiran = $this->input->post('lamp');
$data['note_date'] = $lampiran."_".TODAY_DATE;
$data['note'] = $this->input->post('isi');
$this->MProduct->ins_notif($data);
echo "<script type='text/javascript'>alert('You have a notification');</script>";
}
How to make the datetime is the same for $data['STOCK_IN'] and $data['note_date']?
Since the web is stateless, no data in a PHP variable will be held from one page (or load) to another; essentially you're booting the application from scratch each time.
The only way around this is to use some sort of semi-persistent storage such as a cookie or session variable (or persistent storage like the database) - setting a constant, e.g. define('TODAY_DATE',$date_now); will only make that data constant for the current execution of the script(s).
This is a basic example using session storage ($_SESSION):
<?php
// crank up the session
// you may well have one running already,
// in which case ignore this
session_start();
// store the execution time for this script
// as a session variable if it's NOT already set
// i.e. don't overwrite it
if(empty($_SESSION['time_now'])) $_SESSION['time_now'] = date("ymdhis");
public function save_activity_m() {
foreach($details as $rows) {
$stock_in = $rows['product'] . "_" . $_SESSION['time_now'];
$data['STOCK_IN'] = ($rows['product'] == "") ? NULL : $stock_in;
$this->MProduct->ins_product_m($data);
}
echo "<script type='text/javascript'>alert('New stock arrived');window.top.location.reload();</script>";
}
/**
* Assuming this is the last thing you want to
* do with 'time_now' you should unset it here
*/
public function save_notifikasi() {
$lampiran = $this->input->post('lamp');
$data['note_date'] = $lampiran . "_" . $_SESSION['time_now'];
$data['note'] = $this->input->post('isi');
$this->MProduct->ins_notif($data);
// since we're done with the 'time_now' session
// variable we need to unset it...
unset($_SESSION['time_now']);
echo "<script type='text/javascript'>alert('You have a notification');</script>";
}
// just to be on the safe side unset the 'time_now' session var
// if it's older than 1 minute - otherwise future calls to this
// script, by the same user, during the same session will use
// the stored value from $_SESSION['time_now']
if(isset($_SESSION['time_now'])) {
$sessionTime = DateTime::createFromFormat('ymdhis', $_SESSION['time_now']);
$oneMinuteAgoTime = new DateTime('-1 minute');
if($sessionTime < $oneMinuteAgoTime) {
unset($_SESSION['time_now']);
}
}
The caveat is that because you've stored the time in a session variable, unless you update or unset it, it will always be there (for the current session) - so if the user runs the script again it'll just use the stored time from the session.
I've put in a couple of unset() calls to try and work around this.
See PHP: define. It's a constant and it should have the same value if the two functions executed in the same time the script is running.

Categories