PHP splitting up classes - php

I'm fairly new to PHP and trying to figure out how to logically split up my classes. Here is the very basic setup.
index.php -- Top page. When login button is pressed, it calls an external authentication server.
callback.php -- Authentication server sends call back here. I store the user's login name.
game.php -- this is where I have a web game that makes a POST request to callback.php
Here is what I thought is "correct" practice from other OO languages.
I'd like to get the data received in callback.php and store it somewhere else (data.php). The only way I can figure out how to do this is to use a session in callback.php and read it in data.php. Is there a better way to do this or should I keep the data in callback.php (and make the POST request to callback.php instead of data.php)?
After the callback.php gets the data from the authentication server, I use a redirect to go to game.php. If the user goes straight to game.php and isn't logged in, I also use a redirect. Is there a better way?
header("Location: http://www.mypage.com/game.php");
I'm happy to post any code but I'm guessing it's not necessary for these types of questions. Let me know and thanks!

The purpose of OO programing to keep code as module as possible while bundling relative modules together.
Example:
User Object - contains all code relative to users
Game Object - contains all code relative to games
It is still very likely that you will have code that doesn't belong to a specific object, but more to a particular set of actions. However, OO programming can still be applied even to these.
Example:
Action page: contains all code relative to dealing with a specific group type of actions (Like handling all the actions/callbacks from a specific frontend page).
That being said, your initial statement of separating into the 3 different files is fine.
I'm assuming the index.php is the front facing said that the user interacts with, so separating that from the backend process or controller is good. It would be better to use an require_once("data.php") versus sending the data over the network again and this way you can save the data to that instance and access it without having to use session variables. I can process the data however you want, and once you get the desired results you can do your header() redirect.

Related

How to forward (not redirect) requests in PHP?

I am working on a simple PHP site that involves needing to be able to forward a request made by the user to another page (note that I said forward, and not redirect). I am aware of how to redirect by manipulating the header variable, but I do not wish to do this, as explained below.
I am trying to write a very simple MVC-patterned mailing list app in PHP, drawing from my knowledge of the same in JSP. One of the things that I appreciated about JSP was that you could both forward or redirect a request. For my purposes, I need forward as I wish to keep the request parameters (whereas redirect will drop them).
Here is a description of what I wish to accomplish:
Retrieve input from a form (ie. /add.php)
Process the input in the page called by the form's action (ie. /process.php) and add a success message to the request object
Forward to another page (ie. /display.php) to display the success message in the request object
The only way I am aware of passing the request message to display is to add it to the request object and then access it from the forwarded page. However, the only way I have had success in transitioning to another page is through using the header method, which drops the request object (from what I can tell). I want to find a way to forward the request (object) to the new page, so that I can access the request variables from the new page.
Is there actually anyway to do this in PHP? Java's getRequestDispatcher.forward() is so nice, but I can't find an equivalent through searching. I've tried several similar questions, including the following, but I've never actually found one where both the question and the answer were what I wanted. Most of the answers seem to have something to do with cURL, but I don't want to actually retrieve a file, but simply forward a request in order to access the request object from another page.
Does PHP have an equivalent of Java's getRequestDispatcher.forward()?
Let me know if I should include anything else?
I believe you can do this with include. Before submitting the form just use, as inclusion, in main page:
include ("add.php"); - where the input forms are
after processing the information, include the display.php in the same way; using this, display.php will use same parameters from header, because is included in the same main page.
briefly: add.php, process.php and display.php will be modules for the mother page, but loaded in different state of form processing.
Hope it helps!
use curl with different method get,post. it will sent a request and also get back the response.
The most common method I see of passing messages to the end user from page to page is called session flashing.
This is when you store a variable temporarily in the session until it is read.
Assuming you already have sessions in use:
On process.php:
$_SESSION['message'] = 'Your data has been saved!';
On display.php:
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
You could also store the entire Request object in the session.
So if I am aware, PHP provides just basic set of tools in this case. And there is nothing like "forward" in HTTP originally. It is just frameworks' abstraction/idea. There are two ways to achieve that: copying all params from request and doing new real HTTP request (with redirect) or internal forward: so framework would create fake request and call another controller and action without issuing a new physical HTTP request.

