PHP - Sessions and Controllers - php

If I may ask, I would like to ask about "sessions", "controllers" and "session controllers".
So let's start at the beginning: I have heard of MVC and tried it in C# (VS), but while I could grasp the concept, I didn't understand implementation. It all seemed so strange. Now in PHP the concept became even more clear.
Now I would like to ask whether or not a "session controller" is like a controller for the session. It seems straight forward, in wording, but maybe I have it wrong. Although I would preferably not implement MVC in the current project I am working on, yet I would like to perform some sort of "controller" that manages groupings of session content.
Although I would like to ask if it is possible to have the following script in your application:
//path: c:/xampp/htdocs/starvationproject/root/index.php
<?php
include '../session/controller.php';
?>
<!DOCTYPE..........
//path: c:/xampp/htdocs/starvationproject/session/controller.php
//I have not coded this script yet, but it will perform tasks like
//setting the user, session variables etc.
<?php
session_start();
?>
// An important question here. If I include this file in the previous, can
// I safely say that the session has been started in index because of the
// include, or do you have to manually type out session_start();
// in each page?
Lastly, I would like to ask if this file structure is correct or not, or rather if it is standard or nor, or whatever:
Folder Structure
, where "multi" (as you can see) has a page named after each folder in "partial", where what I did is, based on the get request of the page in "multi", I included a partial, i.e:
if ($_GET['q'] == 'Add') {
include '../partial/stockAct/add.php';
}
else if ($_GET['q'] == 'Update') {
include '../partial/stockAct/update.php';
}
And then those "partial" files only held like a section with a form or something like that. As in the tv stays where it is, I'm just switching channels.

I'll do my best to help.
First let's talk about sessions. Sessions are used by the server to 'store' temporary information throughout a single browser session (this can be modified slightly but we won't go down that rabbit hole). In your specific situation, having a session Controller is unnecessary because the server handles all of the session logic. For example, on the login page, when the login form is pushed to a login script, you can simple add the user id to the session at that point and then no matter which page you move to, the user id will still remain in the session. The benefit is of course that you only need to set the session once and only access it when you require. This is where an MVC shines though as you can easily define a routing where all pages of a specific authentication type first go through to ensure the user is logged in/ has access to the page content.
For folder structure, I'd recommend some immediate changes. Firstly, I'm sure you are familiar with the talk of "public / public_html' folders? These folders are specifically name to represent the location where you put ALL of the files a front-end user would "see". This includes, front-end js files, css/ styles and in your case php PAGES. This folder SHOULD NOT however contain any back-end logic like database connections or verification scripts as this would give the front-end access to potentially sensitive information (ie. database login information which I am sure is found in your DB_Conn.php file).
To fix this I propose the following (assuming you would like to avoid the "MVC" structure).
ROOT
->Public //this is your WEB ROOT/ DOCUMENT ROOT folder
->Pages
->Style
->Scripts
->Assets
->Images
->etc.
->DB
->Connections
->db1_conn.php
->db2_conn.php
->Models
->User.php
->Posts.php
->Verification
->login.php
->etc
I'd like to finish with some advice as I used to build sites this way some time ago. MVCs take some time to learn, but their biggest advantage is the organization and flow of information. As a bonus, their process covers common issues like verification, security and data sanitization. Don't let them scare you, for the time it takes to learn then, they are well worth the capability you will gain from them.
I'd highly recommend Laravel. Version 5.5 just came out and oh boy is it a thing of beauty. Hope I could help at least a little!

Related

Can session variables be used to separate landing pages geographically?

