Advised way to access PHP class instance in AJAX call? - php

I have a pretty big PHP class instance with quite a lot of methods and potentially including semi-sensitive data that I would need to be able to access through AJAX. I've read about and successfully tested $_SESSION to transfer the class and object, but there seem to be some security concerns. Eg. see How safe are PHP session variables?, and PHP Session Hijacking.
Previously I 'solved' this by simply require'ing the class and re-instantiating the object on every AJAX call/ or making those methods I needed static (after checking for a token and a constant), but I feel like this should be quite performance-heavy (how long does it take for PHP to initialize an object which reads in 200+ JSON/XML files?).
Another option I see is serializing the data in a temp file, but really I have no idea nor experience of what is the best way to go from a performance vs security point of view... Any help will be appreciated, thanks.

Related

PHP Storing a Class in session

I have searched and searched and found tons of examples but it seems that everyone has a different opinion about how and when to use session, some use it some say it is evil...
Here is my use case.
I have a Class that has several variables that will need to be used on every page in my application. These variables values are set by making a SOAP call to an API that I am working with. The SOAP call is relatively quick but I am trying to understand how to avoid making a call to the API on every page. I would much prefer to make the call once and then "store" the values somewhere.
I would think that I would just create an Instance of my class on some say Init.php page, make the SOAP calls and then store the whole class in session. Then on all of my pages include the Init.php page. In that page I would do a check to see if the Class existed in the session and if so then pull it form the session.
I know I have to serialize\deserialize the class to do this but I am looking for some feedback here on weather this is the right way to satisfy this use case or if there is a better option?
I am kinda new to PHP, mostly a .NET guys and in .NET the session is generally the best way forward.
All input is appreciated.
thanks
I assume when you stay "serialize\deserialize the class," you really mean you want to serialize/deserialize a class instance (an object) in the session, not the actual class definition. Be careful when using the terms class, instance, and object, since they are not interchangeable and can lead to confusion.
An object can be easily stored in a PHP session. PHP automatically serializes the object at the end of the request and deserializes it when the session data is read on the next request.
session_start();
if (!isset($_SESSION['soap'])) {
$_SESSION['soap'] = doSoapRequest(); // Returns an instance of your class.
}
When an object is serialized, only the variables defined in the class are saved along with the name of the class. When it is unserialized, the class definition must be available (that is, either autoloader or explicitly included into the script). Unserializing will create a class instance with the same data as the object that was previously serialized.

Passing an Object between PHP pages, IDE and passing object to other classes problems

I've inherited some PHP code that I need to make significant changes on. I know with PHP it is possible to serialize an Object, and pass the serialized text between pages as FormData. In the code I've inherited, they have done just that, But this is creating some maintainability problems. I'm wondering if taking this approach is even a good idea.
For example ...
When the user opens PageA.php the following is created:
$expensiveObj = new ExpensiveClass($id);
The $expensiveObj is then serialized and the resulting text is stored in a div with the following:
<div id="expensiveObj"><?php echo strtr(base64_encode(serialize($expensiveObj)), '+/=', '-_,');?></div>
When PageA.php loads, an ajax call is made to PageB.php. The content of the div is passed along as a post variable to PageB.php. Within PageB.php the following code unserializes the object:
$expensiveObj = unserialize(base64_decode(strtr($_POST['expensiveObj'], '-_,', '+/=')));
The fields and methods of the $expensiveObj are now accessible to PHP. The problems I'm encountering are
Because the $expensiveObj is not identified in PageB.php as an instance of the Class ExpensiveClass then the IDE doesn't know that the fields and functions of ExpensiveClass are available. I can't do autocomplete, nor lookup within the IDE what functions are available. Plus the IDE can't catch potential issues. The other developer worked exclusively in VI, so he never cared.
PageB.php needs to be re-factored. There is view, business, and controller logic all happening within this page, I would prefer to create a couple of classes, but I'm encountering a problem where I don't know how to pass the $expensiveObj to a class.
My questions are, is there a way to pass an Object to a class? And is there a way inform the IDE that the passed in post variable is indeed an instance of ExpensiveClass?
Lastly, is it even a good idea to be passing around objects this way, or should I be looking at a larger re-factor?
Storing objects directly in HTML is never a good idea, because it can be easily changed by client. In PHP is more common to create new object on every request according to given parameters. I see you are initializing your object using $id, so you can just pass this id between requests. Storing data to session also isn't best practice, session should be used for session-specific data, e.g. logged-in user etc.
If the creation of the object is very expensive, you can use cache, e.g. memcache, some external library or just to write your own, for example storing data in JSON on file system or in database.

PHP Performance: Storing a Class Object in a Session vs Static vs Globals

