PHP - Issues With Unsetting Session Arraykey
HI, I'm having trouble with unsetting a key from SESSION. I can unset the cart, but when I try to target the key, it doesn't work.
Are there some regular things I should be looking for? The only thing I can think of is that I'm re-initializing the key by accident elsewhere in my code. if(isset($_POST['mainCartDelete'])){ unset($_SESSION['cart_array'][21]); $sessionArray = $_SESSION['cart_array']; print_r ($sessionArray); }Print_r returns Array ( [0] => Array ( [item_id] => 21 [quantity] => 1 ) ) Edited by 7blake, 10 December 2014 - 01:43 PM. Similar TutorialsI have a shopping cart, and I am using a php session to track the basket. All works fine, the only problem I have is completely removing the session once the order is placed. The user places the order, goes through the process and then once complete are sent back to a page called order complete. I have placed the following at the very top of this file: session_start(); session_unset(); session_destroy(); At first it looks as if the session is destroyed, but when I add an item to the basket it pulls up the item I previously ordered. Is the above the correct way? The session is only the sid? I'm teaching myself a bit of OOP in php. found that i could pass an object into the SESSION array if i serialize() the object and then unserialize() it where i need it in other page files. all seems to work well until it comes time for a user to logout from my application and attempt to destroy the session. at times, when they log back in, this serialized SESSION value seems to still be set while other SESSION values have been cleared. at least i *thinnk* this is what is going on.
in my logout handler, i have the following:
$_SESSION = array(); // clear all SESSION vars setcookie(); // clear cookies session_destroy();but the above does not seem to be working. my guess is there is something native to serialized SESSION values that im not yet aware of. any help here would be much appreciated. This topic has been moved to Application Frameworks. http://www.phpfreaks.com/forums/index.php?topic=353397.0 I am using session variables to keep track of what is in a shopping cart. I can add the items to the cart quite easily enough. But my problem is that I can't delete a specific item in the cart. Below is a summary of what the array looks like $Item1=array("ProdID"=>"Hat","Color"=>"Not Needed","Size"=>5); $Item4=array("ProdID"=>"Shirt","Color"=>"Green","Size"=>"L"); $Item2=array("ProdID"=>"Pants","Color"=>"Not Needed","Size"=>"32x32"); $Item3=array("ProdID"=>"Socks","Color"=>"Not Needed","Size"=>"Not Needed"); $NumItems=4; $TestArray=array("NumItems"=>$NumItems,1=>$Item1,2=>$Item2,3=>$Item3,4=>$Item4); However when I attempt to delete any of the top level elements (1,2,3,4,NumItems), I either end up deleting only the last element (4) or somehow taking out 2 of them. I know that this must be an easy fix but I've looked at it for so long that I can't seem to figure out what the problem is. below is the code that I use to delete the Item from the array Code: [Select] $ItemNum=$_GET['item']; if ($ItemNum=="All"){ $ItemNum=$_GET['item']; if ($ItemNum=="All"){ unset($TestArray); unset($TestArray['NumItems']); unset($_SESSION['OrderTotal']); //header("Location:Cart.php?act=view"); } else{ $TestArray['NumItems']=$TestArray['NumItems']-1; if($TestArray['NumItems']<1) { unset($_SESSION['OrderTotal']); unset($TestArray); unset($TestArray['NumItems']); } else { unset($TestArray[$ItemNum]); } Can anyone take a look at this and point me in the correct direction? What I am after is to delete any element of the top array and keep the rest. so im developing a WEB GAME etc.... etc.... and im including a page that has functions on it in another page if that makes sense....<br> so here's my code tell me why i cant get theese array values to clear? Code: [Select] function unlockables(){ // restore the content $unlockables = array( 'ach'=>array( // achevements unlockables md5(0)=>array('key'=>md5(0),'title'=>'novice','cash'=>'1000', 'exp'=>'100000', 'lvl'=>'20'), md5(1)=>array('key'=>md5(1),'title'=>'rookie','cash'=>'5000', 'exp'=>'150000', 'lvl'=>'40'), md5(2)=>array('key'=>md5(2),'title'=>'pro','cash'=>'10000', 'exp'=>'250000', 'lvl'=>'60'), md5(3)=>array('key'=>md5(3),'title'=>'king','cash'=>'50000', 'exp'=>'500000', 'lvl'=>'80'), md5(4)=>array('key'=>md5(4),'title'=>'Morphelo','cash'=>'100000','exp'=>'1000000','lvl'=>'100'), ), 'levels'=>array( // lvl up md5(5)=>array('key'=>md5(5),'price'=>'1000', 'lvlup'=>'1'), md5(6)=>array('key'=>md5(6),'price'=>'4000', 'lvlup'=>'5'), md5(7)=>array('key'=>md5(7),'price'=>'7500', 'lvlup'=>'10'), md5(8)=>array('key'=>md5(8),'price'=>'15000', 'lvlup'=>'25'), md5(9)=>array('key'=>md5(9),'price'=>'25000', 'lvlup'=>'50') ), 'exp'=>array( // exp up md5(10)=>array('key'=>md5(10),'price'=>'100','expup'=>'500'), md5(11)=>array('key'=>md5(11),'price'=>'1000','expup'=>'6000'), md5(12)=>array('key'=>md5(12),'price'=>'10000','expup'=>'75000'), md5(13)=>array('key'=>md5(13),'price'=>'50000','expup'=>'375000'), md5(14)=>array('key'=>md5(14),'price'=>'100000','expup'=>'750000') ) ); if($_COOKIE['lvl'] >= 0 && $_COOKIE['lvl'] < 20) { // first snakes $status = 'fs'; }elseif($_COOKIE['lvl'] >= 20 && $_COOKIE['lvl'] < 40){ // Novice $status = 'novice'; }elseif($_COOKIE['lvl'] >= 40 && $_COOKIE['lvl'] < 60){ // Rookie $status = 'rook'; }elseif($_COOKIE['lvl'] >= 60 && $_COOKIE['lvl'] < 80){ // pro $status = 'pro'; }elseif($_COOKIE['lvl'] >= 80 && $_COOKIE['lvl'] < 100){ // Novice $status = 'king'; }elseif($_COOKIE['lvl'] >= 100){ // Novice $status = 'morphelo'; } switch($status){ case 'novice': unset( $unlockables['ach'][md5(0)], $unlockables['ach'][md5(2)], $unlockables['ach'][md5(3)], $unlockables['ach'][md5(4)] ); break; case 'rook': unset( $unlockables['ach'][md5(0)], $unlockables['ach'][md5(1)], $unlockables['ach'][md5(3)], $unlockables['ach'][md5(4)] ); break; case 'pro': unset( $unlockables['ach'][md5(0)], $unlockables['ach'][md5(1)], $unlockables['ach'][md5(2)], $unlockables['ach'][md5(4)] ); break; case 'king': unset( $unlockables['ach'][md5(0)], $unlockables['ach'][md5(1)], $unlockables['ach'][md5(2)], $unlockables['ach'][md5(3)] ); break; case 'morphelo': unset($unlockables['ach']); break; } // here is were im trying print to screen but the array is still printing full print_r($unlockables['ach']); } Driving myself nuts...can't figure out what is wrong with this code. This is part of a pagination system that uses an array instead of hitting the db each time. I am using CodeLobster PHP version (3.7), Windows 7, and using a virtual server on my computer for development (XAMPP) the error I get is this: Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\website\searchinv.php on line 45 Warning: array_multisort() function.array-multisort: Argument #1 is expected to be an array or a sort flag in C:\xampp\htdocs\website\searchinv.php on line 49 Warning: array_slice() expects parameter 1 to be array, boolean given in C:\xampp\htdocs\website\searchinv.php on line 108 Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\website\searchinv.php on line 146 I am pasting the code below and point out each of the lines in the warnings above, and will try to clean up some so that it's not too extensive... Here is the problem: If I click on any of the "page" $_SESSION['rows'] has all the correct information contained in it. However, if I trigger the "re-sort" select option...$_SESSION['rows'] is empty...all my other $_SESSION variables are still there. At first I thought it was an issue with too many "if/ifelse/else" statements or a wrong syntax...so I changed it to a "switch" and traced it closely. I don't see anything wrong. Next I thought it was caused by the JavaScript "onchange" event...so I took that out...and replaced it with just a submit button...same result. I've done a search on the page for EVERY $_SESSION['rows'] and found only 4 and none of them should blank it out...I've been going crazy on this code for 2 days I'm pulling my hair out now...can ANYONE help? Code: [Select] if(!empty($_POST)) { if(empty($_POST['page'])) { switch($_POST) { case (!empty($_POST['ref'])): $deleted=sql_ending($_POST['del']); $rows=select_from_database('inventory', '*', 'ref_number=\''.$_POST['ref'].'\' and '.$deleted); break; case (!empty($_POST['type'])): $sort=$_POST['sort']; $deleted=sql_ending($_POST['del']); if($_POST['type']!='*') { $type=$_POST['type']; $len=strlen(trim($type)); if($len!=1) $type=$type.'-'; $end=$deleted.' and ref_number like \''.$type.'%\''; } else $end=$deleted; $rows=select_from_database('inventory', '*', $end, $sort); break; default: $data=$_SESSION['rows']; $sorts=explode(' ', $_POST['sort']); $keys=$sorts[0]; $order=$sorts[1]; Line 45 --> foreach ($data as $key => $row) { $column[$key]=$row[$keys]; } Line 49 --> $rows=array_multisort($column, $order, $data); break; } $_SESSION['rows']=$rows; } $x=count($_SESSION['rows']); if(isset($_SESSION['admin_user'])) $width=1280; else $width=900; $srch_rslt= ' <div id="displaybox"> <div id="translucent"></div> <div id="result" style="width:'.$width.'px;"> <!--[if lt IE 7]> <h3 class="center">This site looks much better with IE 7 and above. Please consider upgrading <a href="browsers.php">HERE</a>.</h3> <![endif]--> '; if($x==0) $srch_rslt.=' <h3>Search Result</h3> <a style="display: block; margin-right:10px;" href="searchinv.php" title="Close this box.">Close <img src="images/close.png" alt="Close this box." /></a> <p>We are sorry, but we currently do not have the equipment available for the given search. Please go back and <a href="searchinv.php" title="Search Again">search again</a>, or <a href="mailto:mywebsite@mywebsite.com" title="Send us an email so we can locate the equipment you need." onclick="popup(\'email.php?title=pray\', \'Request for Equipment\', 500, 500); return false">contact us</a> so we may begin to utilze are vast resources to locate your needs. </div> </div> '; else { if(empty($_POST['page'])) $pg=1; else $pg=$_POST['page']; $page=($pg-1)*20; $_SESSION['pages']=ceil($x/20); if(!$_SESSION['pages']>1) $buttons='<button type="button" class="active" title="Page 1">1</button> '; elseif($pg>1) { $prev_pg=$pg-1; $buttons='<button type="submit" class="button" title="First" value="1" name="page"><< First</button> <button type="submit" class="button" title="Previous" value="'.$prev_pg.'" name="page">< Prev</button> '; } for($i=1; $i<=$_SESSION['pages']; $i++) { if($i==$pg) $buttons.=' <button type="button" class="active" title="Page '.$pg.'">'.$pg.'</button> '; else $buttons.=' <button type="submit" class="button" title="Page '.$i.'" value="'.$i.'" name="page">'.$i.'</button> '; } if($pg<$_SESSION['pages']) { $next_pg=$pg+1; $buttons.=' <button type="submit" class="button" title="Next" value="'.$next_pg.'" name="page">Next ></button> <button type="submit" class="button" title="Last" value="'.$_SESSION['pages'].'" name="page">Last >></button> '; } Line 108 --> $results=array_slice($_SESSION['rows'], $page, 20, true); $srch_rslt.=' <h3>Search Complete!</h3> <a class="close" href="searchinv.php" title="Close this box.">Close <img style="border:none;" src="images/close.png" alt="Close this box." /></a> <p>You may now browse, re-sort and download your results in either PDF or an Excel format.</p> '; if (isset($_SESSION['admin_user'])) $table = 1260; else $table = 880; $tableinner = $table-20; $srch_rslt.=' <form name="search_page" method="post" action="searchinv.php?search='.$_POST['search'].'"> <div style="border:2px solid #00000; width:'.$table.'px;"> /* there's a table here */ '; $y=0; Line 146 --> foreach($results as $result) { $y++; $cl_type=explode('-', $result['ref_number']); $type=select_from_database('car_types', '*', 'abbvr=\''.$cl_type[0].'\''); $raw_notes=$result['notes']; if ($raw_notes == NULL) $notes="Call for additional information."; elseif (strlen($raw_notes) >65) { $txtlth=strpos($raw_notes, " ", 65); $notes=substr($raw_notes, 0, $txtlth).'<span id="para'.$pg.$y.'" class="jshide"> '.substr($raw_notes, $txtlth).'</span><a class="jsunhide" href="javascript:function(){};" onclick="toggleMe(\'para'.$pg.$y.'\', \'href'.$pg.$y.'\')" id="href'.$pg.$y.'" style="text-decoration: none">...[click for more]</a>'; } else $notes=$raw_notes; $srch_rslt.=' /*just some html output stuff */ $srch_rslt.=' </table> </div> <div> <input type="hidden" name="search" value="'.$_POST['search'].'" /> <p class="center"> '.$buttons.' </p> </div> </td> </tr> </table> </div> </form> <div class="search_menu_wrapper"> <ul class="sermenu"> <li>Need to search again? Back to the <a href="searchinv.php" title="Do another search.">search page</a>.</li> <li>Download this search to a <a href="http://www.mywebsitedowloadpdf.php?search='.$_POST['search'].'" title="Download to .pdf.">.pdf <img src="images/adobe.png" style="width:15px; height:15px; border:none;" alt="Download in Adobe PDF format." /></a></li> <li>Download this search to a <a href="http://www.mywebsitedowloadexcel.php?search='.$_POST['search'].'" title="Download to MS Excel.">MS Excel <img src="images/excel.png" style="width:15px; height:15px; border:none;" alt="Download in MS Excel format." /></a></li> </ul> </div> Like I said if I click a "page" button (stored in the $buttons var and printed above)...the code works beautifully...it's when the next lines (below) are triggered that cause $_SESSION['rows'] to be empty...I just don't get it Code: [Select] <div style="text-align:center;"> <form name="re_sort" method="post" action="searchinv.php?search='.$_POST['search'].'"> <label class="form-label-left" id="l_sort" for="sort">Re-Sort By:</label> <div class="form-input"> <select class="form-dropdown" style="width:190px" id="sort" name="sort" onchange="this.form.submit();"> <option value="ref_number SORT_ASC" selected="selected"> Reference Number - Ascending </option> <option value="ref_number SORT_DESC"> Reference Number - Descending </option> <option value="date_added SORT_ASC"> Date Added - Ascending </option> <option value="date_added SORT_DESC"> Date Added - Descending </option> <option value="last_update SORT_ASC"> Date Updated - Ascending </option> <option value="last_update SORT_DESC"> Date Updated - Descending </option> '; if($_SESSION['admin'] == 10) $srch_rslt.=' <option value="source SORT_ASC"> Source - Ascending </option> <option value="source SORT_DESC"> Source - Descending </option> '; $srch_rslt.=' </select><button type="submit" value="submit">Submit</button> </div> </form> </div> </div> </div> <script type="text/javascript" language="javascript"> //<![CDATA[ document.body.style.overflow="hidden"; //]]> </script> '; } } echo $srch_rslt; 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 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'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> 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. 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. This is weird. I thought session_destroy erased your session id: echo "session is ".session_id(); session_destroy(); echo "<br>session now is ".session_id(); When I run it i get: Code: [Select] session is mkqb0m49ktbtt1g34r6e67g012 session now is But when I reload the page I get the same thing! Code: [Select] session is mkqb0m49ktbtt1g34r6e67g012 session now is If session_id was destroyed (it echoed blank to prove this) why does it get repopultaed with the same session id when I reload the browser? giving me Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/enriquec/public_html/admincenter.php on line 6 this is my code Code: [Select] <?php require "header.php";?> <?php if ($_SESSION['username']) echo "Welcome, "."$_SESSION['username']."; else die("You must be logged in!"); ?> <?php require "footer.php":?> Code: [Select] <?php session_start(); if(!session_is_registered(myusername)){ header("location:./default.php"); } ?> My session works fine but I am just wondering how I can echo the current sessions username? Thanks Hi guys help please Code: [Select] foreach($_SESSION['cart'] as $id => $value){ } is this valid? im getting error Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\shopping cart\new_cart.php on line 48 Many thanks If i use session in my php code then for how much time the session will be valid... And how can i change the length of the session... 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; } ?> 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 |