PHP - Need Some Help With Php And Mysql Session Variables
Hi All! I've written up a script for my website. It\ is basically a virtual job quest. My queries are all correct it just isn't registering the variable for the session. It is $-SESSION[theid']. I want to be bale to use it in my table but I get an error. How do I write this in my SQL query for it to work. The page (when no errors), doesn't show my data. Here is my ocde:
Code: [Select] <?php session_start(); include("config536.php"); ?> <html> <head> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <?php if(!isset($_SESSION['username'])) { echo "<ubar><a href=login.php>Login</a> or <a href=register.php>Register</a></ubar><content><center><font size=6>Error!</font><br><br>You are not Logged In! Please <a href=login.php>Login</a> or <a href=register.php>Register</a> to Continue!</center></content><content><center><font size=6>Messages</font><br><br></center></content>"; } if(isset($_SESSION['username'])) { echo "<nav>$shownavbar</nav><ubar><img src=/images/layout/player.gif><a href=status.php>$showusername</a>.......................<img src=/images/layout/coin.gif> $scredits</ubar><content><center><font size=6>Basic Quests</font><br><br>"; $startjob = $_POST['submit']; $jobq = "SELECT * FROM jobs WHERE username='$showusername'"; $job = mysql_query($jobq); $jobnr = mysql_num_rows($job); if($jobnr == "0") { ?> <form action="<?php echo "$PHP_SELF"; ?>" method="POST"> <input type="submit" name="submit" value="Start Job"></form> <?php } if(isset($startjob)) { $initemidq = "SELECT * FROM items ORDER BY RAND() LIMIT 1"; $initemid = mysql_query($initemidq); while($ir = mysql_fetch_array($initemid)) { $ids = $ir['itemid']; } mysql_query("INSERT INTO jobs (username, item, time, completed) VALUES ('$showusername', '$ids', 'None', 'No')"); $wegq = "SELECT * FROM items WHERE itemid='$ids'"; $weg = mysql_query($wegq); while($wg = mysql_fetch_array($weg)) { $im = $wg['image']; $nm = $wg['name']; $id = $wg['itemid']; } $_SESSION['theid'] = $id; echo "<font color=green>Success! You have started this Job!</font><br><br>Please bring me this item: <b>$nm</b><br><br><img src=/images/items/$im><br><br><br>"; echo $_SESSION['theid']; } if($jobnr == "1") { $finish = $_POST['finish']; $okgq = "SELECT * FROM items WHERE itemid='$yes'"; $ok = mysql_query($okgq); while($ya = mysql_fetch_array($ok)) { $okname = $ya['name']; $okid = $ya['itemid']; $okimage = $ya['image']; } echo "Where is my <b>$okname</b>?<br><br><img src=/images/items/$okimage><br><br><br>"; echo $_SESSION['theid']; ?> <form action="<?php echo "$PHP_SELF"; ?>" method="POST"> <input type="submit" name="finish" value="I have the Item"></form> <?php } } if(isset($finish)) { $cinq = "SELECT * FROM uitems WHERE theitemid='$_SESSION[theid]'"; $cin = mysql_query($cinq); $connr = mysql_num_rows($cin); if($connr != "0") { echo "<font color=green>Success! You have the item.</font>"; } else { echo "<font color=red>Error! You do not have my item!</font>"; } } ?> . I basically just want to know how I can set this session as a variable. Also..I have a user login on every page and I want to be able to destroy JUST THE "theid" session and NOT the username session. How would I do that too? thanks for the help in advance! Similar TutorialsHola, I'm trying to create a web form to insert info into my database using session variables. I'm at my wits end at this point. The reset button does its job but when you click submit it doesn't do anything. I'm using the template from the lynda.com essential php web form tutorials. Any help would be appreciated Here is the client-side header code I'm working with, <?php header("Expires: Thu, 17 May 2001 10:17:17 GMT"); // Date in the past header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header ("Pragma: no-cache"); // HTTP/1.0 session_start(); if (!isset($_SESSION['SESSION'])) require ( "include/session_init.php"); $arVal = array(); require_once("include/session_funcs1.php"); // make sure the seesion vars are initialized... reset ($arVal); while (list ($key, $val) = each ($arVal)) { if (!isset($_SESSION[$key])) $_SESSION[$key] = ""; } if ($_SESSION["eventgenre_sel"] == "") $_SESSION["eventgenre_sel"] = 0; // if the bFlg is true then some validation problems in the data. // namely a blank field or a submission without the feedback page. // just present a general error... $flg = ""; $error = ""; if (isset($HTTP_GET_VARS["flg"])) $flg = $HTTP_GET_VARS["flg"]; switch ($flg) { case "red": $error = "<br><font class=\"txt12_red\">Please fill out all the required fields.<br>Please Try Again.<BR></font>"; break; case "blue": $error = "<br><font class=\"txt12_red\">Your Session has Expired.<br>Please Try Again.</font><BR>"; break; case "pink": $error = "<br><font class=\"txt12_red\"><BR>The Special Code you entered is not valid.<br>Please Try Again or Leave that field blank.</font><BR>"; break; case "white": $error = "<br><font class=\"txt12_red\"><BR>The fields are too long for our Database.<br>Please correct your data via this form.</font><BR>"; break; default: $error = ""; } ?> <?php echo $_SERVER['SCRIPT_NAME']."<BR>"; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="detect800.css"/> <link rel="stylesheet" type="text/css" href="detect1024.css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="detect.js"></script> <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/ui.all.css" rel="stylesheet" type="text/css" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js" type="text/javascript"></script> <script src="jquery.ui.datetimepicker.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { $('#eventdate').datetimepicker(); }); </script> <script src="imageflow.js" type="text/javascript"></script> <script src="highslide-full.js" type="text/javascript"></script> <script src="autosuggest.js" type="text/javascript"></script> <script type="text/javascript"> hs.graphicsDir = 'graphics/'; </script> <script language="javascript"> function SubmitForm() { var form = document.forms[0]; var bRequired = true; if((form.eventname.value.length < 1) || (form.eventvenue.value.length < 1) || (form.eventdate.value.length < 1) || (form.eventgenre.value.length < 1) || (form.eventprice.value.length < 1) || (form.eventpromoter.value.length < 1) || (form.eventflyer.value.length < 1)) { alert("Please fill out all the required fields."); bRequired = false; } if (!bRequired) return false; form.eventgenre_sel.value = form.state.selectedIndex; form.submit(); } function ResetForm() { var form = document.forms[0]; form.eventname.value = ""; form.eventvenue.value = ""; form.eventdate.value = ""; form.eventgenre.value = ""; form.eventprice.value = ""; form.eventpromoter.value = ""; form.eventflyer.value = ""; form.eventgenre_sel.value = ""; } </script> </head> This is the client side form code <form action="scripts/register.php" method="post" name="userevent" id="userevent"> <input name="eventgenre_sel" type="hidden" id="eventgenre_sel" value="<?php echo $_SESSION['eventgenre_sel'] ?>" /> <?php echo $error; ?> <fieldset> <label for="eventname" accesskey="n" ><span>Event Name</span> <input type="text" name="eventname" id="eventname" value="<?php echo $_SESSION['eventname_sel'] ?>" size="32" maxlength="30" /></label> <div id="autosuggest"><ul><li></li></ul></div> <label for="eventvenue" accesskey="v" ><span>Event Venue</span> <input type="text" name="eventvenue" id="eventvenue" size="32" value="<?php echo $_SESSION['eventvenue'] ?>" maxlength="30" /></label> <script type="text/javascript"> var venues = new Array("Republik", "HiFi Club", "Bamboo Tiki Room", "Tantra", "Jubilee Auditorium", "Ironwood Stage & Grill", "Broken City", "Soda", "Amsterdam Rhino", "Olympic Plaza", "Stampede Casino", "Habitat Living Sound", "Cantos Music Foundation", "Flames Central", "Prince's Island Park", "Beat Niq Jazz & Social Club", "Giuseppe's Italian Market", "BLVD", "Fourth on 4th", "Opus on 8th", "Local 510", "Local 522", "Raw Bar", "Jupiter Restaurant & Bar", "Vern's", "Lord Nelson's", "Kings Head Pub", "Blind Beggar Pub", "Viscous Circle", "Milk Tiger Lounge", "Pengrowth Saddledome", "Tubby Dog", "Marquee Room", "Distillery Public House", "Cafe Koi", "Mikey's Juke Joint & Eatery", "Palomino", "Atlantic Trap & Gill", "Drake Inn", "Radiopark Music Room", "Rusty Cage South", "Big Al's Good Times Bar", "Rose & Crown", "Tudor Rose Pub", "Elbow River Casino & Lounge", "Rusty Cage Central", "Rusty Cage South", "Rusty Cage North", "Olive Grove", "Shamrock Hotel", "Woody's Taphouse Southland", "Woody's Taphouse Country Hills", "Murrieta's West Coast Bar & Grill", "Stageline Saloon", "Pig & Pint", "Ranchman's", "Red Pepper Pub", "Stavro's Steak House & Lounge Ranchlands", "Stageline Saloon", "Whiskey"); new AutoSuggest(document.getElementById("eventvenue"),venues); </script> <label for="eventdate" accesskey="d" ><span>Event Date</span> <input type="text" name="eventdate" id="eventdate" value="<?php echo $_SESSION['eventdate'] ?>" size="32" maxlength="30" /></label> <label for="eventgenre" accesskey="g" ><span>Event Genre</span> <select name="eventgenre" id="eventgenre"> <option value="none">--select one--</option> <option value="HipHop">Hip-Hop</option> <option value="Funk">Funk</option> <option value="Soul">Soul</option> <option value="Metal">Metal</option> <option value="Punk">Punk</option> <option value="Blues">Blues</option> <option value="Jazz">Jazz</option> <option value="Trance">Trance</option> <option value="Breaks">Breaks</option> <option value="Electro">Electro</option> <option value="House">House</option> <option value="DNB">Drum'N'Bass</option> <option value="Dubstep">Dubstep</option> <option value="Lounge">Lounge</option> <option value="Top40">Top 40</option> </select> </label> <label for="eventprice" accesskey="p" ><span id="eventprice">Event Price</span> <input type="text" name="eventprice" id="eventprice" value="<?php echo $_SESSION['eventprice'] ?>" size="6" maxlength="4"/></label> <label for="eventpromoter" accesskey="c" ><span id="eventpromoter">Event Promoter</span> <input type="text" name="eventpromoter" id="eventpromoter" value="<?php echo $_SESSION['eventpromoter'] ?>" size="25" maxlength="23"/></label> <label for="eventflyer" accesskey="f" ><span id="eventflyer">Event Flyer (jpg or png MAX 300kb)</span> <input type="file" name="eventflyer" id="eventflyer" value="<?php echo $_SESSION['eventflyer'] ?>" size="25" maxlength="23"/></label> <input type="button" name="Reset" value="Reset" onclick="ResetForm();"> <input type="button" name="Submit" value="Submit" onsubmit="return validateForm(this);" onclick="SubmitForm(); return false; " > </fieldset> </form> <script language="javascript"> // set the selection box values... var form = document.forms[0]; form.eventgenre.selectedIndex = parseInt("<?php echo $_SESSION['eventgenre_sel'] ?>"); </script> And this is the server-side code. <?php $debug = FALSE; /************************************************************ Adjust the headers... ************************************************************/ header("Expires: Thu, 17 May 2001 10:17:17 GMT"); // Date in the past header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header ("Pragma: no-cache"); // HTTP/1.0 /***************************************************************************** Check the session details. we will store all the post variables in session variables this will make it easier to work with the verification routines *****************************************************************************/ session_start(); if (!isset($_SESSION['SESSION'])) require_once( "include/session_init.php" ); $arVal = array(); require_once("include/session_funcs1.php"); reset ($_POST); while (list ($key, $val) = each ($_POST)) { if ($val == "") $val = "NULL"; $arVals[$key] = (get_magic_quotes_gpc()) ? $val : addslashes($val); if ($val == "NULL") $_SESSION[$key] = NULL; else $_SESSION[$key] = $val; if ($debug) echo $key . " : " . $arVals[$key] . "<br>"; } /********************************************************************************************** Make sure session variables have been set and then check for required fields otherwise return to the registration form to fix the errors. **********************************************************************************************/ // check to see if these variables have been set... if ((!isset($_SESSION["eventname"])) || (!isset($_SESSION["eventvenue"])) || (!isset($_SESSION["eventdate"])) || (!isset($_SESSION["eventgenre"])) || (!isset($_SESSION["eventprice"])) || (!isset($_SESSION["eventpromoter"])) || (!isset($_SESSION["eventflyer"]))) { resendToForm("?flg=red"); } // form variables must have something in them... if ($_SESSION['eventname'] == "" || $_SESSION['eventvenue'] == "" || $_SESSION['eventdate'] == "" || $_SESSION['eventgenre'] == "" || $_SESSION['eventprice'] == "" || $_SESSION['eventpromoter'] == "" || $_SESSION['eventflyer'] == "") { resendToForm("?flg=red"); } // make sure fields are within the proper range... if (strlen($_SESSION['eventname']) > 35 || strlen($_SESSION['eventvenue']) > 35 || strlen($_SESSION['eventdate']) > 35 || strlen($_SESSION['eventgenre']) > 35 || strlen($_SESSION['eventprice']) > 35 || strlen($_SESSION['eventpromoter']) > 35 || strlen($_SESSION['eventflyer']) > 35 ) { resendToForm("?flg=white"); } /********************************************************************************************** Insert into the database... **********************************************************************************************/ $query = "INSERT INTO td_events (seventname, seventvenue, seventdate, seventgenre, seventprice, seventpromoter, seventflyer) " ."VALUES (".$arVals['eventname'].", ".$arVals['eventvenue'].", ".$arVals['eventdate'].", ".$arVals['eventgenre'] .", ".$arVals['eventprice'].", ".$arVals['eventpromoter'].", ".$arVals['eventflyer'].")"; //echo $query; $result = mysql_query($query) or die("Invalid query: " . mysql_error() . "<br><br>". $query); $insertid = mysql_insert_id(); /*** This following function will update session variables and resend to the form so the user can fix errors ***/ function resendToForm($flags) { reset ($_POST); // store variables in session... while (list ($key, $val) = each ($_POST)) { $_SESSION[$key] = $val; } // go back to the form... //echo $flags; header("Location: ./user_registration.php".$flags); exit; } ?> <p>SUCCESS!<br> The event was entered in the database!<br> You probably want to redirect to a thank you page or send an email to the user for confirmation.<br> <br> <br> Here are the variables...<br> <?php reset ($arVals); while (list ($key, $val) = each ($arVals)) { echo $key . " : " . $arVals[$key] . "<br>"; } echo "<br><br>The SQL Statment was:<br>"; echo $query."<br><br><br><br>"; ?> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <?php /********************************************************************************************** CREATES THUMBNAIL **********************************************************************************************/ //define a maxim size for the uploaded images define ("MAX_SIZE","1024"); // define the width and height for the thumbnail // note that theese dimmensions are considered the maximum dimmension and are not fixed, // because we have to keep the image ratio intact or it will be deformed define ("WIDTH","500"); define ("HEIGHT","650"); // this is the function that will create the thumbnail image from the uploaded image // the resize will be done considering the width and height defined, but without deforming the image function make_thumb($img_name,$filename,$new_w,$new_h) { //get image extension. $ext=getExtension($img_name); //creates the new image using the appropriate function from gd library if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext) || !strcmp("JPG",$ext)) $src_img=imagecreatefromjpeg($img_name); if(!strcmp("png",$ext) || !strcmp("PNG",$ext)) $src_img=imagecreatefrompng($img_name); //gets the dimmensions of the image $old_x=imageSX($src_img); $old_y=imageSY($src_img); // next we will calculate the new dimmensions for the thumbnail image // the next steps will be taken: // 1. calculate the ratio by dividing the old dimmensions with the new ones // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable // and the height will be calculated so the image ratio will not change // 3. otherwise we will use the height ratio for the image // as a result, only one of the dimmensions will be from the fixed ones $ratio1=$old_x/$new_w; $ratio2=$old_y/$new_h; if($ratio1>$ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; } // we create a new image with the new dimmensions $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h); // resize the big image to the new created one imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); // output the created image to the file. Now we will have the thumbnail into the file named by $filename if(!strcmp("png",$ext)) imagepng($dst_img,$filename); else imagejpeg($dst_img,$filename); //destroys source and destination images. imagedestroy($dst_img); imagedestroy($src_img); } // This function reads the extension of the file. // It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } // This variable is used as a flag. The value is initialized with 0 (meaning no error found) // and it will be changed to 1 if an error occurs. If the error occurs the file will not be uploaded. $errors=0; // checks if the form has been submitted if(isset($_POST['Submit'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['eventflyer']['name']; // if it is not empty if ($image) { // get the original name of the file from the clients machine $filename = stripslashes($_FILES['eventflyer']['name']); // get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); // if it is not a known extension, we will suppose it is an error, print an error message // and will not upload the file, otherwise we continue if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "JPG") && ($extension != "PNG") && ($extension != "png")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } else { // get the size of the image in bytes // $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which // the uploaded file was stored on the server $size=getimagesize($_FILES['eventflyer']['tmp_name']); $sizekb=filesize($_FILES['eventflyer']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($sizekb > MAX_SIZE*500) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=$filename; //the new name will be containing the full path where will be stored (images folder) $newname="flyers/".$image_name; $copied = copy($_FILES['eventflyer']['tmp_name'], $newname); //we verify if the image has been uploaded, and print error instead if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { // the new thumbnail image will be placed in images/thumbs/ folder $thumb_name='flyers/thumb_'.$image_name; // call the function that will create the thumbnail. The function will get as parameters // the image name, the thumbnail name and the width and height desired for the thumbnail $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} //If no errors registred, print the success message and show the thumbnail image created if(isset($_POST['Submit']) && !$errors) { echo "<h1>Thumbnail created Successfully!</h1>"; echo '<img src="'.$thumb_name.'">'; } ?> Hi Can some steer me in the right direction. I am having issues subtotaling 2 session variables: <td>'.$_SESSION['itemqty'][$key].'*'.$_SESSION['itemprice'][$key].'</td> Can you advise if I am doing this right? Cheers they recently reset my website so my php.ini file has been adjusted. One of my sites is no longer passing a session variable to the next page. I am sure its one of the settings being reset. here is the data from my phpinfo file. Anything that looks off to anyone? session Session Support enabled Registered save handlers files user sqlite Registered serializer handlers php php_binary wddx Directive Local Value Master Value session.auto_start Off Off session.bug_compat_42 On On session.bug_compat_warn On On session.cache_expire 180 180 session.cache_limiter nocache nocache session.cookie_domain no value no value session.cookie_httponly Off Off session.cookie_lifetime 0 0 session.cookie_path / / session.cookie_secure Off Off session.entropy_file no value no value session.entropy_length 0 0 session.gc_divisor 100 100 session.gc_maxlifetime 1440 1440 session.gc_probability 1 1 session.hash_bits_per_character 4 4 session.hash_function 0 0 session.name PHPSESSID PHPSESSID session.referer_check no value no value session.save_handler files files session.save_path /home/users/web/b535/ipw.plevtech/public_html/cgi-bin/tmp /home/users/web/b535/ipw.plevtech/public_html/cgi-bin/tmp session.serialize_handler php php session.use_cookies On On session.use_only_cookies Off Off session.use_trans_sid 0 0 Say I have a dropdown menu consisting of user specific options. I need to be able to set a session variable depending on the option chosen & then re-access it on the following page. Can someone give me a crash course on how to utilize session variables? ...anyone know anything about Internet Explorer not printing values from session variables. It works on Firefox but not on Internet Explorer. The session variable value works find on the web page but click on Print preview and it dissapears and will not print. Hi. I'm brand new to this forum, so sorry if I do something wrong... I'm someone who has thought myself to code in php to add dynamic objects to my basic static websites. I have had no formal education. This is not my first project however. I'm having problems with session variables working fine up to a point when I call a new file and then all my session variables are lost. I have tried everything, but cannot keep them alive when I get into this or any other new file. I display a form, get user data submitted, then display a next form and after the user submits this next form all the session variables are lost. Anyone have any idea what is killing my session variables? Thanks in advance. 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 everyone and thanks in advance for the help. I am working on a permission system for a site I am creating that will be used to restrict access to various areas of the site. I have a table with all the permission that is linked to a group that the user is a member of. I then use a query to get a list of the permission ids the user is part of and put those into the session array. I used a basic login script I found online I planned on modifying to add my own features and to make more secure. Originally it had just a member id and member name variable in the session array saved in the login script which are both working fine after login. I am using a dynamic variable to set one session variable for each permission with the id being the changing part in the variable name. The problem I found is that the new variables are not being set. When i removed the redirect from my login script so I could check the problem I found that the temp variable, which is also set before it saves to the session array, is blank as well. If I hit refresh on my browser the new variables become set and all is well. I was talking to nvee in irc chat who said I need to make a function on the page I am redirected to that checks if the variable exists. I looked through the original code of the login script I am using and found that this seems to be how they did it as well so I added an if statement to my index page to check if the variable has a value with and without using if isset. In both cases the new variable is still not getting set. He also gave me some pointers to help make my login checks more secure but the main thing IM concerned with right now is to make my new permission variables accessible to the session. My login script is available in my pastebin. I have a PHP page that offers various information from a single text file. This text file is encrypted on the server HD. Upon initial entry into the page, the user enters an encryption/decryption KEY and the encrypted file is decrypted to clear text and it is available for viewing. I have some parameters that I store in PHP session variables. I do this since various subsequent actions by the user will require these parameters. The code is written and the whole process seems to work well. Since the info in these session variables is sensitive, I need to understand WHERE they are stored. I know that it is a file on the HD, but after hours of reading the PHP Manual on sessions, I am not finding where (HD directory) that storage is. I have a typical shared hosting account for my web site. Mostly I want to discover is, are the session variables in y User/file hierarchy, or are they stored in a system area where the PHP is installed. Whew. Sorry this was so long.
Thank you, I have created a test account in my database with a user level of -1 and i think my code might be wrong but i am hoping someone can spot where i have gone wrong as i cannot, also a similar problem with another session variable loggedIn this is what i get when i login this is on the index page.
Notice: Undefined index: loggedIn in C:\xampp\htdocs\Login\index.php on line 11 Notice: Undefined index: loggedIn in C:\xampp\htdocs\Login\index.php on line 17 You must be logged in to view this page!Index page source code: <?php session_start(); error_reporting(E_ALL | E_NOTICE); ini_set('display_errors', '1'); require 'connect.php'; if($_SESSION['loggedIn'] == 1) { //Do Nothing exit(); } else if($_SESSION['loggedIn'] != 1) { echo "You must be logged in to view this page!"; exit(); } if($_SESSION['user_level'] == -1) { header("Location: banned.php"); } if(isset($_SESSION['username'])) { echo "<div id='welcome'> Welcome, ". $_SESSION['username'] ." <br> </div> "; } ?>Also if you need my login source code: <?php error_reporting(E_ALL | E_NOTICE); require 'connect.php'; session_start(); if (isset($_POST['submit'])) { $username = trim($_POST['username']); $password = trim($_POST['password']); if (empty($username)) { echo "You did not enter a username, Redirecting..."; echo "<meta http-equiv='refresh' content='2' URL='login.php'>"; exit(); } if (empty($password)) { echo "You did not enter a password, Redirecting..."; echo "<meta http-equiv='refresh' content='2' URL='login.php'>"; exit(); } //Prevent hackers from using SQL Injection to hack into Database $username = mysqli_real_escape_string($con, $_POST['username']); $password = mysqli_real_escape_string($con, $_POST['password']); $result = $con->query("SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'"); $row = $result->fetch_array(); $user_level = $row['user_level']; // check to make sure query did execute. If it did not then trigger error use mysqli::error to see why it failed if($result->num_rows > 0) { //Set default user $_SESSION['loggedIn'] == 1; $_SESSION['user_level'] == 1; $_SESSION['username'] == trim($_POST['username']); header("Location: index.php"); exit(); } else if($row['user_level'] == 1) { $_SESSION['user_level'] == 1; //Location admin header("Location: admin.php"); exit(); } else if($row['user_level'] == -1) { $_SESSION['user_level'] == -1; $_SESSION['username'] == trim($_POST['username']); //Location banned header("Location: banned.php"); exit(); } else if($_SESSION['loggedIn'] == true) { //Location default user home page header("index.php"); } else { echo "Invalid Username/Password"; } //Kill unwanted session } if(isset($_POST['killsession'])) { session_destroy(); echo "<br> <br> The Session Destroyed. (Basically means you have been logged out)"; exit(); } ?>I appreciate all help Hi, I am facing problems in destroying the session variables in my logout file .I have used session_id() in my php files for ex $sid = session_id().Now when I click on logout I naviagte to my index file but the session variable $sid still remain.I have chkd it.I have kept session_start() function in a file and I am including that file in every php by require_once function.The file is palced in Includes folder..is it causing the problem?? please help me out Also can I use session_start() more than once in a single php file? My logout file is : <?php session_start(); session_destroy(); header("location:index.php"); exit(); ?> Question about variable variables and using session variables for them. O.K. So if I have: $foo = 3; $_SESSION['bar'] = "foo"; $$_SESSION['bar'] should equal the value of $foo, however I can't get it to work. Can someone tell me what I am doing wrong..... is it formatting??? Thanks, Thomas About to pull my hair out. Looks simple, I think it's simple, but something is not behaving. I have a simple login page (loginpage.php) which checks a database for the FamilyID and Password, if it is a match, then it redirects them to userspage.php. I eventually want to use the FamilyID as a filter for my database so I only show the stuff relative to that FamilyID. Using CS5 and the built in functions, and it looks to me that the session variable 'MM_Username' should contain the FamilyID which is "adminid" in my database. It appears to work since it sends me to my userspage.php when I enter a valid FamilyID and Password, but it will not show me my session variable on the that page!!! PLEASE PLEASE HELP...Slap me in the face if it's a stupid question, but I have spent WAY too much time trying to figure what is wrong. I have included my code: CODE FOR LOGINPAGE.PHP <?php require_once('Connections/MyTest.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } ?> <?php // *** Validate request to login to this site. if (!isset($_SESSION)) { session_start(); } $loginFormAction = $_SERVER['PHP_SELF']; if (isset($_GET['accesscheck'])) { $_SESSION['PrevUrl'] = $_GET['accesscheck']; } if (isset($_POST['familyid'])) { $loginUsername=$_POST['familyid']; $password=$_POST['password']; $MM_fldUserAuthorization = ""; $MM_redirectLoginSuccess = "userspage.php"; $MM_redirectLoginFailed = "loginpage.php"; $MM_redirecttoReferrer = false; mysql_select_db($database_MyTest, $MyTest); $LoginRS__query=sprintf("SELECT adminid, password FROM `admin` WHERE adminid=%s AND password=%s", GetSQLValueString($loginUsername, "int"), GetSQLValueString($password, "text")); $LoginRS = mysql_query($LoginRS__query, $MyTest) or die(mysql_error()); $loginFoundUser = mysql_num_rows($LoginRS); if ($loginFoundUser) { $loginStrGroup = ""; if (PHP_VERSION >= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();} //declare two session variables and assign them $_SESSION['MM_Username'] = $loginUsername; $_SESSION['MM_UserGroup'] = $loginStrGroup; if (isset($_SESSION['PrevUrl']) && false) { $MM_redirectLoginSuccess = $_SESSION['PrevUrl']; } header("Location: " . $MM_redirectLoginSuccess ); } else { header("Location: ". $MM_redirectLoginFailed ); } } ?> <!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>Untitled Document</title> </head> <body> <form id="form1" name="form1" method="POST" action="<?php echo $loginFormAction; ?>"> <p> <label for="familyid">FamilyID:</label> <input type="text" name="familyid" id="familyid" /> </p> <p> <label for="password">Password:</label> <input type="text" name="password" id="password" /> </p> <p> <input type="submit" name="Submit" id="Submit" value="Submit" /> </p> </form> </body> </html> CODE FOR USERSPAGE.PHP <?php if (!isset($_SESSION)) { session_start(); } ?> <!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>Untitled Document</title> </head> <body> <strong>YOU MADE IT! </strong> <?php echo $_SESSION['MM_Username']; ?> </body> </html> THANKS IN ADVANCED!!! Hello all, I just wrote a php website to communicate with a database and it has a login based on the users email and password, they login on the first page and then the php checks for every page they visit if they indeed logged in before and not just found out what php file to open to get where they want to be. For this I used session variables to store both e-mail and password. The login info gets posted from the 1st(login) site to the 2nd site where it is checked for the first time, after that the login info isn't posted to the next page anymore, but just checked, this works for the 3rd page but when the user hits for the 4th page the variables are lost(I can't echo them either). However if I'd go from the 2nd page directly to the 4th page the page will load, however the 5th will then get my security-msg. So offcourse, I am wondering how this might have happened and how to fix this problem, here's some of the code I wrote: This is the check for the logininfo: <?php include('SessionStart.php'); include('logindata.php'); $db = mysql_connect($host, $user, $pw); if (!$db) { echo "<br />Helaas, u heeft geen verbinding met de database."; exit(); } else { mysql_select_db("teammanagementtool", $db); $sql24 = "SELECT * FROM leidinggevenden"; $allesarray = mysql_query($sql24); $i = 0; while ($mails = mysql_fetch_array($allesarray)) { $mailtjes[$i] = $mails['lg_mailadres']; $i = $i+1; } echo "...".$_SESSION['sessie']['email']."...".$_SESSION['sessie']['password']."...".$session_name."..."; if (in_array($_SESSION['sessie']['email'],$mailtjes)) { $sql25 = "SELECT lg_wachtwoord FROM leidinggevenden WHERE lg_mailadres = '".$_SESSION['sessie']['email']."'"; $pass = mysql_query($sql25); $pasje = mysql_fetch_array($pass); if ($_SESSION['sessie']['password'] != $pasje['lg_wachtwoord']) { echo "<script>alert('U bent hier op incorrecte manier terecht gekomen!');</script>"; echo "<meta http-equiv='refresh' content='0;URL=index.php' />"; exit(); } else if ($_SESSION['sessie']['password'] = "" || $_SESSION['sessie']['email'] = ""){ echo "<script>alert('U bent hier op incorrecte manier terecht gekomen!');</script>"; echo "<meta http-equiv='refresh' content='0;URL=index.php' />"; exit(); } else { } } else { echo "<script>alert('U bent hier op incorrecte manier terechtgekomen!');</script>"; echo "<meta http-equiv='refresh' content='0;URL=index.php' />"; exit(); } ?> And this is the code in my SessionStart.php: <?php $session_name = 'sessie'; $session_exp_time = 10000 ; $previous_name = session_name($session_name); ini_set('session.gc_maxlifetime', $session_exp_time); ini_set('session.gc_probability', '1'); ini_set('session.gc_divisor', '1000'); ini_set('session.name', $session_name); ini_set('session.cookie_domain', ''); ini_set('session.cookie_lifetime', 0 ); session_set_cookie_params($session_exp_time, '/', ''); session_start(); if (isset($_COOKIE[$session_name])) setcookie($session_name, $_COOKIE[$session_name], 2147483647 , ''); ?> the includes are at the start of all of my pages, I only do a session_unset() at my index.php(the login page). and my 2nd page gets: $_SESSION['sessie']['email'] = $_POST['email']; $_SESSION['sessie']['password'] = $_POST['password']; from the login. I could really use some help here, thanks in advance. I have some difficulty identifying why the session variables' values have disappeared in my PHP code. When I try to echo their values, nothing shows up and when I try to compare the values, it does not work.
There are no error messages to indicate something has gone wrong?
Can someone assist?
Attached Files
x.txt 6.29KB
1 downloads Is there a way to use extract to make session variables? If so how would you go about doing it? I am finally making the upgrade from PHP 5.3 to PHP 7.3. When converting over the code I noticed that session some sessions are not being processed. My test code for this is below:
session_start(); include ("../includes/connect.inc"); echo "hiiiiiiii: ".$currentDate; echo "He ".$_SESSION['user']; if (isset($_SESSION['user'])) { $user = $_SESSION['user']; $currentDate = date("Y/m/d"); } else { echo "Session not started: "; }
My include is listed below: $link = mysqli_connect('localhost', 'root', ''); if (!$link) { die('Could not connect: ' . mysql_error("Connection error message")); } mysqli_select_db($link, 'dbname') or die (mysqli_error($link)); date_default_timezone_set('America/Chicago'); define ("TZ_CORRECTION", 43200); $bkcolor = "#FFFFFF"; $currentDate = (Date("Y-m-d")); I am not getting the message "Session not started or the current date from the include". If it matters I am using WAMP as my testing server Any help is greatly appreciated. Hi, I'm having a wierd problem related to session variables. It looks like variables would get duplicated inside same session, which of course should not be possible. Background: This problem exists on one page script which creating a quote request system where users can select different products and get quote for those. Quote system creates quote ID per customer and all products selected in one session should go under the same quote ID. Problem is that sometimes when user selects products second quote ID is created and after that products are randomly added into both of quotes. While trying to solve this problem I added simple logs to see what's going on, those are added below. Problem seems to be caused by duplicated session variables. At somepoint it looks like session variables are not defined any more and new quote ID is created. After that the old and new session variables seems to be used randomly. To demonstrate the problem I added session variable called 'counter' which is defined if it does not exist and incremented always when page is reloaded by submitting the form. As you can see from below logs the 'counter' variable seems to have duplicate values, see the quote value to separate two different session variable "sets". <?php session_start(); echo "\n Current session id: ".session_id(); echo "\n _SESSION['quote']: ".$_SESSION['quote']; $_SESSION['counter'] = isset($_SESSION['counter'])? $_SESSION['counter'] +1 : 0; echo "\n _SESSION['counter']: ".$_SESSION['counter']; Output when page is reloaded(form submitted): Current session id: r5i15u4s9e20ud4j6jke8ln376 $_SESSION['quote']: $_SESSION['counter']: 0 set _SESSION['quote']: 984 Current session id: r5i15u4s9e20ud4j6jke8ln376 $_SESSION['quote']: $_SESSION['counter']: 0 set _SESSION['quote']: 985 Current session id: r5i15u4s9e20ud4j6jke8ln376 $_SESSION['quote']: 985 $_SESSION['counter']: 1 Current session id: r5i15u4s9e20ud4j6jke8ln376 $_SESSION['quote']: 985 $_SESSION['counter']: 2 Current session id: r5i15u4s9e20ud4j6jke8ln376 $_SESSION['quote']: 984 $_SESSION['counter']: 1 Current session id: r5i15u4s9e20ud4j6jke8ln376 $_SESSION['quote']: 985 $_SESSION['counter']: 3 Current session id: r5i15u4s9e20ud4j6jke8ln376 $_SESSION['quote']: 984 $_SESSION['counter']: 2 Could anyone explain how the 'counter' can behave such way inside same session (based on session ID)? This is far beyond my knowledge and I would highly appreciate any advice or tip how to solve this porblem. Thanks. BestRegards, Laowai I am having probelm in saving Session variables ALthough I'm writing session_start(); in the header of my php script and saving the values of Session array in the next page. It does not print the values or show right results. Code: [Select] session_start(); require_once ("functions.php"); $token=$_GET['t']; if(!isset($token)){ $name = stripslashes($_POST['username']); $email = stripslashes($_POST['email']); check_validate_input($name, $email); } if($token=='register') { show_registration_form(); } $my_model = new model(); $arr_info = $my_model->check_members($name,$email); if (($arr_info==NULL)&&($token!='register')) { echo '<p> Hello Guest</p><br />'; show_mailing_form(); } else if (($arr_info['role']=='user')||($arr_info['role'] == 'admin')) { $_SESSION['userId']=$arr_info['id']; $_SESSION['user_role']=$arr_info['role']; $_SESSION['user_name']=$arr_info['name']; print_r ($_SESSION);} here it does not print session array. Hello everyone, I'm sitting here in a position where I can't work on my site or test any code, but my mind is racing about what I can do to solve a particular problem that I have. I won't get into the problem because it would take more time to type than I have right now, but I have an idea for a simple solution, just not sure if it will work or not. So, here's my question: Is it possible to have multiple session variables during a session? Such as: $email=$_SESSION['email']; $user=$_SESSION['userid']; If this is possible, my problem is solved (I think)... otherwise, I have to keep thinking about it. Thanks for any help! |