PHP - Session Hell
Short version of my question is going to be "why are my session variables vanishing?"
[ START not important Stuff ] My (simplified) site layout looks like login_page.php ->page1.php->page2.php login_page.php connects to mysql, to check login/pwd, and, if valid, sets the _SESSION id's/other credentials and then redirects to page1.php. page1.php has link to page2.php. Both page1 and page2 check against (require_once) an auth.php (authorization) and redirect to login_page.php if not logged in. The auth.php file has the structu session_start(); if(!isset($_SESSION['SESS_USER_ID'])|| other parameters){ //code } page2 has an AJAX load that pulls in a php file that includes various content (XML,text,.htm,etc.) That php file also requires auth.php All of these things work. [ END not important stuff ] [Start important part] Everything works. Session variables persist and are readable/accessible via all pages, as well as a Debug link (pop window that echos the $_SESSION vars.) UNLESSS the user is inactive for more than a minute or two; At which point the session variables vanish. Again, I can log in, Set the session variables, load multiple pages via AJAX (all of which are checked against the session variables...which means they have to exist) and generally everything works as expected. However, if I stop navigating/interacting with the site for more than a minute, or so, the session variables vanish (user id / other user credentials) and the I'm kicked back to the login the next time I click a link. There is nothing but the initial mysql login that writes to the session variables. No code, on any other page, does anything but read the session. My php ini file appears to have the correct location for my session.save_path. The garbage collection is the defualt 1440 and the cache_expire is also the default 180 I'm hosted with fatcow (starting to regret that) with Debian/Apache/php5 Oh and, this happens on every browser on Linux, Mac, and Windows. But it doesn't seem to occur if I run it locally from xampp/lampp. I'm at a total loss as to ideas for my next debugging step and any suggestions would be much appreciated. Similar TutorialsSo I wrote this code, what its supposed to do is draw an image on a grid space, based on its X,Y coordinates from a mySql database, compared to the player X,Y. Heres the code: Code: [Select] <table> <tr> <td> <?php //northwest echo "nw"; $x1 = $_SESSION[x] - 1; $y1 = $_SESSION[y] + 1; $hasobject1 = mysql_query("SELECT * FROM objects WHERE x='$x1' && y='$y1'"); while($row = mysql_fetch_array($hasobject1)) { $image = "space_228.gif"; $image = $row[image]; } if(!empty($image)){ echo "<IMG SRC=$image WIDTH=64 HEIGHT=64 onerror='onImgError(this)>'"; } else{ echo "<IMG SRC='space_228.gif' WIDTH=64 HEIGHT=64>"; } ?></td> <td><?php //north echo "n"; $x2 = $_SESSION[x]; $y2 = $_SESSION[y] + 1; $hasobject2 = mysql_query("SELECT * FROM objects WHERE x='$x2' && y='$y2'"); while($row = mysql_fetch_array($hasobject2)) { $image = "space_228.gif"; $image = $row[image]; } if(!empty($image)){ echo "<IMG SRC=$image WIDTH=64 HEIGHT=64 onerror='onImgError(this)>'"; } else{ echo "<IMG SRC='space_228.gif' WIDTH=64 HEIGHT=64>"; } ?></td> <td><?php //northeast echo "ne"; $x3 = $_SESSION[x] + 1; $y3 = $_SESSION[y] + 1; $hasobject3 = mysql_query("SELECT * FROM objects WHERE x='$x3' && y='$y3'"); while($row = mysql_fetch_array($hasobject3)) { $image = "space_228.gif"; $image = $row[image]; } if(!empty($image)){ echo "<IMG SRC=$image WIDTH=64 HEIGHT=64 onerror='onImgError(this)>'"; } else{ echo "<IMG SRC='space_228.gif' WIDTH=64 HEIGHT=64>"; } ?></td> </tr> <tr> <td><?php //wesr echo "w"; $x4 = $_SESSION[x] - 1; $y4 = $_SESSION[y]; $hasobject4 = mysql_query("SELECT * FROM objects WHERE x='$x4' && y='$y4'"); while($row = mysql_fetch_array($hasobject4)) { $image = "space_228.gif"; $image = $row[image]; } if(!empty($image)){ echo "<IMG SRC=$image WIDTH=64 HEIGHT=64 onerror='onImgError(this)>'"; } else{ echo "<IMG SRC='space_228.gif' WIDTH=64 HEIGHT=64>"; } ?></td> <td><?php echo "p"; //player echo "<IMG SRC='spaceship_wire5.jpg' WIDTH=64 HEIGHT=64>"; ?></td> <td><?php //east echo "e"; $x5 = $_SESSION[x] + 1; $y5 = $_SESSION[y]; $hasobject5 = mysql_query("SELECT * FROM objects WHERE x='$x5' && y='$y5'"); while($row = mysql_fetch_array($hasobject5)) { $image = "space_228.gif"; $image = $row[image]; } if(!empty($image)){ echo "<IMG SRC=$image WIDTH=64 HEIGHT=64 onerror='onImgError(this)>'"; } else{ echo "<IMG SRC='space_228.gif' WIDTH=64 HEIGHT=64>"; } ?></td> </tr> <tr> <td><?php //southwest echo "sw"; $x6 = $_SESSION[x] - 1; $y6 = $_SESSION[y] - 1; $hasobject6 = mysql_query("SELECT * FROM objects WHERE x='$x6' && y='$y6'"); while($row = mysql_fetch_array($hasobject6)) { $image = "space_228.gif"; $image = $row[image]; } if(!empty($image)){ echo "<IMG SRC=$image WIDTH=64 HEIGHT=64 onerror='onImgError(this)>'"; } else{ echo "<IMG SRC='space_228.gif' WIDTH=64 HEIGHT=64>"; } ?></td> <td><?php //south echo "s"; $x7 = $_SESSION[x]; $y7 = $_SESSION[y] - 1; $hasobject7 = mysql_query("SELECT * FROM objects WHERE x='$x7' && y='$y7'"); while($row = mysql_fetch_array($hasobject7)) { $image = "space_228.gif"; $image = $row[image]; } if(!empty($image)){ echo "<IMG SRC=$image WIDTH=64 HEIGHT=64 onerror='onImgError(this)>'"; } else{ echo "<IMG SRC='space_228.gif' WIDTH=64 HEIGHT=64>"; } ?></td> <td><?php //southeast echo "se"; $x8 = $_SESSION[x] + 1; $y8 = $_SESSION[y] - 1; $hasobject8 = mysql_query("SELECT * FROM objects WHERE x='$x8' && y='$y8'"); while($row = mysql_fetch_array($hasobject8)) { $image = "space_228.gif"; $image = $row[image]; } if(!empty($image)){ echo "<IMG SRC=$image WIDTH=64 HEIGHT=64 onerror='onImgError(this)>'"; } else{ echo "<IMG SRC='space_228.gif' WIDTH=64 HEIGHT=64>"; } ?></td> </tr> </table> Now what happens is it draws the image on a bunch of different spots. The object is at 0,0. It doesnt display the object if the object is out of range of the player, or the player is at 0,0. But if the player is near the object, it draws it on like half the grid spaces, and on some places everywhere but the players. Heres the page, login with test, password test. http://spacetimemmo.webuda.com/login.php Ok, I will explain first what I am trying to do, and show you how I am going about it, which isn't working I have a table set up. It has missing ID numbers, such as, 1 2 3 6 7 8 11 12 ..etc. I am trying to pull a random ID number from all valid ID numbers. (Meaning, I don't want to get an ID of a record that is no longer there, so skip all the missing ID's) This is for a cron job to change which record is being shown each day, randomly. I figured, logically, the best way to do this would be to pull all the valid ID's into an array, and then use array_rand($id_array,1); to pull one random ID number out of the array. So, I tried using this code: Code: [Select] //Set variable as an array $id_array = array(); //Populate array with valid ID's $sql="SELECT ID FROM riddles"; $result=mysql_query($sql,$db) or die(mysql_error()); while($row = mysql_fetch_array($result,$db)) { $id_array[] = $row['ID']; }; print_r(array($id_array)); $new_rotd=(array_rand($id_array[0],1)); I am running into 2 problems with this code. First, when I print_r the array, I get the following: Quote Array ( => Array ( => [1] => [2] => [3] => [4] => [5] => [6] => [7] => [8] => [9] => [10] => [11] => [12] => [13] => [14] => [15] => [16] => [17] => [18] => [19] => [20] => [21] => [22] => [23] => ) ) The numbers are not correct. It is the correct number of total records, but it is not putting the correct ID number in there. 2) When I try and pull a random number out of the array, I get an error saying the First argument has to be an array. It IS an array?! I need to get this working, so any help would be much appreciated. To summarize I need to: Pull all valid ID #'s out of the table and put them in an array. Pull one random number out of that array and set it as variable: $new_rotd Hey guys havent coded in a while and im stumped. Ive checked google but to no avail lol i wanna include my config file and have an IF statement to run/include another file IE... <?php include("config/config.php"); If File(Not Exist); include("install/config.php"); ?> If someone can put me back on track it would be greatly epreciated <?php # Game Info # $game_link = "http://mob-dynamic-lb".rand(1,5).".mobsters0".rand(1,9).".com/mob/"; //$id2 = 548685167; # ID / Auth Key file info # $filename = "auth-keys111.txt"; $fp = file($filename); foreach($fp as $cwb){ list($id,$auth) = explode(" ",$cwb); $a = file_get_contents($game_link."attack?user_id=".$id."&target_id=548685167&punch_in_face=true&auth_key=".$auth); echo "WTF!"; //////////////////////////////////////////// //////////////////////////////////////////// $a = file_get_contents($game_link."attack?user_id=".$id."&target_id=548685167&punch_in_face=true&auth_key=".$auth); $b = file_get_contents($game_link."top_mob_gift?user_id=".$id."&target_id=".$id."&auth_key=".$auth); $c = file_get_contents($game_link."remove_top_mob?user_id=".$id."&target_id=548685167&auth_key=".$auth); echo "WTF?!";} ?> everything is correct for $game_link and all that.. but its not workin.. Any ideas? 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 I 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'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. 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> 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. I am trying to get sessions to work right Here are my settings: session.gc_maxlifetime = 60 session.gc_probability = 1 session.gc_divisor = 1 session.cookie_lifetime = 0 (when browser closes) So say I have two php files: php1.php session_start(); $_SESSION['var1'] = 'var1'; php2.php session_start(); echo $_SESSION['var1']. '<br>'; So if I go to php1 it will set the variable and then I can go to php2 and it will echo the variable. This works. But if I don't do anything and then go back to php2 after 60 seconds the variable should no longer exist. This part is not working. What do I need to change to get it to work? 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']."' />"; ?> 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? 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 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"; } } } ?> hello all, What I want to do is, make the session ID clickable in a url here Code: [Select] Login Successful <a href="user.php">Conitnue</a> so when a user logs in, his ID gets in the link of Continue so he can only see his information so for example, if his id is 10, then the url would be ....user.php?id=10 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(); } 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 People, I am on a deadline and finding that my code does not work in php5 and I have to change it to work. Just wonder if anyone can spot the obvious within my code. This all worked in php4 but now I have to rewrite it. Basically its a little order system. <? include("inc/connect.php"); // Continue start session. // We need to first check to see if an item with the SID and cat and product_code exists in the database, // if it does then we need to update that item, if not then we need to add the item // clean out any malicious data foreach ($_REQUEST as $k => $v) { $_REQUEST[$k] = (get_magic_quotes_gpc() ? strip_tags($v) : strip_tags(addslashes($v))); } session_start(); { $sql = "SELECT * FROM orders WHERE sid = '$PHPSESSID' AND product_id = '$product_id' "; $sql_result = mysql_query($sql); if (mysql_num_rows($sql_result) ==0) { # setup SQL statement $SQL = " INSERT INTO orders (sid,product_id,product_title,qty,standard_price,deluxe_price) VALUES ('$PHPSESSID','$product_id','$product_title','$qty','$standard_price','$deluxe_price')"; #execute SQL statement $result = mysql_db_query( azflowers,"$SQL",$connection ); # check for error if (!$result) { echo("ERROR: " . mysql_error() . "\n$SQL\n"); } } else { # setup SQL statement $SQL = " UPDATE orders SET qty = qty +1 WHERE sid = '$PHPSESSID' AND product_id = '$product_id' "; #execute SQL statement $result = mysql_db_query( azflowers,"$SQL",$connection ); # check for error if (!$result) { echo("ERROR: " . mysql_error() . "\n$SQL\n"); } } header("Location: http://www.site.com/site/cart.php?sid=$PHPSESSID"); exit; } ?> |