Login sytem with PHP

Good day.
I have questions about the login system , that disturbed me quite a long time. For this i want you to imagine that i have 2 pages login.php and userpage.php. The login page contains fields for input of user name and password. While userpage contains all the information about the logined user. When user inputs his data, some class Connection checks him in the database and if user exists, creates a session.
When I'm creating a redirection from login.php to userpage.php, how should i redirect users data? (Should I use global arrays (like $_SESSION) to transfer the info or I should connect the db again from the user page?)
Should I create some multi-threading (Do not judge strictly, I'm a newbie) for userpage.php, to be created for multiple users, which are trying to login at the same time?
How should I protect the information (code side), for being hard to read? (For example Facebook pages source-code. because i don't want some "bad guys" to view my sources) and other things.
How can I make some users to see what the others can't ? For example userpage.php shows different links and information for different users and all the information for me .
How can i prevent membership.php from being viewed?(Is there some other way than using header?)
How can i prevent my require and require_once from being viewd at the login.php and userpage.php ?
1.) When I'm creating a redirection from login.php to userpage.php, how should i redirect users data? (Should I use global arrays (like $_SESSION) to transfer the info or I should connect the db again from the user page?)
You need to have a connection to the db everytime you want to get the user's data. You can create a session to store a unique attribute for the user, like $_SESSION['id'], when the user is successfully logged in, and you can use that value on any page to query the db and get the necessary user data.
2.) Should I create some multi-threading (Do not judge strictly, I'm a newbie) for userpage.php, to be created for multiple users, which are trying to login at the same time?
No, you don't need to worry about users connecting at the same time. The server can handle this. When you have a million users or so, you can start considering this. (Although, even then I'm not too sure. Unfortunately I've never had that problem ;) )
3.) How should I protect the information (code side), for being hard to read? (For example Facebook pages source-code. because i don't want some "bad guys" to view my sources) and other things.
You cannot prevent anyone from seeing your markup and styles, that is, your html and css, or any client side scripting, like javascript. However, your php is server side and not displayed in the source. The 'bad guys' will not be able to view source to see your db connections, php logic, etc.
4.) How can I make some users to see what the others can't ? For example userpage.php shows different links and information for different users and all the information for me .
There are different approaches to take. The simplest is probably to store the user's 'permission level' in the db, and then check that every time you load content. For example,
if ($user['permission']==1)
// Show something
elseif ($user['permission']==2)
// show something else
5.) How can i prevent membership.php from being viewed?(Is there some other way than using header?)
The easiest way to do this is by checking to see if there is an active session, and if not, redirect:
if (!isset($_SESSION['id']))
header("Location: login.php");
6.) How can i prevent my require and require_once from being viewed at the login.php and userpage.php ?
Not too sure what you mean by this, but consider this: require and require_once are the exact same as including the code directly in the file. If you are referring to them being viewed directly by the client by hitting 'view source', don't worry - see answer to question 3.
Note:
These answers are simplified, and there are plenty of other complications to consider. Some of this stuff may not make sense, but I wouldn't sweat it too much. I would recommend starting small - find a decent tutorial or two on how to create a simple user database, a registration, and login page, and start there. No answers you get here will substitute research, practice, and trial and error. Start small, and things will quickly become clearer as you progress.
Save the users state in a cookie or in a session. Note that you need the session_start() the userpage.php page as well as the rest of the page were the user is connected.
More info on http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
See the above link.
No one can read PHP code because it is server side and not client side. So your code is secure already from its own structure.
Let users have different level from the swl-database. If a user got auth 1 they see some links, if they got user auth 2 they see other things.
See page from answer 1
See page from answer 1
Considering your stated fact that you are newbie,I will also assume that the login system is more of practice thing and not a real world app.
Now to answer your queries point-wise.
Storing data in SESSION variables is alright.However,do not store too many data in SESSIONS.I would suggest just store the userid for the user and use that to gather and display info in the userpage.php. As the app gets bigger,you will definitely need to make connections in each individual page.
Use SESSION and COOKIE combination to create multiple user logins. However,Refrain from trying to implement/allow same browser multiple logging-in.SECURITY ISSUE.
PHP source code is anyways not readable from client-side.Regarding javascript & css-u can maybe minify it.But that would still not make it client-safe.
There are many ways to implement this.Maybe have a $_SESSION['admin'] =true when a admin logs-in and use it to display/hide info on userpage.php.
Same as NEXT
What it is that u want to hide?If its HTML/JS ,u dont't have much choice. One solution may be to use if-else in ur php code and restrict display of code present in header.php and the pages included via require and require_once.
This is a very basic guide.Your strategies may vary depending on the complexity of your application and also if/when you start using framweorks . Happy logging-in !!
ADDITIONS wrt to application structure.
Considering that your end product would be a system that allows a user to register and login/logout,i would suggest a following structure to begin with.
Structure-
index.php
|--action
|---register.php
|---logged_in_user_landing.php
index.php-- This is main page and used to redirect to individual pages based on actions.
check if SESSION is set.
If yes,include action/logged_in_user_landing.php else include action/register.php.
As actions increase,you can add if-else and include more pages accordingly.
In register.php,u have the form for login. On submit, redirect to index.php (via form action).
establish db connection in index page and check username-password combination.If correct,set the SESSION for that user and include the 'action/logged_in_user_landing.php'.
Have a unique identifier sent along when redirecting from each individual page,So that u can identify what to do in index.php.
This is a very simple architecture that should get u started.Its kind of a controller based architecture and will help you in the future when u go into MVC architectures.