This is probably a dumb question. I have a Web site that uses php and html with a bit of Javascript. I am trying to set it up so there are multiple landing pages. I think it would work if all the remaining .php files on the site were kept identical but there were separate index_a.php, index_b.php files, etc. The only problem is when the user clicks "Home" they of course get the root index.php. Is there a way to store the name (or some other indication) of what the user's landing page was for that session (using PHP session variables or I don't know what) and have the user directed to that page again when they click Home ?
Any help would be much appreciated (keeping in my mind I am a relative newby and any solution would need to be pretty simple and safe to load on a server). Any straightforward way way to do this ? It must be something that is fairly commonly required.
Short answer: yes
Smart answer: use a (mvc) framework of some kind which implements views and routes everything through a front controller.
Quick and dirty answer:
// anywhere
session_start();
$_SESSION['landing_page'] = 'landing-2.html';
// in your index.php
session_start();
include $_SESSION['landing_page'];
Note: if you use the code above, be sure the torn of the security gods will fall upon you.

PHP include in middle of file

is this considered to be bad programming practice? I have includes in the beginning and end of my file in order to make templates.
so it is like this
beginning.php
<html>
some stuff
end.php
some stuff
</html>
user accessed files
include beginning.php
some stuff
include end.php
No it's perfectly fine. You can include files in places wherever you need to.
You can even use conditional statements to include specific php files as opposed to others. For example, your index page can have a conditional statement that checks to see if the user is logged in. If the user is not logged in, include a php file with the login form. If the user is logged in, include a php file that displays the user's profile information instead.
The only thing you'd want to worry about is making your pages too spaghettied by trivially splitting things into different files if they don't need to be. But all in all, you're good to go.
well, consider a designer point of view. will he/you find it difficult to make design changes to the file without affecting the server side implementation?
Using PHP this way is popular in design patterns such as the MVC, so you should be fine doing it. I wouldn't recommend it unless you have a clear structure to your projects because files can quickly become unorganised and messy.
Remember that PHP is generally finished executing before any HTML is outputted, so as long as it is logical to include PHP as-and-when, it should be fine.

have different static url in dynamic page