I've been looking for an answer on this, so far I have been unable to find an answer. My question is; What is the best way to store a huge global class that does not require any dynamic input, it only needs to be used once.
Lets take for example a template class:
<?php
class Design_API{
function loadfile($file){
//load file here
}
// do file manipulation here
function presentfile(){
echo($this->file);
}
}
?>
Utilizing this class as a basic example of a layout. What would be the best way performance and security wise to use it. Would it be to create an instance of it as a global; store the instance in a session; or simply make it a static class.
Also, say we used a session if 2 clients access the site at the same exact millisecond, would php lock the session file forcing client 2's web load to take longer?
This question is a bit too mixed up to be answered in a consistent way, so here are some points:
one client does not block another, unless they're accessing a shared resource
sessions are not shared resources between different users, forget about this misconception
wherever you store objects hardly makes a difference in performance
it makes even less of a difference between different requests and users, since no resources are shared between requests
code what you mean first and what is most maintainable, optimize this for performance later when it is proven to be slow (which it likely won't be)
avoid globals wherever possible
don't store stuff in the session that does not belong there, like code
avoid static classes as much as possible, they cause code coupling, which should be reduced
static classes are not necessarily faster
The best way to handle this is to make the class a Singleton class and use the static method to instatiante it.
Storing the object in session will involve serialization and de-serialization which is very bad for performance. Also if you store any resources in the class they can't be serialized.

ideas for simple objects for day to day web-dev use?

Dang-I know this is a subjective question so will probably get booted off/locked, but I'll try anyway, because I don't know where else to ask (feel free to point me to a better place to ask this!)
I'm just wrapping my head around oop with PHP, but I'm still not using frameworks or anything.
I'd like to create several small simple objects that I could use in my own websites to better get a feel for them.
Can anyone recommend a list or a resource that could point me to say 10 day-to-day objects that people would use in basic websites?
The reason I'm asking is because I'm confusing myself a bit. For example, I was thinking of a "database connection" object, but then I'm just thinking that is just a function, and not really an "object"??
So the question is:
What are some examples of objects used in basic PHP websites (not including "shopping cart" type websites)
Thanks!
Here's a few basic reusable objects you might have:
Session (identified by a cookie, stored server side)
User (username, password, etc.)
DBConnection (yes, this can be an object)
Comment (allow users to comment on things)
It sounds like you want to start to build your own web framework, which is a decent way to learn. Don't reinvent the wheel though. For a production site, you're probably better off using an existing framework.
Since you said you don't want to glue HTML and CSS again, you don't try this:
Create a WebForm class. This class is a container of form elements. It has methods to add and remove form elements. It has a getHTML() method that writes the form so that the user can input data. The same object is when a POST is made. It has a method to validate the input of the user; it delegates the validation to every form element and then does some kind of global validation. It has a process method that processes the form. It is final and checks whether validation has passed. If it passed it calls an abstract protected method that actually does the form-specific processing (e.g. insert rows into the DB). The form may be stored in the stored in session, or it may be re-built everytime (if it is stored in the session, it's easier to make multi-page forms).
Create a BaseFormElement and then several child classes like EmailElement, PhoneElement etc. These have also a getHTML() method that is called by WebForm::getHTML() and that prints the specific element. They have a validate() method that is called by WebForm::validate() and a getData() method that returns the properly validated and processed data of that element.
These are just some ideas. Some things may not make sense :p
I'd say database access would be the first most likely object - encapsulate your most common SQL requests into one class. If you make them abstract enough, you can use them for a wide variety of data access situations.
The way to think about class design/usage is to think of the class responsibility. You should be able to describe the class purpose in a short sentence (shorter than this...) i.e for database access object, you might say:
"provides API for common data access tasks"
If any of the methods in your data access class do something other than that, then you know they belong somewhere else.

Implementing own Session Management in PHP

What options are there to implement an own session management in PHP?
Is there a nice way to implement a component which performs all session tasks?
How can i construct a class which receives the HTTP Request and Response during one request process?
I only found the option "session_save_handler" which seems to define the storage handler. What I need is to replace the whole session management.
Is there another way using the PHP configuration or do I have to implement my own controller which receives all requests and calls my session management?
Thanks for your help
Regards Michael
No, I'm sorry to say, there is no interface to switch the built in 'modules' to your own. There are some hooks ( e.g: session_save_handler(), set_error_handler() ), and that's unfortunately it.
The $_SESSION is a 'super global' and should IMO not be set directly either way if you're working on a bigger projects. Then it would be better to use a custom class responsible for handling sessions. Will make the code easier to debug and such on.
I am not sure, what you want to achieve. It seems more like you want to abstract away from the $_SESSION variable than that you want to change the storage.
Take a look at the way the Zend or the Solar framework handle the Session access.
http://www.phpeveryday.com/articles/Zend-Framework-Session-Introduction-P571.html
http://solarphp.org/manual:sessions
How can i construct a class which receives the HTTP Request and Response during one request process?
I don't know, what you mean by receiving the response, but the frameworks have front-/page-controllers which route to the chosen action, then call a method that can access the Session (read/write) and Request (read) objects and generates a Response object which is then rendered through a template.
For automatic testing you can construct your own Request and Session objects and pass them to the page controller.
You said it yourself in one of the comments. Just wrap the $_SESSION in a class. I don't think you can replace it, but you can certainly build your own interface to it.
You could, for example. Build a class that is constructed first thing and call session_start() inside the constructor
Using the session_save_handler() function allows to handle how the session information is stored and retrieved.
By default PHP stores the session information in temporary files located somewhere on your web server. You can define callback functions using the session_save_handler() function where you can have this information stored in a database table instead.
Even if you handle sessions with your own defined functions with the session_save_handler() function you would still access the information with the superglobal variable $_SESSIONS.
Check out this page from the php online manual. Has lots of useful information with regards to your question. Hope it helps.
You could create a session implementation with cookies and a database. You set a cookie on the client's machine. Then, you run a lookup on a database, something like this:
+--------+------+
| sessid | data |
+--------+------+
Where sessid contains a reference to the cookie (probably some king of md5 or SHA hash), and data is something like a JSON or Serialized array.
The functions:
You can use the function runkit_function_redefine(), which is part of the Runkit API, to redefine the session_xxxx functions.
Note: Runkit is part of PECL. That is, NOT BUNDLED WITH PHP. You will have to install it yourself.
The session variable:
$_SESSION = &SessionClass->data;
Simplicity itself: just make $_SESSION as a reference to YOUR data.

Categories