PHP - Session Help
To my understanding, a session is created and then stored on the server with its assigned value and a unique id. So, if that is correct I should be able to somehow locate a particular session on the server based on it's assigned value. Well, I was hoping to use this concept to keep multiple people from logging in under the same account at the same time.
I figured that I could check this in my login script by declaring the customer's id as the session value when they login. Then, I could check for a session variable equal to the cusotmer's id when they try to login. My (untested) code is below. Am I going about this right, and how would I check to see if a user's session is currently set on the server? Code: [Select] <?php // initiate session and redirect logged in users session_start(); if(isset($_SESSION['customer_id'])) { header('location:my_videos.php'); } // if login button was pressed if(array_key_exists('login', $_POST)) { // initalize error array and check that user supplied a username and password $error = array(); $username = trim($_POST['username']); $password = trim($_POST['password']); if(empty($username)) { $error['username'] = 'Please enter your username.'; } if(empty($password)) { $error['password'] = 'Please enter your password.'; } // if username and password supplied then proceed if(!$error) { // connect to the database require_once('includes/connect.php'); // filter data for query $username = mysql_real_escape_string($username); $password = md5(mysql_real_escape_string($password)); $queryUser = mysql_query("SELECT customer_id, customer_username, customer_password FROM customer WHERE customer_username = '$username' AND customer_password = '$password'", $connect) or die(mysql_error()); $dataUser = mysql_fetch_assoc($queryUser); $rowsUser = mysql_num_rows($queryUser); $customerId = $dataUser['customer_id']; // determine if the user is a valid customer if($rowsUser == 1) { // see how many IP addresses the customer has used to login with in the past 24 hours $queryIP = mysql_query("SELECT COUNT(DISTINCT log_ip) AS ip FROM log WHERE log_customer_id = $customerId AND log_timestamp IN((DATE_SUB(NOW(), INTERVAL 1 DAY)), NOW())") or die(mysql_error()); $dataIP = mysql_fetch_assoc($queryIP); if($dataIP['ip'] > 3) { $error['ip'] = 'This customer account has reached the maximum number of IP addresses allowed. If you feel this is a system error please send us an email via the Contact Us form.'; exit; } else { // see if the customer is already logged in $queryLogged = mysql_query("SELECT customer_id, customer_logged_in FROM customer WHERE customer_logged_in = 1 AND customer_id = '$customer_id'", $connect) or die(mysql_error()); $dataLogged = mysql_fetch_assoc($queryLogged); $rowsLogged = mysql_num_rows($queryLogged); if($rowsLogged == 1) { // if database shows the customer is already logged in // if there is also a session variable set that matches their customer id on the server if($_SESSION['customer_id'] == $customerId) { // i need to somehow find this session value on the server first // this means the user is trying to login from two different locations header('location:bad_login.php'); exit; // if no session variable for customer id is set on the server } else { // this means user lost connection without logging out // set a customer id session variable $_SESSION['customer_id'] = $customerId; // log customer activity $ip = $_SERVER["REMOTE_ADDR"]; $queryLog = mysql_query("INSERT INTO log (log_timestamp, log_ip, log_customer_id) VALUES (NOW(), '$ip', '$customerId')", $connect)or die(mysql_error()); // send user to appropriate page (if a previous page session variable exists send them there) if(isset($_SESSION['previous_page'])) { header('location:video_info.php'); // if not send them to the my_videos.php page } else { header('location:my_videos.php'); } } } // if database shows the customer is not logged in else { $_SESSION['customer_id'] = $customerId; $queryLogin = mysql_query("UPDATE customer SET customer_logged_in = 1 WHERE customer_id = '$customerId'", $connect) or die(mysql_error()); $ip = $_SERVER["REMOTE_ADDR"]; $queryLog = mysql_query("INSERT INTO log (log_timestamp, log_ip, log_member_id) VALUES (NOW(), '$ip', '$customerId')", $connect)or die(mysql_error()); if(isset($_SESSION['previous_page'])) { header('location:video_info.php'); } else { header('location:my_videos.php'); } } } // if there was no match found in the database } else { $error['login'] = "Incorrect username and/or password. If you do not have an account with us, please create one"; } } } ?> Similar TutorialsI am having trouble resolving an error. Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/s519970/public_html/header.php:27) in /home/s519970/public_html/admin/login.php on line 2 What I can gather is I can't use "header (Location: 'admin.php')" after i've used session_start(). I have tried to replace the header (Location: 'admin.php') with this: echo "<script>document.location.href='admin.php'</script>"; echo "<script>'Content-type: application/octet-stream'</script>"; I've been trying to read up on solutions but haven't been able to get it sorted. If anyone can offer some advice that would be greatly appreciated as im new to php. Code: [Select] <?php session_start(); if(isset($_SESSION['user'])) echo "<script>document.location.href='admin.php'</script>"; echo "<script>'Content-type: application/octet-stream'</script>"; ?> <div id="loginform"> <form action="dologin.php" method="post"> <table> <tr> <td><span>Username:</span></td> <td><input type="text" name="username" /></td> </tr> <tr> <td><span>Password:</span></td> <td><input type="password" name="password" /></td> </tr> <tr> <td colspan="2" align="right"><input type="submit" name="login" value="Login" /></td> </tr> </table> </form> </div> I have tried using require_once('yourpage.php'); before my <head></head> tags in the header document where I've specified the html information but this doesn't seem to work. I've been advised to use ob_start("ob_gzhandler"); but I am not sure how to implement this. Any advice is greatly appreciated! in this page http://maximaart.com/newscp/ i have this problem Code: [Select] Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/maximasy/public_html/newscp/index.php:1) in /home/maximasy/public_html/newscp/index.php on line 2 my source code is <?php session_start(); include_once("config.php"); include_once("functions.php"); $errorMessage = ''; if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) { if ($_POST['txtUserId'] === "$user" && $_POST['txtPassword'] === "$pass") { // the user id and password match, $_SESSION['basic_is_logged_in'] = true; require("main.php"); exit;?> I am trying to create an index page which contains registration and login field the problem that i get is on successful login a warning is displayed session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\xampp\htdocs\Eventz.com\index.php:116) in C:\xampp\htdocs\Eventz.com\index.php on line 235 This is the login part of my index.php this tag is inside an html table below the login form I also have a registration form and its php code above the login form Code: [Select] <?php if (isset($_REQUEST['pass'])) { $id=$_POST['id']; $pass=$_POST['pass']; $conn =mysql_connect("localhost","root",""); if (!$conn) { die('Could not connect: ' . mysql_error()); } /* checking connection....success! */ $e=mysql_select_db('test', $conn); if(!$e) { die(''.mysql_error()); } else { echo 'database selected successfully'; } if (isset($_REQUEST['id']) || (isset($_REQUEST['pass']))) { if($_REQUEST['id'] == "" || $_REQUEST['pass']=="") { echo "login fields cannot be empty"; } else { $sql=mysql_query("Select email,password from login where email='$id' AND password='$pass'"); $count=mysql_num_rows($sql); if($count==1) /* $count checks if username and password are in same row */ { session_start(); $_SESSION['id']=$id; echo "</br>Login Successful</br>"; } else { echo "</br>invalid</br>"; echo "please try to login again</br>"; } } } } ?> Any help or suggestion would be appreciated hi everyone. i'm wondering what the best way is to create a session variable and pass it to an iframe. i need to do something along these lines, but it doesn't seem to pass the ID. Any hints on how i should accomplish this? Code: [Select] session_start(); $_SESSION['ID']=$_GET['ID']; // id from previous page $ID=session_id(); <iframe src="iframepage.php?ID=<?php echo $ID; ?>" style="width:680px; height:200px;" noresize="noresize" frameborder="0" border="0" scrolling="Yes" allowtransparency="true" /> </iframe> I'm making a simple login system with MySQL and PHP (very simple, I'm just starting with PHP). The MySQL portion is done, but I need to ensure only people who are logged in can see certain content. To check if people are logged in, my website checks that they have the $_SESSION['user'] variable set. If it is set, then it lets them continue through the website, if not, it tells them to login. Is that enough security, or can people simply inject a session cookie into their browser to spoof that they are logged in? My idea was to generate a session key cookie when they login (just a random string of letters and numbers) and store that in the database, then on every page, check to make sure their session key is the same thing that's in the database. Is this necessary? It seems expensive. Evening! I've been iffing and ahhing over this and well im not too sure, hence the post. Code: [Select] // Redirects if there is no session id selected and echos the error on the previous page if(!isset($_GET['get']) || ($_GET['getget'])){ header("Location: #.php?error"); } So it should simply check if get is set if it isnt then see if getget is set? If not redirect and show the error. Now ive tried it and even when get/getget is set it still redirects, probably something silly. Care to share anyone? Harry. Just curious how other people feel about this. I am working on an application where a lot of info is pulled from MySQL and needed on multiple pages.
Would it make more sense to...
1. Pull all data ONCE and store it in SESSION variables to use on other pages
2. Pull the data from the database on each new page that needs it
I assume the preferred method is #1, but maybe there is some downside to using SESSION variables "too much"?
Side question that's kind of related: As far as URLs, is it preferable to have data stored in them (i.e. domain.com/somepage.php?somedata=something&otherdata=thisdata) or use SESSION variables to store that data so the URLs can stay general/clean (i.e. domain.com/somepage.php)?
Both are probably loaded questions but any possible insight would be appreciated.
Thanks!
Greg
Edited by galvin, 04 November 2014 - 10:30 AM. Hello I keep having this issue with sessions. I have an login feature on my website that uses sessions. When i do like this: 1. Login 2. close browser 3. open browser again 4. try to log in It fails, actually nothing happens, so I manually need to go to logout.php to reset and then I can log in again. Why is this happening and how do i solve it? Hi guys help please Code: [Select] foreach($_SESSION['cart'] as $id => $value){ } is this valid? im getting error Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\shopping cart\new_cart.php on line 48 Many thanks Hi, I am trying to get the value of a session veriable and if the variable contains a certain word it will show an error message, else just continue as normal. if (isset($_POST['selectroom'])) {$_SESSION['room'] = $_POST['selectroom'];} if (!isset($_SESSION['room'])) $room = "RoomNameA"; else $room = $_SESSION['room']; Please Advise, - Stuart How to add more data into $_SESSION? I have following code: Code: [Select] if(isset($_GET['poredi']) && $_GET['poredi'] == "upo"){ $idp = intval($_POST['idp']); $sql = "SELECT * FROM product WHERE product_id={$idp}"; $query=mysql_query($sql); if(mysql_num_rows($query)!=0){ $row=mysql_fetch_array($query); $_SESSION['poredi'] = $row['product_id']; } } On click it need to store more product_id, and after that i have to be able to do query with data (find all data with product_id)? I am building an app (PHP and MySQL)and I had been using a lot of GET calls to get info from URLs, but the more I thought about it, the more I didn't like the possibility of people being able to mess with the URLs. So I am in the process of changing everything to use SESSION variables to store data across pages, rather than GET. The way I see it, SESSION variables are completely behind the scenes so they seem to be the better option. Am I right, or is GET better than SESSION for some reason? Hi I am looking for help with a working script to input multiple lines of data , but i am looking for each line of data to have the $_SESSION[userid] entered into each line, ie into the table $_SESSION[userid], name, surname, age Many Thanks <? include "include/session.php"; include "include/z_db.php"; // check the login details of the user and stop execution if not logged in require "check.php"; // If member has logged in then below script will be execuated. // let us collect all data of the member $row=mysql_fetch_object(mysql_query("select * from plus_signup where userid='$_SESSION[userid]'")); if(isset($_POST['submit'])) { foreach($_POST['person'] as $person) { $name= mysql_real_escape_string($person['name']); $surname= mysql_real_escape_string($person['surname']); $age= mysql_real_escape_string($person['age']); $values[] = "('$name', '$surname', '$age')"; } $query = "INSERT INTO plus_signup (name,surname,age) VALUES " . implode(', ', $values); $result = mysql_query($query) or die("Error!<br />Query: $query<br />Error: " . mysql_error()); } ?> <form method="POST" action='multi.php' name=""> <table> <tr> <td>Name<input type="text" name="person[0][name]"></td> <td>surname<input type="text" name="person[0][surname]"></td> <td>age<input type="text" name="person[0][age]"></td> </tr> <tr> <td>name<input type="text" name="person[1][name]"></td> <td>surname<input type="text" name="person[1][surname]"></td> <td>age<input type="text" name="person[1][age]"></td> </tr> <tr> <td>name<input type="text" name="person[2][name]"></td> <td>surname<input type="text" name="person[2][surname]"></td> <td>age<input type="text" name="person[2][age]"></td> </tr> </table> <td><p> <input type="submit" name="submit" value="add"> </p> <p> </p>| <a href=update-profile.php>back</a>| </form> <? require "bottom.php"; ?> <center><br>| <a href=update-profile.php>back</a>|<br></center> </body> </html> I am having trouble calling the session var "email" from the landing page. Here is the code that I am using. I am not even sure the session "email" is starting or registering. Code: [Select] $referer = $_SERVER['HTTP_REFERER']; $email = $_POST['email']; $sql="SELECT * FROM users WHERE email='$email' "; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $email, table row count must be 1 row if($count==1){ // Session Register email session_start(); $_SESSION['email'] = $email; header("location:".$referer2." "); exit(); } Pls tell me what is wrong? <?PHP include("dba.php"); function hvataj ($trazi, $id) { $upit = mysql_query ('select * from administrator where member_id = '.$id.''); return ( $row = mysql_fetch_assoc ($upit) ) ? $row[$trazi] : mysql_error (); } ?> I have parse error here on this line when I want to echo it: <?PHP echo "<img src='images/korisnik_slike/".hvataj('slika',$_SESSION['member_id']."' />"; ?> Hello everyone I have the following code $num = 1; $query = mysql_query("SELECT * FROM people"); while($row = mysql_fetch_array($query)) { $nums = $num++; $_SESSION['equal'.$nums.''] = $row['name']; $_SESSION['total'.$nums.''] = $row['age']; } which basically returns me SESSION names by increasing by 1, so it could produce the following session names Code: [Select] equal1 total1 equal2 total2 equal3 total3 equal4 total4 instead of setting those as sessions, I simply want to set them as vars, so instead of $_SESSION['equal'.$nums.''] = $row['name']; $_SESSION['total'.$nums.''] = $row['age']; it would look like $equal.$nums = $row['name']; $total.$nums = $row['age']; I have tried $equal.$nums = $row['name']; $total.$nums = $row['age']; but it doesn't seem to work any ideas? thanks Why is my SESSION not getting set in the code below?! Code: [Select] <?php // Initialize a session. session_start(); // Initialize Logged-In Status. $_SESSION['loggedIn'] = FALSE; // Display Logged-In Status. echo '<p>$_SESSION[\'loggedIn\'] = ' . $_SESSION['loggedIn'] . '</p>'; exit(); When I run this I get... $_SESSION['loggedIn'] = Debbie Is there anyway to work out the age of a session, i.e the time that has elapsed since it was created? Cheers I'm trying to make my own shopping cart for the first time and having a problem getting products to add to it. All I get is "No product in cart.". Its nothing special now, I'm just trying to reach the first stepping stone of adding something successfully to the session. index.html Code: [Select] <?php session_start(); ?> <?php $cart = $_SESSION['cart']; if (!$cart) { echo "No product in cart."; } if ($cart) { foreach ($id) { echo $id; } } ?> <A href="index.html?action=add&id=1">Add to cart</A> What have I done wrong and what am I suppose to do? Code: [Select] <?php session_start(); if(!session_is_registered(myusername)){ header("location:./default.php"); } ?> My session works fine but I am just wondering how I can echo the current sessions username? Thanks |