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.
Related
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.
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.
I've been looking around at similar topics on REST APIs but I am still having some confusion in my project, mostly with the PHP side of things.
USPS provides a REST API with functions that can be called via URL like this: https://epfws.usps.gov/ws/resources/epf/login
To make any call successfully, I have been told that a JSON object must be created and passed as a "POST parameter" with the expected values.
This is the JSON object that needs to be passed in this case:
obj=
{
"login":"loginExample",
"pword":"passwordExample"
}
I have also been given a PHP class that is supposed to manage these calls. This is the login function:
public function login ()
{
// Set up the parameters for a login attempt
$jsonData = array(
'login' => $this->loginUser,
'pword' => $this->loginPass,
);
// Make a login request
$jsonResponse = $this->pullResource
('/epf/login', 'POST', $jsonData);
return $jsonResponse;
}
So I have a few questions regarding this:
The document they sent says
"To make the request calls, a JSON object will need to be created and passed as a POST form parameter obj={jsonObject} for security reasons using content-type “application/x-www-form-urlencoded”."
I know that the login function contains the correct input values that USPS' REST API is wanting, but I'm not sure how to pass them as "obj", or how to apply the "content-type".
I have a "constant" defined at the top of my PHP script that looks like this:
const EPF_BASE_URL = 'https://epfws.usps.gov/ws/resources';
And I noticed in the actual functions that this part of the link is left out and they simply reference '/epf/login' as you can see above. Since "$this" contains lots of different values I'm wondering how it supposedly finds EPF_BASE_URL as needed. Is it similar to how 'using' directives work in C#?
What is the easiest way to call this function and display the result? This is my biggest question. Would I use a separate PHP class with an HTML form? I understand the concept of what it should do but I'm completely lost setting up a development environment for it.
I've been trying all of this with MAMP but would love to know if I'm on the right track or not.
That really depends on their API. Hopefully you get a string back that can be decoded to a JSON object (http://au.php.net/manual/en/function.json-decode.php). Some API might give a simple string that says 'SUCCESS' or 'FAIL'. You've got the code, so take a look at what $this->pullResponse() gives you.
If you've been given a PHP class that is supposed to support the API (hopefully from USPS), then it should already take care of putting the data in the form content, and ensuring is it submitted with the appropriate content-type.
A PHP const is more like a C# static string. It is very likely that the library will use the constant to create the end URL (i.e. EPF_BASE_URL . $resource). If you needed to run against a sand box environment, you could change that constant without having to change all the other code.
That's a very big question, because it depends on how you are programming your application. Procedural, MVC, existing frameworks, etc.
At the very least, you would set the loginUser and loginPass on the instantiated object, and call the login method`. You could then inspect the results, assuming the result is a JSON object, or use your favourite debugging method to see the contents.
I'm having a guess as the USPS API class name.
$uspsApi = new UspsApi();
$uspsApi->loginUser = 'username';
$uspsApi->loginPass = 'password';
$result = $uspsApi->login();
echo print_r($result, true);
I am currently writing an ajax-application, which gets some of its config-params by sessions.
The session['apps']['appXY'], which is holding these params, is built in the php-script, which provides the js-links, calling the ajax. As i dont want the sessions['apps']['appXY'] consume resources, when the user doesnt use the ajax-app, i have the session['apps'] array deleted each time, the user calls any site by regular/synchron way.
The order of the site-buildup is like this:
session['apps'] is deleted;
app-classes are included
within each app (f.e. appXY), if needed for ajax, the session['apps']['appXY'] is built (Step3)
site is built, loading is complete, user is calling some ajax-functionality, which may depend on the session['apps']['appXY']
The Problem with this now, if at the beginning of the sites building process the session['apps'] is deleted, that the session-array $session['apps']['appXY'] is not available within the ajax-script anymore, even though, it was rebuilt - and is existing and usable - in step3, the regular php-script of appXY.
If i dont delete the session its available by ajax too, but i dont understand, why is the session not available in the ajax-application, as the deleting of it is before the rebuilding? What could cause the fact, that session is available in regular php-script, but not in ajax, after deleting and rebuilding it?
Thanx, Jayden
As suggested by Ninsuo, i try to make the szenario more clearly by a more detailed model, containing some code:
In the main-class, before including any of the modules (apps) all ajax-sessions are deleted:
function get-apps()
{
unset($_SESSION['ajaxconf']);
require_once(appXY.php);
require_once(appABC.php);
}
Then, in class 'appXY.php' the session '$_SESSION['ajaxconf']['appXY']' is (re)filled:
class appXY extends base
{
function main ( $localconf, $lang )
{
foreach ($array as $key => $value)
$_SESSION['ajaxconf']['appXY'][$key] = $value;
return 'click
}
}
Getting the values from '$_SESSION['ajaxconf']['appXY']' works fine in the ajax-script, which is called by the javascript-function 'ajax-app()', as long as the the session is not deleted at the beginnning of the php function 'get-apps()'. If the session is deleted though, its not available in the ajax-file, even though, it has been redefined again in the class 'appXY', which clearly is included after deleting the sessions. to me, this doesnt make much sense, as the session is available in the class 'appXY'.
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.