How to call destructor after response in php? - php

I have a chat bot which save some data into db which user is sending. I want to save it to db (a slow network call) after sending response to the user.
I could do that in Python Tornado but I havent been able to do it PHP Apache.
user sends input as request -> we process it -> we send output to user as response -> then we wish to store data
class A
{
function __construct()
{
echo "Hello World";
}
function __destruct()
{
sleep(15); //I want this to happen after response is being send
}
function calc()
{
echo "Progress World";
}
}

__destruct is called upon object deletion, the object being out of scope, or normal script ending. If the script isn't terminating normally but killed, the destructor may not be called at all.
If you just want to do cleanup task at specific points and ensure them being processed use the PHP 5.5-introduced finally clause
A __destruct example from the PHP site:
<?php
class my_class {
public $error_reporting = false;
function __construct($error_reporting = false) {
$this->error_reporting = $error_reporting;
}
function __destruct() {
if($this->error_reporting === true) $this->show_report();
unset($this->error_reporting);
}
?>
See the PHP Documentation on destructors. I hope this helps.

Related

Pubnub PHP SDK subscribe function

I'm working on a chat application using PubNub and PHP. The publishing of messages is working but I'm not sure how to read from the subscriber.
I ran the subscriber file in the command line and it is showing the messages as they are published but I'm not sure how to read from it or how to return, as per the doc the subscriber is a separate process.
use PubNub\PNConfiguration;
class MySubscribeCallback extends SubscribeCallback {
function status($pubnub, $status) {
if ($status->getCategory() === PNStatusCategory::PNUnexpectedDisconnectCategory) {
// This event happens when radio / connectivity is lost
} else if ($status->getCategory() === PNStatusCategory::PNConnectedCategory) {
} else if ($status->getCategory() === PNStatusCategory::PNDecryptionErrorCategory) {
// Handle message decryption error. Probably client configured to
// encrypt messages and on live data feed it received plain text.
}
}
function message($pubnub, $message) {
print_r($pubnub);
print_r($message);
}
function presence($pubnub, $presence) {
// handle incoming presence data
}
}
$subscribeCallback = new MySubscribeCallback();
$pubnub->addListener($subscribeCallback);
$pubnub->subscribe()
->channels(["Channel-1","Channel-2","Channel-3"])
->execute();
this is the subscriber code present on the PubNub Doc.
I'm calling this file using javascript.

How to use a SOAP API with login and session codeigniter

I have a set of soap APIs which can perform actions like login,logout,keepalive,access other several resources.Inorder to access the other resources,I have to pass a session id which I got from the login api.The session gets time out in 5minutes.
I am confused on how to make this working.
I am using codeigniter for my project,and I have built one library with the set of soap api requests defined in it.
class Soap_api
{
function __construct()
{
define("UID", "myuser");
define("PWD", "34rf3a45575");
define("API_ENDPOINT", "http://uat-api.testingsoapapi.in/services/smp");
define("PRODUCT_CODE", "24");
$resp = $this->keepAliveLib();
if($resp['ResponseCode'] == '0')
{
define("SessionID",$resp['SessionID']);
}
}
function keepAliveLib()
{
$resp = $this->login();
return $resp;
}
function one
{
//This function needs the sessionID receieved from login function
}
function two
{
//This function needs the sessionID receieved from login function
}
So when ever any of the functions from this class is accessed,the constructor calls the keepAliveLib which calls the login function residing in this class and return the session id to the constructor function and set it as global constant sessionID .So the function which I called will be using the that session ID which is made as a constant.
Is this the standard way of calling APIs which relay on sessions?The login function is called when ever a function is called and creates a different session ID.There is a function keepAlive in the library which can be used to maintaining the session,but instead of using keepAlive , Im logging each time a function in this is accessed.
Is there anything wrong in this flow?Can this be done in some other ways?
ok i'm probably not understanding this fully but would this work?
$resp = $this->keepAliveLib();
if($resp['ResponseCode'] == '0') {
$this->sessionid = $resp['SessionID']); }
else { // fail gracefully }
$this->sessionid is now available to any method in the controller.

How to save an object in PHP and access it everywhere?

I am new to PHP and I want to save an object from this class which I can access in my webservice this object hold a sessions id which can be used for calling an API:
MyObject.php:
class MyObject {
private $sessionId = '';
private function __construct(){
$this->sessionId = '';
}
public static function getInstance() {
if (!$GLOBALS['MyObject']) {
echo 'creating new instance';
$GLOBALS['MyObject'] = new MyObject();
}
return $GLOBALS['MyObject'];
}
public function getSessionsId() {
if ($GLOBALS['MyObject']->sessionId == '') {
// Do curl to get key (works)
if (!curl_errno($curlCall)) {
$jsonObj = json_decode($result);
$sessionID = $jsonObj->session_id;
$GLOBALS['MyObject']->sessionId = $sessionID;
}
}
return $GLOBALS['MyObject']->sessionId;
}
}
Webservice GetKey.php
include 'MyObject.php';
$instance = MyObject::getInstance();
echo $instance->getSessionsId();
The I visit the GetKey.php file it always echoes 'creating new instance'
what you store in $GLOBALS will be destroyed when the page is loaded... that variable is available only when the response is being created...
You don't save an object and use it everywhere (for all users) .. you are in php :) and you can store it anywhere... but if you're in a function then it will be destroyed when you are outside the function...
And in webservices you don't use session because it won't exist at next operation call
In the case that you want to store that variable for multiple requests of the same user you can store it in $_SESSION and not in $GLOBALS...
In PHP everything is destroyed when the user gets the response... (only session is an exception)... a session is like in java or any other language... you have it / user and you can modify it at request time... you don't have something like applicationScope and store there everything for all users... everything is being recreated at every request

PHP session being lost

I'm trying to implement and authentication system with jQuery and PHP. All the php work is made in the controller and datahandler class. There is no php code inside the .html files, all the values in .html files are rendered via jQuery that request the data from php server. So what I'm trying to do is:
When user clicks the login button, the jQuery makes a call to the authenticate() method in my controller class, it checks if the user is correct and stuff, and if it is, start the session and set the user_id on the session so I can access it later, and returns the userId to the jQuery client again.
After that, if everything is fine, in jQuery I redirect it to the html file. On the html file I call a jQuery from the <script> tag that will handle other permissions. But this jQuery will access the method getPermissionString (from the same class of authenticate() method mentioned before), and it will need to get the session value set in authenticate method.
The Problem:
When I try to get the session value inside getPermissionString() it says:
Notice: Undefined variable: _SESSION
I've tried to check if the session is registered in the second method, but looks like it's not. Here is my PHP code.
Any idea? Thanks.
public function authenticate($login, $password)
{
$result = $this->userDataHandler->authenticateUser($login, $password);
if(is_numeric($result) && $result != 0)
{
session_start();
$_SESSION["uid"] = $result;
if(isset($_SESSION["uid"]))
{
echo "registered";
$userId = $_SESSION["uid"];
}
else
{
echo "not registered";
}
echo $result;
}
else
{
echo 0;
}
}
public function getPermissionString()
{
if(isset($_SESSION["uid"]))
{
echo "registered";
$userId = $_SESSION["uid"];
}
else
{
echo "not registered";
}
}
Before you can access $_SESSION in the second function you need to ensure that the program has called session_start() beforehand. The global variable is only populated when the session has been activated. If you never remember to start a session before using it then you can change the php.ini variable below:
[session]
session.auto_start = 1
Further, you said that you're using a class for your code. In this case you can also autos tart your session each time the class in created by using magic methods:
class auth {
function __construct() {
session_start();
}
function yourfunction() {
...
}
function yoursecondfunction(){
...
}
}
If you don't have session.auto_start enabled, and authenticate and getPermissionString are called on two different requests, you need to call session_start() in each function.
If you need more information on how the session ID is passed, just read Passing the Session ID
You should not use that function if session is not started. So throw an exception:
public function getPermissionString()
{
if (session_status() !== PHP_SESSION_ACTIVE)
{
throw new Exception('No active session found.');
}
if(isset($_SESSION["uid"]))
{
echo "registered";
$userId = $_SESSION["uid"];
}
else
{
echo "not registered";
}
}
This ensures the pre-conditions of your functions are checked inside the function so you don't need to check it each time before calling the function.
You will now see an exception if you wrongly use that function and it will give you a backtrace so you can more easily analyze your code.
For php sessions to work you have to call session_start() every time you script is requested by the browser.

The Right Strategy for PHP Session User in Ajax Application

I'm writing a Ajax/PHP web application. Most ajax calls are using accessing the user object which is stored in the session.
<?php
session_start();
function session_user()
{
static $session_user = null;
if (!isset($session_user))
{
if (isset($_SESSION['user']))
$session_user = unserialize($_SESSION['user']);
else
$session_user = new User();
}
return $session_user;
}
class User {
public $books_borrowed = array();
public function __construct()
{
}
function __destruct()
{
// store the user object in the session upon destruction
session_start();
$_SESSION[ 'user' ] = serialize( $this );
}
function authorise($user_id, $password)
{
// if the user_id and password match, load books_borrowed from the DB
...
}
function deauthorise()
{
session_destroy();
}
}
?>
Ajax calls access the user object like this:
return session_user()->books_borrowed;
Note that the user object stores itself upon destruction, which, as far as I can tell, happens just before the ajax call return.
The reason I'm storing the user object to the session every time the object is destroyed is that it contains other objects (books) that might change during ajax calls, and neither do I want the book object to 'know' about the user object (for reusability) nor do I want to bother with having to remember storing the user object whenever any information within it changes.
Can someone see anything wrong with this strategy?
Thanks
The main strategy when you make a design for brand new application with ajax is not to think of ajax like about something special. It is regular request performed by browser. Absolutely the same like when you open new page by typing url manually and pressing enter.

Categories