Can session variables be used to separate landing pages geographically? - php

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.

Related

PHP - Sessions and Controllers

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!

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.

Generate pages on the fly with PHP

I'm new to PHP and I'm curious as to how you generate pages on the fly?
I have a table of users that I'm pulling from my DB and displaying on my homepage and that I know I can pass their user ID as a POST variable to 'mysite.com/profilepage.php' and then have a query on that page that would pull all relevant information for that ID, but say I wanted the page to be 'mysite.com/user-profiles/john-doe.php' ?
Would this be done with a .htaccess file? Any help is greatly appreciated!
If you must have the page be called mysite.com/user-profiles/john-doe.php, you can use URL rewriting as mellamokb mentioned in the comment to change the URL to that.
But as far as PHP is concerned, the way to do this is to create a PHP page (I'm going to suggest user-profiles.php), and then pass usernames to it with either GET or POST. Assuming that you're only reading and that the information in question is public, GET seems fine and it's easier to explain here.
You access the relevant page (generated "on the fly" by PHP) by pointing your browser to user-profiles.php?username=John-Doe and including code like this in user-profiles.php:
if ( isset($_GET['username']) )
{
$username = $_GET['username'];
// you now know the passed username
}
else
{
// some kind of error handling for when there is no username
}
You now know you have the relevant username within your PHP file, and can use it to create the page as you want it. You can also use URL rewriting to change user-profile.php?username=John-Doe to user-profiles/John-Doe if you like.
WARNING: Do not use $_GET if the page in question is either going to be modifying the database in any way, or if it's going to be getting private information from the database. It is not in any way secure. Please read up on PHP security before creating pages that do either of those things.
If you are new to PHP and havent looked at any frameworks, have a look at the agiletoolkit. It does some neat integration between jquery and php which will give you a nice look and feel to your pages. It also encourages you to use ModelViewController (MVC) to segregate the parts of your code that are for database access and functionality from those which are purely for web page layout.
The options for URL rewriting mentioned above are the same but when a user is logged in, you have access to the user information from $this->api->auth('xxx') where xxx is the column in the users table.
The framework takes a little bit of learning but so does PHP and it's easy to get into very bad habits writing PHP code which means as the websites get bigger, you will find it harder to maintain your code.

Magento and Best Way to Sync Sessions across stores

I am syncing sessions between two different domains for Magento using a token passing technique with a remote iframe or img. I am about to implement it into Magento and was looking for some pointers.
I will have to do two things:
Every 5 mins, output an iframe or img with a remote SRC attribute for the second domain.
Q. Where is the best place to implement this? In the past I did storewide actions by overriding the renderLayout() method in Magento. Should I just do it by appended a block to the end of the page load? If I use a block, is it still keeping MVC?
I need to sync the session on the other domain when the script is called. I need to set the same cookie that Magento would set, that links to that session for the user.
Thinking about this, I think I am going to have to load Mage::app or whatever the call is that loads the Magento environment.
Q. Is there a lighter way of doing this?
Just for better understanding of what I am doing, here is a quick description of the flow.
User goes to Site A. If its time to sync the sessions, an IMG or IFRAME is outputted with SRC pointing to site-b.com/sessionSyncer?token=SHA1TOKEN
sessinSyncer validates the token and if so, creates a session and sends the cookie to the browser for the session. This should happen in a Magento manner
I am aware that Magento has the ability to pass session through the URL and generates the links to do so, but this is inadequate because the user must only switch sites using those special urls, plus the URL becomes ugly.
Thanks in advance!
Overriding renderLayout is overkill. Instead create a block that outputs your img tag and include it in the base theme, perhaps for the area before_body_end, that will safely place it on all pages.
Inventing your own token is also overkill since Magento is using the PHP session identifier and places it automatically for foreign domains. Your custom block might generate the URL with this:
$this->getUrl('OTHER/STORE/PATH', array('_store' => 'YOUR_STORE_CODE'))
If you think your script is going to need Mage::app() then you might as well use a controller which is a similar effort. On encountering a SID value the session will be updated behind the scenes, cookies set etc.
It using an iframe it doesn't need to output anything and if a small image can be static like this:
print "GIF89a\1\0\1\0\x80\0\0\xff\xff\xff\xff\xff\xff!\xf9\4\1\n\0\1\0,\0\0\0\0\1\0\1\0\0\2\2L\1\0;";
P.S.
When creating the URL of the foreign store without an SID use the _nosid parameter to force a clean URL.
Store sessions in DB and replicate database tables or entire databases it's much easier. You can configure that in your local.xml
<session_save><![CDATA[db]]></session_save>

Categories