Pass PHP object to another page via AJAX post - php

Anyone can help with this. I think i'm missing something basic and obvious!
I pass object $session from index.php to results.php like so..
index.php
include 'classes/user.php';
$session = new User();
//some object work
$sessionObjectStr = serialize($session);
<script>
var sessionObj = <?php if(isset($session)){echo json_encode($sessionObjectStr);}else{echo json_encode("");}; ?>;
$.post( 'results.php', {'object':sessionObj}, function(data){.....
</script>
results.php
include 'classes/user.php';
if(isset($_POST['object'])){ $session = unserialize(($_POST['object']));}
$session->getName();
The getName method returns nothing. It should return name like it did on index.php page..
var_dump from index.php for serialized $session
string(690) "O:4:"User":7:{s:9:"*userId";s:2:"27";s:7:"*name";s:5:"Admin";s:8:"*email";s:13:"admin#nrt.com";s:9:"*rights";s:5:"Super";s:9:"*cookie";N;s:12:"*lastLogin";s:10:"1475435341";s:5:"*db";O:8:"Database":4:{s:7:"*link";O:6:"mysqli":19:{s:13:"affected_rows";N;s:11:"client_info";N;s:14:"client_version";N;s:13:"connect_errno";N;s:13:"connect_error";N;s:5:"errno";N;s:5:"error";N;s:10:"error_list";N;s:11:"field_count";N;s:9:"host_info";N;s:4:"info";N;s:9:"insert_id";N;s:11:"server_info";N;s:14:"server_version";N;s:4:"stat";N;s:8:"sqlstate";N;s:16:"protocol_version";N;s:9:"thread_id";N;s:13:"warning_count";N;}s:10:"*numRows";i:1;s:13:"*affectRows";i:1;s:9:"*result";b:1;}}"
var_dump from results.php for $_POST['object'] - (serialized)
string(690) "O:4:"User":7:{s:9:"*userId";s:2:"27";s:7:"*name";s:5:"Admin";s:8:"*email";s:13:"admin#nrt.com";s:9:"*rights";s:5:"Super";s:9:"*cookie";N;s:12:"*lastLogin";s:10:"1475435341";s:5:"*db";O:8:"Database":4:{s:7:"*link";O:6:"mysqli":19:{s:13:"affected_rows";N;s:11:"client_info";N;s:14:"client_version";N;s:13:"connect_errno";N;s:13:"connect_error";N;s:5:"errno";N;s:5:"error";N;s:10:"error_list";N;s:11:"field_count";N;s:9:"host_info";N;s:4:"info";N;s:9:"insert_id";N;s:11:"server_info";N;s:14:"server_version";N;s:4:"stat";N;s:8:"sqlstate";N;s:16:"protocol_version";N;s:9:"thread_id";N;s:13:"warning_count";N;}s:10:"*numRows";i:1;s:13:"*affectRows";i:1;s:9:"*result";b:1;}}"
So as you can see the serialized versions are the same.. Once i unserialize on the results.php i should be able to use the object as i did before right?
Edit:
As suggested, and what i tried before posting this question was the decode the variable and then unserialize it. But it returns an error
if(isset($_POST['object'])){ $decodeObjStr = json_decode($_POST['object']); $session = unserialize($decodeObjStr);}
Fatal error: Call to a member function getName() on boolean
var dump for decoded_json.
var_dump($decodeObjStr);
NULL

Why? This is the first thing that popped into my head when reading your question. Why would you want to do this? It is a huge security risk, which can (and probably will) expose your users' details to a third party.Not to mention, giving the users a trivial way to increase their own permissions by simply editing the HTML code in their browser's built-in tools..
Most importantly: Why not use the built-in functionality of sessions, and their associated cookie? That way you only need to run session_start(), and use the $_SESSION array to store stuff in. Also, no need to involve AJAX or even JavaScript on this, as this functionality is all server-side. Sending data to the client, for it to just re-send it back to the server unchanged, is a bit unnecessary. Especially when you can just store it on the server in the first place. Don't you agree? :)
In this case I strongly recommend using sessions. Store the userID in the session, and use this to re-create the user object on each load. Querying the database if necessary.
There should be absolutely no need to serialize the object, nor creating your own custom-built "session state engine".
Quick code example:
index.php
session_start ();
$user = new User ();
// Woodoo here, creating new user or logging in.
$_SESSION['userid'] = $user->getID ();
?>
<html>
Results
</html>
results.php
session_start ();
$user = new User();
// Read the user's details from the DB, finalizing the object for use.
$user->read ($_SESSION['id']);
// Now we can do whatever we wanted to with the $user object.

Use json_decode() built in PHP function before making it unserialized.

Related

Hand over "data/params" on reroute(); in "fat free framework"

Im looking for an elegant way to hand over data/params when using $f3->reroute();
I have multiple routes configured in a routes.ini:
GET #sso: /sso/first [sync] = Controller\Ccp\Sso->first, 0
GET #map: /map [sync] = Controller\MapController->second, 3600
Now I reroute(); to #map route, from first();
class Sso {
public function first($f3){
$msg = 'My message!';
if( !empty($msg) ){
$f3->reroute('#map');
}
}
}
Is there any "elegant" way to pass data (e.g. $msg) right into $MapController->second(); ?
I donĀ“t want to use $SESSION or the global $f->set('msg', $msg); for this.
This isn't an issue specific to fat-free-framework, but web in general. When you reroute, you tell the browser to redirect the user's browser page using a 303 header redirect code.
Take a minute to read the doc regarding re-routing: http://fatfreeframework.com/routing-engine#rerouting
There seems to be some contradicting information in your question, which leads me to question the purpose of what you are trying to achieve.
If you are rerouting, you can either use the session, cookies, or use part of the url to pass messages or references to a message.
If you do not need to redirect, but just want to call the function without changing the passed parameters, you could abstract the content of the function and call that function from both routes. You could also use the $f3 globals, which are a great way of passing data between functions in cases where you don't want to pass the data using the function call. is there a reason why you don't want to to use this? The data is global for the single session, so there is no security concern, and the data gets wiped at the end of the request, so there is very little extra footprint or effect on the server.
If you're alright with not using #map_name in re-routes you can do something like this:
$f3->reroute('path/?foo=bar');
Not the prettiest I'll admit. I wish $f3->reroute('#path_name?foo=bar') would work.

How to preserve facebook objects between calls in php?

I render the page corretly, display images etc. But when the user changes the album selection I want to use ajax to refresh the div.
My problem is that when I send the call to the server it gets an exception since the facebook objects are dead/no-reference, I don't know.
I tried to save them with session_start. I can pass strings like this but if I pass the objects like this than calling them still fails:
$albumID = $_GET['album'];
$facebook = $_SESSION['fb'];
$albums = $_SESSION['albums'];
$tester = $_SESSION['tester']; //works fine
echo get_pictures_from_album($facebook, $albums, $albumID);
I would also reallt appriciate it if someone can refer me to good documentation. It seems that facebook only have examples for the simple, trivial issues but no complicated apps.
If you are storing an object in the session, you need to make sure you require the file containing the class definition before you call session_start. Otherwise PHP won't be able to deserialize the objects from the session correctly.

How to store search result?

I am working on my personal site, where I want to store my customers recent search result limited to that particular session.
I am using PHP platform and Javascripts.
Here is an example of what I am exactly looking at :
It stores your previously searched domain name for that particular session so that user can make decision by comparing those results.
Thanks.
EDIT- Well Thanks for all of your answers and suggestions.
But If you have noticed
above example
It looks like some kind of script loading a new content on the same page without refreshing it and keeping previous search content <div> as it is.
How to achieve this using javascripts or some sort of div layer ????
UPDATE START
This example uses page reload. If you want to do it without page reload, you can but you'll have to use AJAX to load new search results. But then, it's not a PHP question. I suggest looking at jquery library, as it makes it easy. Tutorials: http://docs.jquery.com/Tutorials and e.g. this one ( http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery#Rate_me:_Using_Ajax ).
When loading data via AJAX, the page rendering result (in my example search.php) should return only HTML for results part, not whole HTML page. This is generally a first part of my tutorial (without session).
But I really think that AJAX in here is not really needed. Session is more reliable and allows access to your page from older / mobile browsers where not always JS works correctly.
UPDATE END
Ok then. Let's try the simple tutorial then. Sorry if too simple, but I don't know your exact level.
PHP has mechanism called sessions. In reality they are just bytes stored on server. Server knows which session is for each client by reading session cookie from client browser.
Not every page uses sessions (not every page needs it, and session uses server space, even if only temporarily), session is not enabled by default. To turn on session you use command
<?php session_start(); ?>
In most cases this is either run by PHP framework you use, or put near the top of your site. Session is definitely needed if you want to authenticate user somehow. Or in your case :)
To access session you can use superglobal $_SESSION variable (superglobal means that you can access it anywhere). It's an array, so session element will be e.g. $_SESSION['search'] etc.
As example, let's assume that your page looks like that
<html>
...
<form action="search.php" method="post">
Search: <input type="text" name="searchQuery" />
<input type="submit" value="Search" />
</form>
...
</html>
this very form will send user search to file named search.php. It can be the same file where the form resides - in simplest case when you put both your code and HTML in one file. Beginners often use this schema, although it's not advisable as result is a mess and hard to further change.
In search.php then, you'll use similar code:
<?php
if (!empty($_POST['searchQuery'])) //we have a new search
{
$result = do_search($_POST['searchQuery']);
}
?>
Then, somewhere below you'll display your search result ($result variable). do_search() function is your search mechanism, I guess you have it somewhere. You may have it not 'wrapped' in a function, then I advise to create it like that, it's much more useful.
function do_search($searchQuery)
{
...
return $result;
}
mind it, the above code doesn't use sessions yet. Let's add saving previous search results in session. The code may then look like that:
<?php
session_start(); //Starting session
//let's create session variable used to store results
if (!isset($_SESSION['searches']))
$_SESSION['searches'] = array();
if (!empty($_POST['searchQuery'])) //we have a new search
{
if (isset($_SESSION['searches'][$_POST['searchQuery']]) //User already searched on this value, delete previous result from sesion
{
unset($_SESSION['searches'][$_POST['searchQuery']]);
}
$result = do_search($_POST['searchQuery']);
//Let's add new search on the begining of session array to make iterations easier.
$result = array($_POST['searchQuery'] => $result); //convert result to same format as session table
$_SESSION['searches'] = array_merge($result, $_SESSION['searches']);
}
?>
In display you'll now not iterate on $result variable as before, but instead you will do something like
foreach ($_SESSION['searches'] as $query => $result)
{
...//display of single result
}
I haven't tested following code and it's not a full program. Parts to display result and to do actual search are not described but I guess you have them already prepared. Also, this is only one possible approach of countless possibilities. But I hope this helps :)
Possible modification - now I always perform search, even if user already searched on this term. You may want to receive the result from cache without second search. Then the code will look like
if (isset($_SESSION['searches'][$_POST['searchQuery']]) //User already searched on this value
{
$result = $_SESSION['searches'][$_POST['searchQuery']];
unset($_SESSION['searches'][$_POST['searchQuery']]);
}
else
{
$result = do_search($_POST['searchQuery']);
}
For more in-depth information about sessions and some other constructs used in my example I suggest PHP manual
http://pl.php.net/manual/en/book.session.php
and various tutorials over the network. Or you can add a comment here :)
Put this code near the beginning of your script(s):
if (!isset($_SESSION['previous_searches']) || !is_array($_SESSION['previous_searches'])) {
$_SESSION['previous_searches'] = array();
}
[edit]
This code snippet checks if if there is already an array with prevous searches and if not it will be created.
[/edit]
Then when the user hits the search page put this code in the receiving script of the search:
$_SESSION['previous_searches'][] = $_GET['what_ever_your_search_value_might_be'];
[edit]
This code snippet adds the current search value to the and of the array with previous search values
[/edit]
Now you have all previous search values in $_SESSION['previous_searches']
If your website is a web application where you never reload the page nor change the page, you can keep it JavaScript in a global store (declare at top level something like var StoredSearch = []; and use it). If not, then use $_SESSION to store this and AJAX to save/load searches from JavaScript to PHP.

PHP, jQuery and Ajax Object Orientation

I'm a fairly experienced programmer getting my head around PHP and Ajax for the first time, and I'm having a bit of trouble figuring out how to incorporate object-oriented PHP into my ajax webapp.
I have an admin page (admin.php) that will load and write information (info.xml) from an XML file depending on the users selection of a form on the admin page. I have decided to use an object (ContentManager.php) to manage the loading and writing of the XML file to disk, i.e :
class ContentManager{
var $xml_attribute_1
...
function __construct(){
//load the xml file from disk and save its contents into variables
$xml_attribute = simplexml_load_file(/path/to/xml)
}
function get_xml_contents(){
return xml_attribute;
}
function write_xml($contents_{
}
function print_xml(){
}
}
I create the ContentManager object in admin.php like so
<?php
include '../includes/CompetitionManager.php';
$cm = new CompetitionManager()
?>
<script>
...all my jquery
</script>
<html>
... all my form elements
</html>
So now I want to use AJAX to allow the user to retrieve information from the XML file via the ContentManger app using an interface (ajax_handler.php) like so
<?php
if(_POST[]=="get_a"){
}else if()
}
...
?>
I understand how this would work if I wasn't using objects, i.e. the hander php file would do a certain action depending on a variable in the .post request, but with my setup, I can't see how I can get a reference to the ContentManager object I have created in admin.php in the ajax_handler.php file? Maybe my understanding of php object scope is flawed.
Anyway, if anyone can make sense of what I'm trying to do, I would appreciate some help!
think of each ajax call as a separate request. if in the life cycle of a particular request you have not instantiated your ContentManager, the object doesn't exist. If you'd like to use a single object between multiple requests, serialize it to session and deserialize it early in the request life cycle.
I dont know if this is what you need, well, here goes. Have a single PHP file to handle all the form submissions. For eg: proc.php or something like that in the ACTION="proc.php". Inside the proc.php, depending upon the parameters submitted, make function calls. One other thing you should likely do is to create an instance of the class (the object) at the end of the class file itself avoiding the need to check everytime if the object was instantiated or not.
Use global $objectname before you make calls to the object functions, if necessary.

How can I generate Dynamic Javascript?

I render a page using YUI. and depending on the user I need to change how it is rendered. This change is not something that can be parametrized, it is drastic and different for each user.
Please tell me how can I generate Javascript dynamically?
I personally use a PHP file to pass a JavaScript object made up of some basic session and internal settings, nothing mission-critical as passing information to the client isn't overly secure, but I believe it might follow the same principles as what you are looking for.
Similarly, I use this to display certain elements once the client is logged in, although all the authorization is still done on the server-side. If my session handler gives the PHP file the ok, it outputs a JavaScript object using a PHP heredoc string, otherwise, it doesn't output anything. You can use attributes of this object to compare against, or you could output only the JavaScript for how a certain page should be rendered, based on settings in your PHP file.
HTML:
<script src="common/javascript/php_feeder.php" type="text/javascript"></script>
PHP:
//my session handler authorisation check has been removed
//although you could place your own up here.
//assuming session was authorised
//set content type header
header("content-type: application/x-javascript");
$js_object = <<<EOT
var my_object = {
my_attr: '{$my_attr}',
my_attr2: '{$my_arrt2}',
etc: '{$etc}'
}
EOT;
print($js_object);
You can probably create two separate Java script files, and include the required file, depending upon the user type.
Pseudocode
If user_type is One
<Script src='one.js' type='javascript'></script>
else
<Script src='other.js' type='javascript'></script>
End If
JavaScript has an eval function, so I think (I haven't tried it) that you can generate JavaScript by writing it into a string variable (and then calling eval on that string variable).
A little bit of elaboration here would most certainly help in getting you a more descript and helpful answer. That in mind, though, you could easily just use functions declared inside an if statement to provide distinctly varied experiences for different users.
A very basic example:
<script>
function do_something(userType)
{
if (userType == 'A')
{
// everything you need to do for userType A
}
if (userType == 'B')
{
// everything you need to do for userType B
}
}
</script>

Categories