I have a website where each person has his personal profile. I would like to have static URL like mywebsite/user1, mywebsite/user2, but actually I would remain in the same page and change the content dynamically. A reason is that when I open the site I ask to a database some data, and I don't want to ask it each time I change page.
I don't like url like mywebsite?user=1
Is there a solution?
Thank you
[EDIT better explenation]
I have a dynamic page that shows the user profile of my website. So the URL is something like http://mywebsite.me?user=2
but i would like to have a static link, like
http://mywebsite.me/user2name
Why I want this? Because it's easy to remember and write, and because i can change dynamically the content of the page, without asking each time data to my database (i need some shared info in all the pages. info are the same for all the pages)
Yes there are solutions to your problem!
The first solution is server dependend. I am a little unsure how this works on an IIS server but it's quiet simple in Apache. Apache can take directives from a file called .htaccess. The .htaccess file needs to be in the same folder as your active script to work. It also needs the directive AllowOverride All and the module mod_rewrite loaded in the main server configuration. If you have all this set up you need to edit your .htaccess file to contain the following
RewriteEngine on
RewriteRule ^mywebsite/([^/\.]+)/?$ index.php?user=$1 [L]
This will allow you to access mywebsite/index.php?user=12 with mywebsite/12.
A beginner guide to mod_rewrite.
You could also fake this with only PHP. It will not be as pretty as the previous example but it is doable. Also, take into concideration that you are working with user input so the data is to be concidered tainted. The user needs to access the script via mywebsite/index.php/user/12.
<?php
$request = $_SERVER['REQUEST_URI'];
$request = explode($request, '/'); // $request[0] will contain the name of the .php file
$user[$request[1]] = $request[2];
/* Do stuff with $user['user'] */
?>
These are the quickest way I know to acheive what you want.
First off, please familiarise yourself with the solution I have presented here: http://codeumbra.eu/how-to-make-a-blazing-fast-ajax-call-to-a-zend-framework-application
This does exactly what you propose: eliminates all the unnecessary database queries and executes only the one that's currently needed (in your case: fetch user data). If your application doesn't use Zend Framework, the principle remains the same regardless - you'll just have to open the database connection the way that is required by your application. Or just use PDO or whatever you're comfortable with.
Essentially, the method assumes you make an AJAX call to the site to fetch the data you want. It's easy in jQuery (example provided in the article mentioned above). You can replace the previous user's data with the requested one's using JavaScript as well on success (I hope you're familiar with AJAX; if not, please leave a comment and I will explain in more detail).
[EDIT]
Since you've explained in your edit that what you mean is URI rewriting, I can suggest implemensting a simple URI router. The basics behind how it works are described here: http://mingos.eu/2012/09/the-basics-of-uri-routing. You can make your router as complex or as simple as needed by your application.
The URL does not dictate whether or not you make a database call. Those are two separate issues. You typically set up your server so example.com/username is rewritten internally to example.com/user.php?id=username. You're still running PHP, the URL is just masking it. That's called pretty URLs, realized by URL rewriting.
If you want to avoid calling the database, cache your data. E.g. in the above user.php script, you generate a complete HTML page, then write it into a cache folder somewhere, then next time instead of generating the page again the script just outputs the contents of the already created page. Or you just cache the database data somewhere, but still generate the HTML anew every time.
You could write an actual HTML file to /username, so the web server will serve it directly without even bothering PHP. That's not typically what you want though, since it's hard to update/expire those files and you also typically want some dynamic content on there.
Select all from your database.
Then create file containing the scripts contents(index.php?user='s) for each one. set the file name to user_id/user_name you got from the SELECT statement.
This will create a page for each user in the present folder.
To avoid having to recreate 'static' pages, you could set a new column named say 'indexedyet' and change it to 1 on creating a file. You select only files which have this as 0. You could perform this via cronjob once a day or so.
This leaves you vulenderable to user data changes though, as they won't autmatically update. a tactic to use here is to update the static page on any editing.
Another, probably better (sorry not had enough coffee yet-) ideal would be to create a folder on a users registration. Make the index.php page tailored to them on registration and then anything like www.mysite.com/myuser will show their 'tailored version'. Again update the page on user updates.
I would be happy to provide examples depending on your approach.

PHP Sessions basics

Ok, i have one totaly noob question about php sessions:
I have 3 (and more) php pages, i need to protect them with login system and sessions. Now, i am including this to the top of every page:
session_name('somename');
session_start();
if(!$_SESSION['user_loggedIn']){
header("location: login.php");
}
if (isset($_SESSION["timeout"])) {
$inactive = 900;
$sessionTTL = time() - $_SESSION["timeout"];
if ($sessionTTL > $inactive) {
session_destroy();
header("location: login.php");
}
}
Question: is it correct to add something like include session.php; to top of every php file, ofc. session.php would include only code above.
You shouldn't need to handle the session timeout yourself, your webserver is almost certainly handling that for you already. All you should need to do is check to see if the session exists and make sure you have login info in that session.
Also, as far as "what's the right thing to do" -- if you require it at the top of every php file, remember to use "require_once" because there's no point in doing the same thing over and over if you include other files. Also, you may only need to do this on pages where you know you only want secured users, which isn't always every page of the site.
PHP is a programming language that is similar to JavaScript but allows for better functionality of the code to develop dynamic websites and apps. PHP stands for Hypertext Pre-Processor. In this tutorial, I will walk you through what a session is, how to declare session variables, and introduce you to a few functions that will allow you to get your session up and running in the way you need it to.
What Is a Session?
First, you may be asking yoursslef, “what is a session?” In this programming language, a session is “used to store and pass information from one page to another temporarily (until the user closes the website).” If you are familiar with cookies, sessions are a very similar topic. While cookies are only stored on the local computer and browser that you use, sessions get stored on your machine as well as on the server you’re using. Both of these collect information about the way you interact with the webpage to improve the experience for a user. To summarize the two of them, “data that is kept in cookies is solely kept on the client’s side, whereas the information kept in sessions is kept on both the client and server’s sides.” (The link to the article I found this can be found here).
The most common functions that you will use as you begin to learn PHP are the session_start() function, the die() function, and the session_destroy() function. These three functions allow you as the user to start specific tasks and then stop them whenever you want. The session start function will allow you to, of course, start a new session. The die() function will allow you to clear any session variables that you may have used during your session, and the session_destroy() function will end your session. Now, understanding what a session is, let’s discuss what a session variable is and how you can declare them.
What Are Session Variables?
Session variables make it possible to make sessions in PHP useful and functional. Which variables you use will be different depending on the project you’re working on, but in my project and database I used variables that helped me see the status of users on my database. I’ll share two examples (see screenshot below, lines 54-55). The two variables I declared here were “logged_in” and “username”. All session variables are declared with a unique syntax. The proper way to declare a session variable is as follows:
$_SESSION[“nameofvariable”] = “variable declaration”;
It is important that you declare your session variables in this syntax or you will not be able to have your sessions run properly. As a system administrator, these variables help me to see who is logged into the databases and making edits to tasks. In addition, the logged_in variable enables functionality of the database and webpage. If the user is not logged in, then the code knows to redirect the user to the login page. See the example below:
Screenshot 1:
I then used these variables to help me keep track of the state that my program and database were in to allow it to function properly.
Let’s Get To It: How to Set Up Your Sessions
Now that we understand more about what a session is and how session variables can help us accomplish our goal of a functioning program, let’s discuss the process as to how we can actually implement this. First off, go ahead and open up your IDE. I personally picked Visual Studio Code as it allows me to comfortably program with color codes, but you can pick whichever one you choose. In this example I will show you how I set up both of my sessions using a particular action that implemented my to-do list to my database. Although the code I will share will be specific to my project, the principles will remain the same for all PHP code.
In the screenshot at the end of this section I have some code I wrote at the top of an action file that ultimately ended up allowing a registered user on my webpage to sign into their to-do list. Because this was an element that required the database to be fully implemented, I knew that I had to use the PHP language. In this screenshot and in your code, you should start your code with the simple PHP starter code of:
<?php
That’s right! That is all you have to do. This allows your IDE to recognize what you will be coding in. Once it has this information you get to set up your session which, believe it or not is another easy step. In order to declare that you’re going to be starting your session all you need to do is declare the following code:
session_start();
In order to properly run your sessions, it is vital to know and understand that this HAS to be the first thing declared in your code document otherwise it will not function properly. Once this code has been declared then the computer knows to iterate through the code in your document until another function is called telling it to stop. Once your function is declared you have the chance to declare your session variables and any other information you need the computer to know. Here in screenshot 2 I have the visual example of me declaring my php language, starting my session, and declaring the variables that are unique to me that establish my connection from my to-do list to my database. This is my 2nd screenshot:
Screenshot 2:
From this example you can see from lines 1-16 of my action file. Everything that I did here is what was explained in this section.
Useful Tip:
Another function that allows you to properly manage your session is the die() function. I implemented this one in my file. It is a way for the script to be stopped while keeping your session open. This was useful to me because it was a way of letting my script know to stop and moving to the next portion of my instructions, which were found in another file. If you are coding a particular project that requires multiple actions, then this is a great function to keep in mind!
Destroying (Ending) a Session
The word “destroy” sounds pretty hardcore, but in PHP sessions destroy is just a word that means “end”. The syntax of this function within the session is the following:
session_destroy()
The destroy function will take any and all data that you used during your session and destroy it. However, it is important to note that it will NOT reset or delete any of the global variables that you may have declared during your coding. In order to start a session again you need to code your project to have the first function, start_session(), called again.
End Result
You may or may not be coding a database, but the steps that I listed above should be a place to allow you to learn the basic principles of what a session is, how to start one, declare variables, and end your session at the appropriate time. In my particular database project I was able to use sessions to allow users to login to a page, log out of their account, register a new user, to update actions included in the database, and more. Whatever your project may be, sessions have a great ability to adapt to the needs that you have as a coder. In the extremely rare event this tutorial didn’t answer every question that you have, I have also included a list of some additional links and videos that may help you answer any unanswered questions about sessions in the PHP language. Happy coding!
Additional Resources:
https://www.javatpoint.com/php-session
This website is a great resource for studying more about what a PHP session is and all basic information about what they do. This page also includes information on specific types of sessions, how to code them, how to implement them, and when they should be used.
https://www.tutorialspoint.com/What-is-the-difference-between-session-and-cookies
This is a great resource for understanding the differences between sessions and cookies, and for also seeing how they are similar. This website is comprehensive in how it compares the two features, even going into detail on their capacities, functions, data storage, and format.
https://code.tutsplus.com/tutorials/how-to-use-sessions-and-session-variables-in-php--cms-31839
This website does a deep dive more into what a session is and defines Session Variables for the PHP language. It goes into detail on how to start sessions and also talks about some common errors that may occur.
https://www.javatpoint.com/php-session
This link has outstanding information and further descriptions as to how to destroy, or end, a session. It also goes into further detail on what it will do to your project and code in addition to describing what it will not do.
https://www.youtube.com/watch?v=h6KID8n0zCU
This is a great video that describes sessions. I personally like to refer to it as “Sessions for Dummies”.

Redundancy in PHP? safer or unnecessary

I'm using the MVC model (I think thats what its called) and I have separated my site into smaller pages and includes.... Is it safer/better or worse (with no benefit) to check the same conditional twice?
For example, I have an accounts page that looks something like this:
// Must be logged in
if(isset($_SESSION['userID'])){
include('edit_user.php');
}
and then in my edit_user.php page I have something like this:
// Must be logged in
if(isset($_SESSION['userID'])){
if(isset($_POST['editUser'])){
//Validate the form
}
?>
<form>
// Display the form
</form>
<?php
} // End main IF
So pretty much I'm checking if the user id is set twice... I'm pretty mush doing the same thing with all my pages (that require users be logged in). Is that really necessary? My initial thought was to prevent unregistered users from accessing the edit_user.php form directly and doing things (I was also thinking of just redirecting if users do access the page directly). What do you guys think/suggest?
Edit
I dont think I explained myself too clearly... That was just an example... Here's a better example to better get across the reasons for my question:
...Account page
if(isset$_SESSION['userID'])){
include('edit_user.php');// edit user form
include('change_password.php');// change password form
include('change_pic.php');// change photo form
}
and from within each of my includes, again I'm asking for a SESSION['userID']... So, what do you guys suggest now?
Well, it is redundant, which violates the "Don't Repeat Yourself" (DRY) principle of design. If your edit_user.php file is publicly accessible, then you definitely need checks in there, so you could probably remove the other checks, as long as you're sure of the functionality.
It's arguable that your code is clearer with the checks in place, however, in the long run redundancy like that will lead to more maintenance hassles.
You shouldn't need to have the multiple checks in there. If all requests go through the controller, then you should only need to add the check in the controller. That is the point of the controller, to direct the request. The view outputs data. The model interacts with the database (and enforces business logic).
In many cases redundancy is beneficial, but in your example it's unnecessary. It also goes against the principle of DRY (Don't Repeat Yourself). The more you repeat the same code, the more time you waste (you also face the possibility of adding errors to your code due to repetition). You should be fine with the check solely in edit_user.php.
Since you're using MVC, here's what I suggest: Define some authentication functions that are globally accessible. Then, in your controller's constructor methods, use them to see if the user should be granted access to that section. If they're not authorized you can redirect them to another page, or display an error message, for example. Of course you can use a finer-grained methodology and place the calls to your authentication functions in the beginning of certain controller methods.
You should always validate input that comes in from outside your control, so every php script that can be accessed by a user should check.
Even if you don't expect it, if a user can see a link in the url to a page that is 10 forms deep in your site then they can still jump directly to it.
Joomla uses a nice method, which is to put this right at the top of each PHP file:
defined('_JEXEC') or die('Restricted access');
_JEXEC is defined in the main entry point. You could do something like:
if ( isset($_SESSION['userID']) ) {
define('LOGGED_IN', 1);
include('edit_user.php');
}
With this in edit_user.php and other files:
defined('LOGGED_IN') or die('You must be logged in.');

Categories