Different page for different users using PHP - php

I want to know how I would get user 'McKenzie' to see his own unique page that he can manipulate and 'Wendy' to see her own page when she logs in.
I've created the login and the pages, connected them to a MySQL database given them ID's etc, so I can do all of this and I know about sessions etc. ;)
So can someone tell me how I would do this, would I have to make different pages for each separate user? I'm thinking something along the lines of
REGISTER PAGE:
Store data in database, get user ID and use "?pageid=1" to then take the user to the id based page.
But I'm not sure how I would make each page without making them manually, as you can imagine making a new page for each separate user would be a pain... and very inefficient. Any ideas?
And please show me an example with code, it would be GREATLY appreciated! Thank you all in advance!

My answer is assuming you want to create fully customizable user data with the added possibility of sharing the page between users (like a profile page). With that out of the way you can do this by creating one php page that searches the MySQL table by $_GET or $_POST data.
Ill expand this answer in to a couple of steps...
SQL Tables
The first thing you will need is your MySQL set-up, ill assume you have a basic set-up already done but I will go ahead and create a simple one.
The basic set-up will be the login data and the custom user data, you can view my set-up here.
php user page
The simplest way would be to get the requested user from the $_GET data. So to do this we would simply get the data and request the users information:
$requested_user = $_GET['id'];
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'root', 'MyPassword');
try {
$stmt = $db->prepare("SELECT * FROM c_userpage WHERE id = ?");
$stmt->execute(array($requested_user));
$mydata = $stmt->fetch();
} catch (Exception $e) {
//error with mysql
die();
}
Now we can simply add the users data to the page!
echo "Hello! my name is {$mydata['username']}!\n";
echo "About Me: {$mydata['custom_data']}";
Sending users to their page
We can simply just use www.page.com/user.php?id=2 And this will request the data for the user with id=2
Extras
If you want to keep user pages private you can simply request the id with $_POST or $_SESSION and then check if the user is logged in!
Full code for user.php
Full code for user.php w/ private page

Here's an example of what you could do:
<?php
if (!isset($_SESSION['user_id'])) && (!isset($_SESSION['user_name'])) {
echo '<p class="login">log in</p>';
//exit();
}
else {
$user_name = $_SESSION['user_name'];
echo('<p class="login">' . $user_name .'\'s page | Log out</p>');
}
?>
There's a lot more you could add, but this is just to generate information on whether they were logged in.. If the $_SESSION['user_id'] is set, you can then generate code based on that information. (note, you would need to create the $user_name or whatever variable, likely from an sql query)

Related

PHP SESSION Conflicts

I have this in my $_SESSION setting script:
<?php
//----------------------// Start session----------------------
if(!isset($_SESSION))
{
session_start();
}
//------------------------------------------------------------
//------------------// Check if Username $_SESSION is set------------------------------------------
if (!$_SESSION['Username']) { // If not current User
header("Location: ./logout.php"); // Session destroy file that leads to session logout landing page
exit();
}
//------------------------------------------------------------
?>
Now, what I basically do is just check if Username SESSION is set. But, I have come to notice something strange while putting another user through:
If we click the same link at the same time and arrive on the landing page same time, I noticed I can see my Username displayed as his Username and his personal data like email and phone replaced mine in my very own PC! This is really strange to me as we do not even live in the same country or even share same PC.
So, it is obvious I have not secured my SESSION and I have used a lame approach without thinking about security and this can be abused with SESSIONS hijacked.
How do I resolve this conflict? How do I restrict each logged in user to a particular session without conflicts if two or more users access the same resource at the very same time? I need help. I can't sleep since I found this.
After reading your responses, I will now show a snippet of the functions.php file which outputs Use data from DB.
First, I get the UserName value from session using:
$UserName = $_SESSION['Username'];
With this value, I query DB to get more user details:
//------------Get User Info -- All user column
$Get_User_Info = mysqli_query($conn,"SELECT * FROM customers WHERE User='$UserName'");
/************************************************************/
/************************************************************/
$Get_User_Info_row = mysqli_fetch_array($Get_User_Info,MYSQLI_ASSOC);
/************************************************************/
//---- Now list all user rows
$GLOBALS['Skype'] = $Get_User_Info_row['Skype'];
$GLOBALS['Jabber'] = $Get_User_Info_row['Jabber'];
$GLOBALS['ICQ'] = $Get_User_Info_row['ICQ'];
$GLOBALS['Join_Date'] = $Get_User_Info_row['Join_Date'];
$GLOBALS['Join_Date_Time'] = $Get_User_Info_row['Join_Date_Time'];
$GLOBALS['Balance'] = number_format($Get_User_Info_row['Balance'],2);
The above is what is contained in the functions.php which I require with each page I need protected.
As you can see, I barely see where I have done too much wrong there.

