PHP - Question On User Session Handeling
is it necessary to store users session on db? if so please explain someone why?
and block multiple session login. say if im logged in and someone else tries to log into my id from some other place how would i stop that to happen? any idea and example would be appreciated. Similar TutorialsHello, i've got some shop script which has 2 payment modules which i'd like to use for something else, the payment modules only work if the user is logged in though, i tried to make them standalone scripts but that didn't work out too well. So now i decided to go another way and just let everyone have the same session so everyone will be using the same username&password automatically. the index file looks like this: Code: [Select] <?php include('./inc/config.php'); include('./inc/functions.php'); include('./lang/'.$language.'.lng'); $id = addslashes($_REQUEST["id"]); $user = addslashes($_REQUEST["username"]); $pass = addslashes($_REQUEST["password"]); $language = strtolower($language); if(empty($id)) $id =1; $file = mysql_query('SELECT * FROM navi_'.$language.' WHERE id="'.$id.'"'); if(mysql_num_rows($file)>0) $file = mysql_fetch_array($file); else $file = mysql_fetch_array(mysql_query('SELECT * FROM navi_'.$language.' WHERE id="404"')); if(!empty($user) AND !empty($pass)) {$query = mysql_query('SELECT * FROM users WHERE username="'.$user.'" AND pass="'.md6($pass).'"'); if(mysql_num_rows($query) == 1) {$_SESSION[$session_prefix."user"] = ucfirst($user); echo'<meta http-equiv="refresh" content="0; url=index.php?id=8">';} else $error = 'Username oder Passwort ist falsch.';} include('./designe/'.$designe.'/head.tpl'); include('./designe/'.$designe.'/navi.php'); include('./designe/'.$designe.'/middle.tpl'); if(file_exists('./pages/'.$file["file"])) {echo'<h1>'.ucfirst($file["title"]).'</h1>'; include('./pages/'.$file["file"]);} if(!empty($error)) echo '<font color="red">'.$error.'</font>'; include('./designe/'.$designe.'/foot.tpl'); ?> Now i tried alot of things including adding: Code: [Select] session_start(); $_SESSION["username"] = "peter"; $_SESSION["user"] = "peter"; $_SESSION["id"] = "1"; $_SESSION["pass"] = "peter"; $_SESSION["password"] = "peter"; or Code: [Select] $id = "1"; $user = "peter"; $username = "peter"; $pass = "peter"; $password = "peter"; also a combination of both, nothing works, but i don't understand why ? Any help is appreciated. /Edit, i tried adding it to the paymentmodule .php aswell, but no luck. Hey Guys. I am across this in a book and I am having a hard time understanding how I can try/catch this expception
The code below will throw an exception if I add an unit object into Archer or LaserCannon object.
Here is a quick example
class UnitException extends Exception{} abstract class Unit{ function AddUnit(Unit $unit){ throw new UnitException(get_class($this)."is a leaf"); } function removeUnit(Unit $unit){ throw new UnitException(get_class($this)."is a leaf"); } abstract function bombardStrength(); } class Archer extends Unit { function bombardStrength(){ return 4; } } class LaserCannonUnit extends Unit { function bombardStrength(){ return 44; } } $laser_cannon = new LaserCannonUnit(); $laser_cannon->AddUnit(New Archer()); // This is not allowedWhen I run the client code I get the following error message Fatal error: Uncaught exception 'UnitException' with message 'LaserCannonUnitis a leaf' Can any please help me understand this?? Thanks! Hi guys I need to know how i can create a session for userid from my database, I have done the session for username but not being able to do it for user name, here is my code. my database table is called users and I can login successfully, but i tried few code and it wont show the user id, the column for user id is 'id' <?php include 'global.php'; $session_username = $_SESSION['username']; if ($_POST['login']) { //get form data $username = addslashes(strip_tags($_POST['username'])); $password = addslashes(strip_tags($_POST['password'])); if (!$username||!$password) echo "Enter a username and password"; else { //log in $login = mysql_query("SELECT * FROM users WHERE username='$username'"); if (mysql_num_rows($login)==0) echo "No such user"; else { while ($login_row = mysql_fetch_assoc($login)) { //get database password $password_db = $login_row['password']; //encrypt form password $password = md5($password); //check password if ($password!=$password_db) echo "Incorrect password"; else { //check if active $active = $login_row['active']; $email = $login_row['email']; if ($active==0) echo "You haven't activated your account, please check your email ($email)"; else { $_SESSION['username']=$username; //assign session header('Location:my.php'); } } } } } } else { if (isset($session_username)) { echo "You are logged in, $session_username., <a href='logout.php'>Log out</a>"; } else { echo " <form action='index.php' method='POST'> Username: <input type='text' name='username'><p /> Password: <input type='password' name='password'><p /> <input type='submit' name='login' value='Log in'> </form> "; } } ?> thanks Hi, I have stored user data in the database, but I think I need to somehow grab the "id" of the username, and use that in a SESSION when they log in, so that I can pull up the user information in the database for that particular user when they log in. and do that for everyone when they log in. My idea is user logs in Something like "grab the user "id" linked to this user, and add that value to "$currentUser", then somehow when it is time to show their user profile page, I do something like "display all field data where username=$currentUser. I don't know I am confused, any help plus code would be great if anyone can help, or just the pseudocode would be good. I hope I explained it right. thanks. This will be a little difficult to explain, but keep with me. On the profile.php page. It starts a new session. Code: [Select] // Connect to MySQL... $conn = mysql_connect($hostname, $username, $password) or die("Connecting to MySQL failed"); mysql_select_db($database, $conn) or die("Selecting MySQL database failed"); // Run our query, see if session username exists in session field... $sql="select username,email from user where username='{$_SESSION['user']}' limit 1"; $result=mysql_query($sql,$conn); // Parse our results into $data (as an associative array)... $data=mysql_fetch_assoc($result); // If one row was found in the result set, username exists... if (mysql_num_rows($result)==1) { $_SESSION['sellername'] = $data['username']; So what I am hoping that is doing, is the session named "sellername" is stored with the variable of the logged in user. In this example "testuser". Now the page updates.php will have an id attached to like so: updates.php?id=13. Which will have info only available for testuser's eyes. On the page it does this. Code: [Select] // Connect to MySQL... $conn = mysql_connect($hostname, $username, $password) or die("Connecting to MySQL failed"); mysql_select_db($database, $conn) or die("Selecting MySQL database failed"); // Run our query, see if session username exists in session field... $sql="select username from user where username='{$_SESSION['user']}' limit 1"; $result=mysql_query($sql,$conn); // Parse our results into $data (as an associative array)... $data=mysql_fetch_assoc($result); // If one row was found in the result set, username exists... if (mysql_num_rows($result)==1) { $query='select seller from listings where seller = "'.$data['username'].'"'; $queryresult=mysql_query($query,$conn); while($info = mysql_fetch_assoc($queryresult)){ if ( $_SESSION['sellername'] == $info['seller'] ){ The if statement should process: "If the session variable for 'sellername' equals the database entry 'seller' then display the rest of the page." However, no matter what user is logged, it will display the page. Any ideas? i have my upload process working that uploads documents to the server and then displays in onto the user page like this:
<?php function find_all_files($dir) { $root = scandir($dir); foreach($root as $value) { if($value === '.' || $value === '..') {continue;} if(is_file("$dir/$value")) {$result[]="$dir/$value"; continue; } foreach(find_all_files("$dir/$value") as $value) { $result[]=$value; } } return $result; } $fileupload = 'fileupload'; $getem = find_all_files($fileupload); foreach($getem as $key => $value) { echo '<a href="'.$value.'">'.$value.'</a><br />'; } ?> <?php if($handle = opendir('members/')) { while (false !== ($entry = readdir($handle))) { if($entry != "." && $enrty != "..") { echo "<a href='download.php?file=".$entry."'>".$entry."</a>\n"; } } closedir($handle); } ?>here they can download the files to their computer however is there a way to only display the file of the user that is logged in through their session? Hello all, I have a membership website which is using sessions... and ive been asked to add some promotion points system. So that each user is able to see how many promotion points they have... Now, I'm a beginner in mysql and php, but feel I'm learning fairly quickly. What I need help with, is to be able to display the amount of promotion points for the logged in user. I created a new field in my "essenti1_Users" table for the promotion code. database is called "essenti1_membership" table is "essenti1_Users" feild is "promo" I think im going to have to manually add the points to each user manually through phpMyAdmin Navicat unfortunatly. Unless anyone has any other ideas just for adding the points to each user account? ziggynerja is online now Add to ziggynerja's Reputation Report Post Edit/Delete Message Unfortunately I have no code for this yet cuz I don;t even know if its possible... I am programming an application that is used by a couple of stores, which could end up being a lot of stores. Anyways, the basis is that the stores would, though a separate application (and therefore separate database) create a username and password, I now want to use this username and password to do the following 1. Allow them to login to my application using the same username and password 2. I want the store the username in a session to pull tables based on the username from my database For instance, a user has the login store123, after loggin in it now pulls the information from the tables store123_items, store123_prices, store123_settings, etc. Now my database will have quite a lot of store###_tables I am, sadly, a noobie to PHP and I do recall seeing an article (somewhere on the net, and I stupidly forgot to bookmark it, knowing I would need it eventually) on how to access multiple databases easily. Now because they are both under my account I can use the same username and password for both, its accessing the MySQL username/password database and storing the info I know I am lacking on how to do it. Any ideas? Login.php Code: [Select] <?php session_start(); mysql_connect("localhost","root") or die(mysql_error()); mysql_select_db("cute") or die(mysql_error()); $username = $_POST['username']; $password = $_POST['pass']; if (isset($_POST["submit"])) { $log = "SELECT * FROM regis WHERE username = '$username'"; $login = mysql_query($log); $row = mysql_fetch_array($login); $number = mysql_num_rows($login); if ($number > 0) { $_SESSION['username'] = $row['username']; $_SESSION['userlevel'] = $row['userlevel']; if($_SESSION['userlevel']==1) { $_SESSION['is_logged_in'] == 1; header("Location: form2.php"); } else if($_SESSION['userlevel']== 0) { $_SESSION['is_logged_in'] == 1; header("Location: registration.php"); } } Registration.php Code: [Select] <?php echo 'Welcome:' .$_SESSION['is_logged_in'];?> form2.php Code: [Select] <?php session_start(); if (empty($_SESSION['is_logged_in'])) { header("Location:chatframe.php"); die(); // just to make sure no scripts execute } ?> <?php mysql_connect("localhost","root") or die(mysql_error()); mysql_select_db("cute") or die(mysql_error()); $message=$_POST['message']; $a=$_SESSION['username']; if(isset($_POST['submit'])) //if submit button push has been detected { if(strlen($message)>1) { $message=strip_tags($message); $IP=$_SERVER["REMOTE_ADDR"]; //grabs poster's IP $checkforbanned="SELECT IP from ipbans where IP='$IP'"; $checkforbanned2=mysql_query($checkforbanned) or die("Could not check for banned IPS"); if(mysql_num_rows($checkforbanned2)>0) //IP is in the banned list { print "You IP is banned from posting."; } else { $thedate = date("U"); //grab date and time of the post $insertmessage="INSERT into chatmessages (name,IP,postime,message) values('$a','$IP','$thedate','$message')"; mysql_query($insertmessage) or die("Could not insert message"); } } } ?> <html> <head> <script type="text/javascript"> function addsmiley(code) { var pretext = document.smile.message.value; this.code = code; document.smile.message.value = pretext + code; } function a() { var x = document.smile.message.value; if(x=="") { alert("Please insert an message!"); return false; } } </script> <style type="text/css"> body{ background-color: #d8da3d } </style> </head> <body> <form name="smile" method="post" action="form2.php" onSubmit="return a()" > Your message:<br><textarea name='message' cols='40' rows='2'></textarea><br> <img src="smile.gif" alt=":)" onClick="addsmiley(':)')" style="cursor:pointer;border:0" /> <img src="blush.gif" alt=":)" onClick="addsmiley('*blush*')" style="cursor:pointer;border:0" /> <input type='submit' name='submit' value='Send' class='biasa' ></form> <br> <br> </body> </html> In this registration.php when im called back its appear nothing im means the number is not showing and the login code even im had also put the "$_SESSION['is_logged_in'] == 1;" outside if else userlevel statement and then i put $d= $_SESSION['is_logged_in'] == 1; and im echoing back but it is nothing im thinks something wrong in session is login and also still it cannot redirect to admin -form2.php when session is login in is 1 show list of files uploaded by current session user to the database. I want to show different users when they log in to the website...they can see a list of old files that they have uploaded. can anyone tell me the code/script to this.....please, ty Hello All, I have a PHP web application which will refresh itself(ajax calls connecting to the server and get the latest data) periodically. These also update the Database-based session handler class. i.e. There is NO UPDATE to the session data but the timestamp is constantly updated. Our problem is that garbage collection does not kick in as it looks at the difference between timestamp and session_gc.maxlifetime. So, if and the user is not interacting with the application. Now my question is how can I force the timeout even though refreshing happens but the user is not interacting with the application and there are "phantom" session updates made by these ajax calls. Please let me know. Thanks. Hi Guys New to php so stick with me. I'm trying to create a simple login script that will grant a user access to content that is only viewable by those people who are logged in. I'm ok doing the login part and authenticating the password etc. But once the user gets directed to the content page how can I ensure that only a registered user who is logged in sees that page? (probably missing something very obvious here). I've tried reading around but not found much on this specific question. Should I set the user's username and password (which is encrypted) as session variables and authenticate them as the first stage of each page they visit? Or is there a better way of doing this? Don't worry, not looking for you to write the code just a description of the best way of doing it would be great! Thanks, Drongo I have a business social network site on hosting server. I am wondering if sessions are enough secure. ini_set('session.use_only_cookies', 1); //this prevent Session Fixation? session_start(); if($_SESSION['loggedIn'] && $_SESSION['userIP']==$_SERVER["REMOTE_ADDR"]) // extra security //user is logged in, assign all data to this profile from session else //user is not logged in, no data are assigned Would you consider that as enough secure? What is the best practice to use cookies and sessions? Should i create a cookie and keep inside the cookie the name of the username the user has logged in or a session? How am i supposed to compine theese two? Is there any example or a tutorial on this? For example how does php freaks sessions and cookies work. Im pretty new to PHP, but have managed to create a login system for a small site, my question relates to why Im entering a certain piece of code, I understand the code apart from the getting the information from a form and assigning it to a variable, I have a username form with one submit button, (username) which goes to a script called register.php I have this in my php: <?php error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED); $username=$_POST['username']; session_register("username"); header("location:index2.php"); ?> then in my index2.php page i have this: <?php error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED); session_start(); $username= $_SESSION['username']; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>My Page</title> </head> <body> <p> Hi <?php echo $username; ?> </p> </body> </html> Ive simplified what ive done here,why am I declaring a variabel to get the form contents? cant I just get the contents? and then register? I dont need a variable.. If I remove the line, it doesnt work obviously.. thanks Hi all a small question. I was wondering if someone knows what would be the approach to achieve the following. on a page I show a random number. If the page refreshes (selfreferencing) It shows a new random number but also a the previous number, and this must be able to repeat itself : ) So to make it more visible: New Random number = 98765 Previous Number = 56412 This is what I have but it's ofc not working because ones the session var has been set it will not show the previous variable but the very first one. <?php session_start(); $random_number .= mt_rand(1,100000); if(!isset($_SESSION['number'])){ $_SESSION['number']=$random_number; } // echo all out: echo 'New random number is: '.$random_number; echo 'Previous number is: '.$_SESSION['number']; ?> I bet i need another variable to store the previous one in but for some reasons my brains don't work at the moment Hi guys, I was wondering if we have table of seats in a cinema (which makes the quantity to 1) and two users are booking the same seat at the same time on our application. How can we prevent that? I though if we create a session or even update that seat row and then if user doesn't finish the booking/or leave the browser on fora while in 10-15 minutes, that session still remains on. I'm sure we can expire that session how can we prevent both users have the same session and if one doesn't complete the purchase for any reason then how session can automatically update the database after that 15 minutes? Thanks in advance. hi guys. i am trying to set a variable to the session global variable. I've initialized the session with session_start(); at the very beginning of my website, and then i try finding if a session variable has been set like so if(isset($_SESSION['user'])) { print 'user is logged in'; } but this works in reverse. i have not set any session variables, but asking if it is set, results in an affirmative answer. so i am thinking this is because of register_globals. because i went to read about register_globals, and it says that if register_globals is turned off, i cannot use any other varibale except members of the session array. i dont know what that is yet, but a question befo in the php manual it says register_globals is deprecated, and it appears i need to enable it to set other variables as session variables besides it's associative array. if this is true, how to enable register_globals and allow other variables to be used as session variables? Hi, I know very little about binding PHP to AD. At the minute it is setup to Authenticate against AD (Via IIS), then from the that I have the following: Declare's the Logon_Name variable, so that it can be used to 'print' buttons, and links i.e. if ($logon_name==("Administrator")); {echo admin link here'}; $logon_name = basename($_SERVER['AUTH_USER']); What I would ideally like to do is be able to find the group the user is a member of, this way we can create custom AD groups like intra_admin and then if they are a member they will be able to see certain links to pages etc. Any ideas, I hope this makes sence |