PHP - Variable Session Variables
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 Similar TutorialsHello everyone, I can get Test 2 to successfully operate the if statement using a variable variable. But when I try the same method using a session variable (Test 1) the if statement is not executed. Please could you tell me why the if statement in Test 1 is not being executed? Code: [Select] <?php # TEST 1 $_SESSION[test_variable] = "abcd"; $session_variable_name = "_SESSION[test_variable]"; if ($$session_variable_name == "abcd") { echo "<br>line 373, abcd<br>"; } # TEST 2 $test_variable = "efgh"; $test_variable_name = "test_variable"; if ($$test_variable_name == "efgh") { echo "<br>line 379, efgh<br>"; } ?> Many thanks, Stu i have Created a Session with this code $_SESSION['USER_NAME'] = trim($_POST['username']) How can i access the $_SESSION['USER_NAME'] in other Pages ; and will this code for $var = $_SESSION[USER_NAME] can i get the SESSIOn value in " $var" variable ?? I have this simple while loop which retrieves data from a mysql query and displays several links on my homepage. I would like to avoid using the php get function and add query strings to my urls I am thinking of using session variables but I need help and I'm pretty sure this can't be done. When a visitor clicks a link from the several ones displayed by the while loop, that particular variable would be set in a session. In my code, the session will always send the last var Can this be done? Code: [Select] <? session_start(); // Start Session Variables $result = mysql_query("my query"); while($slice = mysql_fetch_assoc($result)){ $url = $slice['url']; $name = $slice['name']; ?> <a href="<? echo $url; ?>"><? echo $name; ?></a> <? } $_SESSION['name'] = $name; // Store session data ?> does anyone know how to decode this XML variable value into string values? I also need to know the oposite way: creating variable values into xml. I've tried several code examples but they did filter the requested data. Code: [Select] $xml='<?xml version="1.0" encoding="utf-8"?> <elements> <text identifier="ed9cdd4c-ae8b-4ecb-bca7-e12a5153bc02"> <value/> </text> <textarea identifier="a77f06fc-1561-453c-a429-8dd05cdc29f5"> <value><![CDATA[<p style="text-align: justify;">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>]]></value> </textarea> <textarea identifier="1a85a7a6-2aba-4480-925b-6b97d311ee6c"> <value><![CDATA[<p style="text-align: justify;">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>]]></value> </textarea> <image identifier="ffcc1c50-8dbd-4115-b463-b43bdcd44a57"> <file><![CDATA[images/stories/red/cars/autobedrijf.png]]></file> <title/> <link/> <target/> <rel/> <lightbox_image/> <width><![CDATA[250]]></width> <height><![CDATA[187]]></height> </image> <text identifier="4339a108-f907-4661-9aab-d6f3f00e736e"> <value><![CDATA[Kramer 5]]></value> </text> <text identifier="ea0666d7-51e3-4e52-8617-25e3ad61f8b8"> <value><![CDATA[6000 RS]]></value> </text> <text identifier="90a18889-884b-4d53-a302-4e6e4595efa0"> <value><![CDATA[Eindhoven]]></value> </text> <text identifier="410d72e0-29b3-4a92-b7d7-f01e828b1586"> <value><![CDATA[APK Pick up and return]]></value> </text> <text identifier="45b86f23-e656-4a81-bb8f-84e5ea76f71f"> <value><![CDATA[15% korting op grote beurt]]></value> </text> <text identifier="3dbbe1c6-15d6-4375-9f2f-f0e7287e29f3"> <value><![CDATA[Gratis opslag zomerbanden]]></value> </text> <text identifier="2e878db0-605d-4d58-9806-8e75bced67a4"> <value><![CDATA[Gratis abonnement of grote beurt]]></value> </text> <text identifier="94e3e08f-e008-487b-9cbd-25d108a9705e"> <value/> </text> <text identifier="73e74b73-f509-4de7-91cf-e919d14bdb0b"> <value/> </text> <text identifier="b870164b-fe78-45b0-b840-8ebceb9b9cb6"> <value><![CDATA[040 123 45 67]]></value> </text> <text identifier="8a91aab2-7862-4a04-bd28-07f1ff4acce5"> <value/> </text> <email identifier="3f15b5e4-0dea-4114-a870-1106b85248de"> <value/> <text/> <subject/> <body/> </email> <link identifier="0b3d983e-b2fa-4728-afa0-a0b640fa34dc"> <value/> <text/> <target/> <custom_title/> <rel/> </link> <relateditems identifier="7056f1d2-5253-40b6-8efd-d289b10a8c69"/> <rating identifier="cf6dd846-5774-47aa-8ca7-c1623c06e130"> <votes><![CDATA[1]]></votes> <value><![CDATA[1.0000]]></value> </rating> <googlemaps identifier="160bd40a-3e0e-48de-b6cd-56cdcc9db892"> <location><![CDATA[50.895711,5.955427]]></location> </googlemaps> </elements>'; My login script stores the user's login name as $_SESSION[ 'name'] on login. For some unapparent reason, i'm getting errors stating that $user and $priv are undefined variables, though I've attempted to define $user as being equal to $_SESSION['name'], using $user to look up the the user's privilege level (stored as the su column ) in the SQL table, and then where the result of the sql query is $priv which is then evaluated in an if statement. I can't seem to figure out why this might not be working. The code I'm using: <?php session_start(); function verify() { //verify that the user is logged in via the login page. Session_start has already been called. if (!isset($_SESSION['loggedin'])) { header('Location: /index.html'); exit; } //if user is logged in, we then lookup necessary privleges. $_SESSION['name'] was written with the login name upon login. Privleges // are written in db as a single-digit integer of of 0 for users, 1 for administrators, and 2 for special users. $user === $_SESSION['name']; //Connect to Databse $link = mysqli_connect("127.0.0.1", "database user", "password", "database"); if (!$link) { echo "Error: Unable to connect to MySQL." . PHP_EOL; echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL; echo "Debugging error: " . mysqli_connect_error() . PHP_EOL; exit; } //SQL Statement to lookup privlege information. if ($result = mysqli_query($link, "SELECT su FROM accounts WHERE username = $user", MYSQLI_STORE_RESULT)) { //LOOP TO CYCLE THROUGH SQL RESULTS AND STORE Privlege information as vairable $priv. while ($row = $result->fetch_assoc()) { $priv === $row["su"]; } } // close SQL connection. mysqli_close($link); // Verify privleges and take action. Only a privlege of "1" is allowed to view this page. A privlege of "2" indicates special //accounts used in other scripts that have certain indermediate additional functions, but are not trusted administrators. if ($priv !== 1) { echo $_SESSION['name']; echo "you have privlege level of $priv"; echo "<br>"; echo 'Your account does not have the privleges necessary to view this page'; exit; } } verify(); ?>
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 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. 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 ...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. 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? Hello! I'm a bit of a novice on PHP variables still and perhaps I'm trying to run before I can walk. I have an SQL database that I am able to successfully write to without any problems. I have also created a session variable for the user id number that I am able to retrieve on a later page. My problem is that I have hit a wall when it comes to retrieving the data from the database based upon the session variable user id. Here is my code and error: $_SESSION['ID_ASSIGNED']=$_POST[KSU_ID]; //this line takes the form data and successfully assigns it to the session variable on an earlier page echo $_SESSION['ID_ASSIGNED']; //that line works normally. Here's my problem code (the line starting with $result ). The line works fine if I input: $result = mysql_query("SELECT * FROM $usertable WHERE KSU_ID='some id number'");: <?php $result = mysql_query("SELECT * FROM $usertable WHERE KSU_ID=$_SESSION['ID_ASSIGNED']"); $row = mysql_fetch_array($result); echo "<br />Participant Number:"; echo $row['ID']; echo "<br />Name: "; echo $row['lname']; echo ", "; echo $row['fname']; echo "<br />Student Number:"; echo $row['KSU_ID']; echo "<br />Age: "; echo $row['age']; echo "<br />Gender: "; echo $row['gender']; echo "<br />Grade: "; echo $row['grade']; mysql_close($con); ?> 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 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 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. 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 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! 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 Hi Maybe a strange request and perhaps someone here knows a better way of doing what I want. I have a sign up form on my website that automatically pulls the session var 'name' and places this in the text field for "Reference". That way I know which agent signed up a customer. What I need to do now though is allow this variable to be injected through the url for click through banners. This what I've done (within the header HTML Tags): Code: [Select] if ($_GET['Reference'] == '') { $_SESSION['Name'] = $my->name; } else { $_SESSION['Name'] = $_GET['Reference']; } However, even though this is loaded on EVERY page view the variable is empty if the user clicks another page. Having some problems with PHP session i currently use cookies to log users in, but i have decided to use php session instead but i can get it to work, it simply dose not pass the variables unless include session id in every single link on my website, can anyone tell me where i am going wrong these are the session setting from php.in session.use_cookies = 1 session.use_only_cookies = 0 session.name = usersesid session.auto_start = 1 session.cookie_lifetime = 0 session.referer_check = 1 session.cache_expire = 180 session.use_trans_sid = 1 |