How does a PHP session-enabled page know a user logged in from another page?

I recently learned how to make a registration form and a login form, and I've done my first work with sessions. Yet I'm getting more confused every day.
Let's start with my login page at mysite/admin/login/index.php. The following code is near the top of the page:
<?php session_start(); ?>
A form on the page sends the person logging in to login-submit.php. The same session code is near the top of that page:
<?php session_start(); ?>
I also have a database-driven quiz at mysite/test/gw-intro1. After you select all the questions and click the Submit button, you're forwarded to mysite/test/grade.php, where you can see your score. If you're logged in, your username and score should also be inserted in the database.
But how are the pages in the test section (mysite/test) supposed to know I logged in at a different section (mysite/admin)? Do I need to put session_start() at the top of every page on my site?
In fact, my test page did somehow "know" if a user was logged in, though I haven't been able to get the username into the database, just the test scores. But something went wrong, and the test doesn't know when I'm logged in now.
My session_start() code also triggers endless error messages, though I'd better save that for another post. Right now, I'd just like to know how to make the pages at mysite/test/gw-intro-1 and mysite/grade.php "aware" that the person selecting answers is logged in.
As an addendum to my comments, on the login page. Some of this uses pretend methods that you'll need to swap out yourself, but it gives the general idea.
session_start();
if ($_POST)
{
// The username supplied by the user
$username = $_POST['username'];
$password = $_POST['password'];
// Get password hash from database based on $username
$passwordHash = $database->getHash($username);
$passwordHashMatch = $hasher->run($password) === $passwordHash;
if ($passwordHashMatch)
{
$_SESSION['logged_in_user'] = $username;
// Redirect to home page
}
// Password was wrong
// Redirect to login.php?wrong=1 so it can render a message
}
All of your pages can check for $_SESSION['logged_in_user'] (e.g. in a navbar or menu) so that your signed in/out status can be rendered.

Stricter session control methods

In a Nutshell: this is a question, about improving the security of sessions in-order to prevent them from session fixation/hijacking
I have a user registration form, login and article posting form.
Now, when user registers, logs in or posts somethings there is always thank you page different for all three. More specifically 'thankyou.php'
The problem is users can access the static thank you page, by typing the url 'site.com/thanks.php'
I don't want this to happen, I want those page to show up only when a specific tasks have been arbitrated.
So, I thought about about making sql query's to see if users has posts for the last 5 seconds and show thank you page, or show 404 but, It's seems unnecessary to create a query just for than one. And, Since I think PHP is flexible if you guys give me an idea I could probable learn something new on the way, on how to achieve this.
You can restrict the page with the $_SERVER['HTTP_REFERER'] (enter link description here) viewing from they are coming to thankyou.php page.
You Can Achieve this by settling the session like this:
if($_SESSION['registration']=="registration")
{
echo "Thank you for registering";
unset($_SESSION['registration']);
}
elsif($_SESSION['login']=="login")
{
echo "Thank you for login";
unset($_SESSION['login']);
}
elseif($_SESSION['post']=="post")
{
echo "Thank you for Post";
unset($_SESSION['post']);
}
else
{
echo "session is not set,something is wrong";
}
So set the values in session on html page like.
$_SESSION['login']="login";
//like for others also

Force user to logout session PHP