Secure AJAX request to URI

I know there have been lots of question about AJAX security. I've searched and read but am still unclear as to what the best approach is.
I have a very specific senario:
I have an application that is build on top a PHP MVC framework. I've turned presentation elements such as a "navigation menu" modular. The navigation menu module has a controller (sever side). The controller uses a model to retrieving data from the database and then it responds with a php echo of the data. I can make the http request to the controller using AJAX because the controller is routed to by a URI. I believe this is call a RESTful API. When the user clicks a link in the navigation menu a static content area is update with the data that was retrieved from the AJAX request. Lets say that I Make a different action in the same controller that is capable of writing data to the database. Having a publicly available URI that allows writing to the database is obviously bad. How does one secure the URI interface so that AJAX can retrieve and write data, but those individuals with malicious intent can do harm?
You must treat an ajax request as you treat a get request or post request.
In other words never trust the user. You have server side control, ajax is client side so never trust "CLIENT SIDE" that makes a request(check the data, if data is ok then return a response if not return another response).
Controller is able to write to database:
There is no true way to secure an public URI interface so that it is only able to be accessed by the part of your application that exists on the client side. The idea is then to not make the interface so public, meaning it cannot be accessed by everyone! If a URI were to point to a “controller” (MVC architecture) and in turn the controller has access to manipulate a critical database, you best make it so the client who sends the request to the controller must “Authenticate”. This concept is true whether the http requests are coming from a web form or Ajax. Typically before Authentication credentials are transmitted using https (http + SSL) to keep a “Man In The Middle” from seeing the credentials.
Controller is able to read from the database:
When a read request is made you can simply return the data, or if its sensitive data require an authenticated client.
The “Navigation menu module” should only be edited by an administrator, so authentication is a must. However, any web surfer who views a page containing the module should not have to authenticate to use the navigation, that would be silly.
The main rule is to validate all inputs - check all data coming in and clear from unwanted chars.
Also, it all depends if You allow user change Your DB without loging in or not. Logged users are easier to verify and You always can put on serwer - side checking scripts - if current user is allowed to do this operation.
Things are harder when You allow annonymous user to write to Your DB. Then, its good to operate mainly on ID`s and if You allow user to insert data from inputs - filter all from unwanted things. The good way of doing it is to create whitelists of chars You approve and cut everything else.
You have to remember, that Ajax is nothing else but sending POST request to url - and You should do the same protection as with standard forms. Also good practice is to add a token to Your send data - wich You can verify by server side.

Fetching and Storing third-party site via PHP and curl on server-side

For some reason I need to process PHP behind the scenes but not using AJAX (I know that might sound silly to you). I need this since I am getting the content dynamically through another page loading.
By using PHP's curl functions I can get the login page of a website inside my 1.php file. But then I use javascript to set form values and hit login and it takes me to the site url (not already localhost/1.php). So the question is: I need to somehow store the content of the page that I am redirected and retrieve it .
The impression i got was that, you have a resource intensive process, which would perform some action in background , while user still interacts whit the page.
I actually would make more sense to do this with some sort of service ( as shell script or standalone application ), but it is possible to do with php: you would need to fork [1] [2] the process. Just don' forget to check, if one such process is already running on the system.
It actually works pretty well in combination with XHR (also know as AJAX by marketing department), because you can kick off the process with a request, and then repeatedly check the status .. and then collect the data, when status is "done".
Since we're all taking stabs in the dark, here's what I think you're trying to do (let me know if I'm way off):
You have a site (let's call it userfriendly.org) and you are trying to add an interface of some kind to another site (we'lll call this site mean-corp.com). Essentially, when you load the page, you use curl to fetch some of the data from mean-corp.com so that your users can login and get some info but without having to deal with their site (maybe it's ugly, maybe it just fits really well into your site, whatever).
You are able to get to the site okay to get whatever initial data you need, but when you try to pass in the user login and password to actually get their info, it's redirecting back to the login URL for the site.
Long story short, you are trying to make a front-to-back web service for another site, but you're running into hiccups with redirects and whatnot?
Am I totally off? If not, I've made similar attempts in the past for my own nobel reasons,and I could pass along some tips as I'm sure others can.
But if I'm totally off, sorry for the distraction.

proper way to craft an ajax call with php and auth

From a security standpoint, can someone give me a step-by-step (but very simple) path to securing an ajax call when logged in to PHP?
Example:
on the php page, there is a session id given to the logged in user.
the session id is placed dynamically into the javascript before pushing the page to the client.
the client clicks a "submit" button which sends the data (including the session id) back to the php processing page.
the php processing page confirms the session id, performs the task, and sends back data
I'm stuck on how (and whether) the session data should be secured before sending it through an ajax request. I'm not building a bank here, but i'm concerned about so many ajax calls going to "open-ended" php pages that can just accept requests from anywhere (given that sources can be spoofed).
PHP can get the session data without you having to send a session ID via javascript. Just use the $_SESSION variable. If you want to check if a session exists you can just do
if(isset($_SESSION['some_val'))
//do work son.
You'll need to use JavaScript to asynchronously pass user input back to the server, but not to keep track of a session.
Don't send your session data with javascript.
You don't need to (in most cases).
Just post the data with javascript and let PHP retrieve the session data from... the session.
Depends on how you setup your session data.
One simple example would be you have a session called username.
When PHP gets the request from javascript you can do: $_SESSION['username'] to retrieve the sessiondata.
This is a very simple example just to show how it can be done.
As noted above, you don't need to send any session identifiers out with your javascript, to the server an AJAX request is the same as any other request and it will know your session just fine. So basically, just don't worry about it, it's already taken care of.
It's another part of your question that worries me.
i'm concerned about so many ajax calls going to "open-ended" php pages that can just accept requests from anywhere
It worries me too; you shouldn't have any "open-ended" PHP pages hanging around at all. Every public .php script should have authentication and authorisation done. The easiest and most maintainable way to achieve this, IMHO, is to have a single controller script (e.g. index.php) that does authentication and authorisation then sends the request to an appropriate controller. Aside from this controller, all other scripts should be outside the document root so that they cannot be called directly.
This means that you only ever have to worry about authentication and authorisation in one place; if you need to change it, it only changes in one place. It means you don't need to worry about accidentally leaving some executable stuff in some library PHP file that's not meant to be called directly. It means you don't need to shag around with mod_rewrite rules trying to protect .php files that shouldn't be in the doc root at all.

Categories