I can't seem to find a straightforward answer to this question. Is there a way in which I can force a logged in user to logout? My login system essentially just relies on a session containing the user's unique ID (which is stored in a mysql database). So essentially just...
if (isset($_SESSION['user_id'])) {
echo "You're logged in!";
} else {
echo "You need to login!";
}
But let's say I want to ban this user, well I can change their status to banned in my database but this won't do anything until the user logs out and attempts to log back in... So, how do I force this user to logout? Preferably without checking every single time they view a page whether or not their status has been switched to "banned" because that seems like unnecessary stress on my server. Any help is appreciated, thank you.
Either you need to check every time they load a page, or possibly look at an Ajax call at set intervals to check their status from the DB.
Then you can use session_destroy(); to end their session. This will destroy their entire session.
Otherwise you can use unset($_SESSION['user_id']); to unset a single session variable
Preferably without checking every single time they view a page whether or not their status has been switched to "banned" because that seems like unnecessary stress on my server.
Loading the user from the database on every page load, rather than storing a copy of the user in the session, is a perfectly reasonable solution. It also prevents the user from getting out of sync with the copy in the database (so that, for instance, you can change a user's properties or permissions without them having to log out and back in).
Try to put this on every page...
if (isset($_SESSION['user_id'])) {
$sql = "SELECT from tbl where status='banned' and user_id=$_SESSION['user_id'] ";
$query = mysql_query($sql);
if(!empty(mysql_num_rows($query))){ // found the banned user
//redirect to logout or
//session_destroy();
}
} else {
echo "You need to login!";
}
if the user is still logged in... check if his/her status is banned or not... if banned.. then logout
You can unset it.
unset($_SESSION['user_id'])
You could use Custom Session Handlers this way you have full control where and how the session data is stored on the server.
So you could store the session data for a particular user in a file called <user_id>.session for example. Then, to logout the user, just delete that file.
Ajax calls in an interval will put extra load on server. If you want real-time response to your actions(e.g. the user will be signed out right when you ban them from your system backend), then you should look into something like Server Push.
The idea is to keep a tunnel open from Server to Browser whenever a user is browsing your website, so that you can communicate with them from server-side too. If you want them to be banned, push a logout request and the process that in your page(i.e. force logout by unsetting session).
This worked for me am using pHP 5.4
include 'connect.php';
session_start();
if(session_destroy())
{
header("Location: login.php");
}
You can use session_save_path() to find the path where PHP saves the session files, and then delete them using unlink().
Once you delete the session file stored in the sever, the client side PHPSESSID cookie will no longer be valid for authentication and the user will be automatically be logger out of your application.
Please be very careful while using this approach, if the path in question turns out to be the global /tmp directory! There's bound to be other processes other than PHP storing temporary data there. If PHP has its own directory set aside for session data it should be fairly safe though.
There is a few ways to do this the best in my opinion based on security is:
NOTE: THIS IS REALLY ROUGH.... I know the syntax is wrong, its just for you to get an idea.
$con = mysql_connect("localhost","sampleuser","samplepass");
if (!$con)
{
$error = "Could not connect to server";
}
mysql_select_db("sampledb", $con);
$result = mysql_query("SELECT * FROM `sampletable` WHERE `username`='".$_SESSION['user_id']."'");
$userdeets = mysql_fetch_array($result);
if($_SESSION['sessionvalue'] != $userdeets['sessionvalue'])
{
session_destroy();
Header('Location: logout.php');
}
else
{
$result2 = mysql_query("UPDATE `sessionvalue` WHERE `username`='".$_SESSION['user_id']."' SET `sessionvalue` = RANDOMVALUE''");
$sesval = mysql_fetch_array($result2);
$_SESSION['sessionvalue'] = $seshval
}
Now I know thats not the very code but in essence what you need to do to be secure and have this ability is:
Everytime a page load check a Session value matches a value in the DB.
Every time a page loads set a new session value based on a random generated DB value. you will need to store the username in a session as well.
if the Session ID's do not match then you destroy the session and redirect them.
if it does match you make the new session ID.
if you want to ban a user you can set their sessionvalue in the DB to a value like "BANNED". this value will not allow them to log in either. this way you can control user through a simple web form and you can also generate list of banned users very easily etc etc. I wish I had more time to explain it I hope this helps.

how to clone mysql_result

I will explain my problem
From index.php I POST my login and in login.php I store session details (like name) e.g.:
$_SESSION['name'] = mysql_result($res,0,"name");
then I am forwarded back to index.php.
Here I want to show logged-in-user's name:
echo $_SESSION['name']
and also all names from the DB:
$result=mysql_query($query);
for ($i=0; $i<mysql_num_rows($result); $i++) {
$row = mysql_fetch_assoc($result);
$name =$row['name'];
echo $name;
}
And here comes the problem: after I log in, everything (both user's name and all names) is displayed correctly. But when I refresh the page echo $_SESSION['name'] shows the last name in the databse == $name instead of the one that was
So I guess I need to clone mysql_result($res,0,"name"); when storing into $_SESSION['name']
Thank you very much
EDIT
the only thing i store in session is the login name. And when the person is logged-in he can see all people from database.
If you are looking to clone an object then you can try the following
$object2 = clone $object1;
From the php documentation it seems that some objects do not support cloning, so if this is the case then you could try the following (again, from comment in php documentation) to do a deep copy
protected function deepCopy($inputObject) {
return unserialize(serialize($inputObject));
}
There are some other good points made in the comments of the documentation page which can be found here http://php.net/manual/en/language.oop5.cloning.php
Best regards
In my opinion you are better off not storing all the other names in the session. Being a database app with logins I assume other people can use and update the data, meaning that any time they change something, your session-saved data will be obsolete on refresh.
Try just letting them login and set their on credentials, then when they get back to index check that they are logged in and fetch the names at that point. That way you don't have to worry about cloning the fetch AND you have the most up to date info.

Categories