PHP - Newb Question On Php Sessions
Hi - I'm using SESSION variables to keep track of customers who come onto the site to order stuff. For example $_SESSION['customerid'] all the incoming customers.
I also use SESSION variables with a different value for the managers to look at and keep track of customer data. eg : $_SESSION['customer']['firstname'] I am expecting many customers and managers to be simultaneously using the site. QUESTION: Do I need to increment the SESSION variable in some way in order to avoid that a session gets overwritten, or will my SESSION variables keep track and keep everything separated by dint of the fact that they contain different values ? so far my testing shows that things are working correctly, but I can only test with 3 / 4 virtual users in different browser windows . Similar TutorialsHey i am doing a login and blog system i have done the login and reg part but i am having troubles with the adding post. Basically at the moment my user can make a post and they can anyone can view it, but i need to the user only be able to create there own prv post and that when anybody else logs in they cant make a post under it. Does anyone have any ideas? this is my code for the posts <?php session_start(); include('db_connect.php'); ?> Welcome to the fear blog <a href="logout.php">log out</a><hr/> <?php $sql = mysql_query("SELECT * FROM posts ORDER BY id "); while($row = mysql_fetch_array($sql)){ $title = $row['title']; $content = $row['content']; $category = $row['category']; ?> <div id="post"> <div id="wrapper"> <div id="title"> <label>Title</label> <?php echo $title; ?> </div> <div id="category"><label>category</label> <?php echo $category; ?> </div> <div id="content"> <label>Content</label><?php echo $content; ?> </div> </div> <?php } ?> <div id="contents"> <form action="post.php" method="post"> <label> Title:</label><input type="text" name="title" /><br/> <label> Category:</label><input type="text" name="category" /><br /> <label> Content:</label><textarea name="content"></textarea><br/> <input type="submit" name="submit" value="Post"/> </form> </div> </div> </div> </div> Hey guys havent coded in a while and im stumped. Ive checked google but to no avail lol i wanna include my config file and have an IF statement to run/include another file IE... <?php include("config/config.php"); If File(Not Exist); include("install/config.php"); ?> If someone can put me back on track it would be greatly epreciated I have set up a session for logins but not to sure if it is the best way to go about it. Seems to work but a little concerned with security. Can someone check it out and let me know what they think? Login page <?php session_start(); // starting session $fingerprint = md5($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT']); $_SESSION['last_active'] = time(); $_SESSION['fingerprint'] = $fingerprint; ?> <?php if( isset($_POST['submitLogin'])) { include('library/login.php'); login(); mysql_select_db('test'); $userID=$_POST["userID"]; $pswd=$_POST["pswd"]; $sql="SELECT * FROM user WHERE userID='$userID' and pswd='$pswd'"; $result=mysql_query($sql); while ($r=mysql_fetch_array($result)) { $exp_date=$r["exp_date"]; $todays_date=date("Y-m-d"); } // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $userID and $pswd, table row must be 1 row if($count==1) { $_SESSION['userID'] = $userID; if ($exp_date >= $todays_date) { // setting user session $_SESSION['logged_in'] = true; // billing is up to date echo "<meta http-equiv='refresh' content='0;url=testSession2.php'>"; } else { // setting user session $_SESSION['billing'] = true; // billing has expired echo "<meta http-equiv='refresh' content='0;url=nextSession.php'>"; } } else { // incorrect user/password echo " <div id='incorrect'>Please verify the username or password.</div> <form method='post' action='' name='login' id='login'> <div id='loginForm'> <fieldset> <span class='textbox'> <label for='username'>Username: </label> <input type='text' name='userID' size='25' class='cells' value='$userID'> <br><label for='pswd'>Password: </label> <input type='password' name='pswd' size='25'class='cells' value='$pswd'> <br><label for='pswd'> </label>Remember Me: <input type='checkbox' name='Remember' value='21'> <br><label for='blank'> </label><a href='resetPswd.php'>Forget Your Password? </a> <br><label for='blank'> </label><input type='image' value='Login' src='img/button_login.gif' width='64' height='25' onmouseover=\"javascript:this.src='img/button_login2.gif';\" onmouseout=\"javascript:this.src='img/button_login.gif';\"> <input type='hidden' name='submitLogin' value='true'> </span> </fieldset> </div> </form> "; } } else { // log in form echo " <form method='post' action='' name='login' id='login'> <div id='loginForm'> <fieldset> <span class='textbox'> <label for='username'>Username: </label> <input type='text' name='userID' size='25' class='cells'> <br><label for='pswd'>Password: </label> <input type='password' name='pswd' size='25'class='cells'> <br><label for='pswd'> </label>Remember Me: <input type='checkbox' name='Remember' value='21'> <br><label for='blank'> </label><a href='resetPswd.php'>Forget Your Password?</a> <br><label for='blank'> </label><input type='image' value='Login' src='img/button_login.gif' width='65' height='25' onmouseover=\"javascript:this.src='img/button_login2.gif';\" onmouseout=\"javascript:this.src='img/button_login.gif';\"> <input type='hidden' name='submitLogin' value='true'> </span> </fieldset> </div> </form> "; } ?> Right now I have it going to this page based of certain conditions of the users account. <?php session_start(); // If $timeout = 60 * 1; // In seconds, i.e. 30 minutes. $fingerprint = md5($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT']); session_start(); if ( (isset($_SESSION['last_active']) && $_SESSION['last_active']<(time()-$timeout)) || (isset($_SESSION['fingerprint']) && $_SESSION['fingerprint']!=$fingerprint) || isset($_GET['logout']) ) { setcookie(session_name(), '', time()-3600, '/'); session_destroy(); } session_regenerate_id(); $_SESSION['last_active'] = time(); $_SESSION['fingerprint'] = $fingerprint; ?> <?php // user will go here is they are not logged in if (!isset($_SESSION['billing'])) { // User is not logged in, so send user away. //header("Location:/singles/login.php"); echo "Sorry, you are not logged in."; die(); } // user will go here if logged in else { echo "Welcome: " .$_SESSION['userID']; "<br><Br>"; } ?> Using this tutorial http://en.wikibooks.org/wiki/PHP_Programming/User_login_systems Hello, On my site I offer the option an option for cookies or sessions on login. If a remember me box is selected, then a cookie will be set. My question is, how do I assign both the $_SESSION['id'] and $_COOKIE['id'] to the same variable? Thanks for the help! I'm almost embarrassed to ask such a simple question but I just cannot get this to work. I'm trying to figure out how to use sessions that takes the information from a form on the first page and displays it on the last. I have this on page 1: <?php session_start(); ?> <form action="test2.php" method="post"> <p>Page 1</p> <p>First Name <input type="text" name="first" /></p> <p><input type="submit" value="Next page 2" /></p> And this for page 2: <?php SESSION_START(); $_SESSION['first'] = $_POST['first']; echo $_SESSION['first'] = $_POST['first']; ?> <form action="test3.php" method="post"> <p>Page 2</p> <input type="submit" value="Next page 3" /> </form> And this for page 3: <?php SESSION_START(); $_SESSION['first'] = $_POST['first']; echo $_SESSION['first'] = $_POST['first']; ?> <p>Page 3</p> <p>You're done</p> I can get it to display on page 2 but not on page 3. Can anyone tell me why? I've been at this for a long time and it should be simple but I cannot get it to work. Thanks in advance. I need to rewrite this php statement Code: [Select] <img src="<?php bloginfo('template_directory'); ?>/images/mainimage.jpg" title="" alt="" /> When I try to do this Code: [Select] <?php echo '<img src="<?php bloginfo('template_directory'); ?>/images/mainimage.jpg" title="" alt="" />' ; ?>It does not work, because I guess I've open and closed a php code inside php. How do I properly write this statement? Thanks Ben Hi All, Im modifying someone elses PHP code (survey tool) (and i havent done PHP for years) Basically the code exports to an external csv file to a file called export.csv However everytime i get it to export, it creates copies. ie it will export to export(2).csv and export(3).csv. How can i make it so that it exports and overwritesa/ammed the existing export.csv file? I had a look at the code and i believe this code below is doing the exporting but not sure code doing the export ( i think) Code: [Select] <?php include('classes/main.class.php'); include('classes/special_results.class.php'); $survey = new UCCASS_Special_Results; echo $survey->results_csv(@$_REQUEST['sid'],$_REQUEST['export_type']); ?> The class that it uses to export Code: [Select] <?php //====================================================== // Copyright (C) 2004 John W. Holmes, All Rights Reserved // // This file is part of the Unit Command Climate // Assessment and Survey System (UCCASS) // // UCCASS is free software; you can redistribute it and/or // modify it under the terms of the Affero General Public License as // published by Affero, Inc.; either version 1 of the License, or // (at your option) any later version. // // http://www.affero.org/oagpl.html // // UCCASS is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // Affero General Public License for more details. //====================================================== class UCCASS_Special_Results extends UCCASS_Main { function UCCASS_Special_Results() { $this->load_configuration(); //Increase time limit of script to 2 minutes to ensure //very large results can be shown or exported set_time_limit(120); } function results_table($sid) { $sid = (int)$sid; if(!$this->_CheckAccess($sid,RESULTS_PRIV,"results_table.php?sid=$sid")) { switch($this->_getAccessControl($sid)) { case AC_INVITATION: return $this->showInvite('results_table.php',array('sid'=>$sid)); break; case AC_USERNAMEPASSWORD: default: return $this->showLogin('results_table.php',array('sid'=>$sid)); break; } } $data = array(); $qid = array(); $survey = array(); $survey['sid'] = $sid; $query = "SELECT q.qid, q.question, s.name, s.user_text_mode, s.survey_text_mode, s.date_format FROM {$this->CONF['db_tbl_prefix']}questions q, {$this->CONF['db_tbl_prefix']}surveys s WHERE q.sid = $sid and s.sid = q.sid ORDER BY q.page, q.oid"; $rs = $this->db->Execute($query); if($rs === FALSE) { $this->error('Error in query: ' . $this->db->ErrorMsg()); return; } $questions = array(); if($r = $rs->FetchRow($rs)) { $survey_text_mode = $r['survey_text_mode']; $user_text_mode = $r['user_text_mode']; $date_format = $r['date_format']; $survey['name'] = $this->SfStr->getSafeString($r['name'],$survey_text_mode); do{ $data['questions'][] = $this->SfStr->getSafeString($r['question'],$survey_text_mode); $qid[$r['qid']] = $r['qid']; }while($r = $rs->FetchRow($rs)); } else { $this->error('No questions for this survey.'); return; } if(isset($_SESSION['filter_text'][$sid]) && isset($_SESSION['filter'][$sid]) && strlen($_SESSION['filter_text'][$sid])>0) { $this->smarty->assign_by_ref('filter_text',$_SESSION['filter_text'][$sid]); } else { $_SESSION['filter'][$sid] = ''; } $query = "SELECT GREATEST(rt.qid, r.qid) AS qid, GREATEST(rt.sequence, r.sequence) AS seq, GREATEST(rt.entered,r.entered) AS entered, q.question, av.value, rt.answer FROM {$this->CONF['db_tbl_prefix']}questions q LEFT JOIN {$this->CONF['db_tbl_prefix']}results r ON q.qid = r.qid LEFT JOIN {$this->CONF['db_tbl_prefix']}results_text rt ON q.qid = rt.qid LEFT JOIN {$this->CONF['db_tbl_prefix']}answer_values av ON r.avid = av.avid WHERE q.sid = $sid {$_SESSION['filter'][$sid]} ORDER BY seq, q.page, q.oid"; $rs = $this->db->Execute($query); if($rs === FALSE) { $this->error('Error in query: ' . $this->db->ErrorMsg()); return; } $seq = ''; $x = -1; while($r = $rs->FetchRow($rs)) { if(!empty($r['qid'])) { if($seq != $r['seq']) { $x++; $seq = $r['seq']; $answers[$x]['date'] = date($date_format,$r['entered']); } if(isset($answers[$x][$r['qid']])) { $answers[$x][$r['qid']] .= MULTI_ANSWER_SEPERATOR . $this->SfStr->getSafeString($r['value'] . $r['answer'],$user_text_mode); } else { $answers[$x][$r['qid']] = $this->SfStr->getSafeString($r['value'] . $r['answer'],$user_text_mode); } } $last_date = date($date_format,$r['entered']); } $answers[$x]['date'] = $last_date; $xvals = array_keys($answers); foreach($xvals as $x) { foreach($qid as $qid_value) { if(isset($answers[$x][$qid_value])) { $data['answers'][$x][] = $answers[$x][$qid_value]; } else { $data['answers'][$x][] = ' '; } } $data['answers'][$x][] = $answers[$x]['date']; } $this->smarty->assign_by_ref('data',$data); $this->smarty->assign_by_ref('survey',$survey); return $this->smarty->fetch($this->template.'/results_table.tpl'); } function results_csv($sid, $export_type=EXPORT_CSV_TEXT) { $sid = (int)$sid; $retval = ''; if(!$this->_CheckAccess($sid,RESULTS_PRIV,"results_csv.php?sid=$sid")) { switch($this->_getAccessControl($sid)) { case AC_INVITATION: return $this->showInvite('results_csv.php',array('sid'=>$sid)); break; case AC_USERNAMEPASSWORD: default: return $this->showLogin('results_csv.php',array('sid'=>$sid)); break; } } header("Content-Type: text/plain; charset={$this->CONF['charset']}"); header("Content-Disposition: attachment; filename=Export.csv"); $query = "SELECT q.qid, q.question, s.date_format FROM {$this->CONF['db_tbl_prefix']}questions q, {$this->CONF['db_tbl_prefix']}surveys s WHERE q.sid = $sid and s.sid = q.sid ORDER BY q.page, q.oid"; $rs = $this->db->Execute($query); if($rs === FALSE) { $this->error('Error in query: ' . $this->db->ErrorMsg()); return; } $questions = array(); if($r = $rs->FetchRow($rs)) { $date_format = $r['date_format']; do{ $questions[$r['qid']] = $r['question']; }while($r = $rs->FetchRow($rs)); } else { $this->error('No questions for this survey'); return; } if(isset($_SESSION['filter_text'][$sid]) && isset($_SESSION['filter'][$sid]) && strlen($_SESSION['filter_text'][$sid])>0) { $this->smarty->assign_by_ref('filter_text',$_SESSION['filter_text'][$sid]); } else { $_SESSION['filter'][$sid] = ''; } $query = "SELECT GREATEST(rt.qid, r.qid) AS qid, GREATEST(rt.sequence, r.sequence) AS seq, GREATEST(rt.entered, r.entered) AS entered, q.question, av.value, av.numeric_value, rt.answer FROM {$this->CONF['db_tbl_prefix']}questions q LEFT JOIN {$this->CONF['db_tbl_prefix']}results r ON q.qid = r.qid LEFT JOIN {$this->CONF['db_tbl_prefix']}results_text rt ON q.qid = rt.qid LEFT JOIN {$this->CONF['db_tbl_prefix']}answer_values av ON r.avid = av.avid WHERE q.sid = $sid {$_SESSION['filter'][$sid]} ORDER BY seq, q.page, q.oid"; $rs = $this->db->Execute($query); if($rs === FALSE) { $this->error('Error in query: ' . $this->db->ErrorMsg()); return; } $seq = ''; $x = 0; while($r = $rs->FetchRow($rs)) { if(!empty($r['qid'])) { if($seq != $r['seq']) { $x++; $seq = $r['seq']; $answers[$x]['date'] = date($date_format,$r['entered']); } switch($export_type) { case EXPORT_CSV_NUMERIC: if(empty($r['answer'])) { $value = $r['numeric_value']; } else { $value = $r['answer']; } break; case EXPORT_CSV_TEXT: default: if(empty($r['answer'])) { $value = $r['value']; } else { $value = $r['answer']; } break; } if(isset($answers[$x][$r['qid']])) { $answers[$x][$r['qid']] .= MULTI_ANSWER_SEPERATOR . $value; } else { $answers[$x][$r['qid']] = $value; } } $last_date = date($date_format,$r['entered']); } $answers[$x]['date'] = $last_date; $line = ''; foreach($questions as $question) { $line .= "\"" . str_replace('"','""',$question) . "\","; } $retval .= $line . "Datetime\n"; $xvals = array_keys($answers); foreach($xvals as $x) { $line = ''; foreach($questions as $qid=>$question) { if(isset($answers[$x][$qid])) { if(is_numeric($answers[$x][$qid])) { $line .= "{$answers[$x][$qid]},"; } else { $line .= "\"" . str_replace('"','""',$answers[$x][$qid]) . "\","; } } else { $line .= ","; } } $retval .= $line . '"' . $answers[$x]['date'] . "\"\n"; } return $retval; } } ?> Hi - wondering if someone can give a little guidance: Why doesn't this trim the whitespace out of the string postzip? trim(strtoupper(((isset($_POST["postzip"]))?$_POST["postzip"]:""))) Thanks Hi, preg_match isn't working the way I feel it should. The idea, when i finally get this script working, is to echo an order form back to the client (so they can see what they've ordered). At the moment I'm just trying to get the product description for each ordered product. $aryOrder: prodCode[6722] with a value of (for instance) 2 prodCode[6724] with a value of (for instance) 1 etc (only ordered products present in the array) prodDB.txt 6722 Hydrocolloid Blister Care 6724 Toe Spreader etc All products present in text file (prode code Description) BUT I get an echo with no matches for any ordered product (or any prod for that matter) i.e. no match: 6724, 6724 TOE SPREADER when clearly, the product code (6724 $aryItem) is present in the text file line ($line_of_text). I just don't get it! foreach($aryOrder as $aryItem => $qty) { $file_handle = fopen("prodDB.txt", "r"); while (!feof($file_handle)) { $line_of_text = fgets($file_handle); if (preg_match($aryItem, $line_of_text)) { echo "Matched! $aryItem, $line_of_text QTY: $qty <br>"; } else { echo "no match: $aryItem, $line_of_text <br>"; } } fclose($file_handle); } I'm completely new to PHP, trying to work it out from the manual, so I've probably made a very basic mistake, and may even be going about this in entirely the wrong way. Any help much appreciated, Steve The following query or while loop is only increasing the ArticleID variable every 3rd time the script is run, I've narrowed it down to the following code snippet. Can you spot a problem with this, I'm in my first week of PHP and MySQL and I can't see any problem with it. Any help would be mighty appreciated by this idiot Code snippet: --- $result = mysql_query("SELECT ArticleID FROM test_top ORDER BY ArticleID ASC LIMIT 1") or die(mysql_error()); while($row = mysql_fetch_array($result)) { $ArticleID=$row['ArticleID']; } $ArticleID=intval($ArticleID); $ArticleID++; --- So I have a count down timer on my site. http://fpsboost.net And I am clueless as to how I would set a final date with this. Cant find where it's grabbing the info for "finaldate" or anything like that. Want to set the final date to feb 1st 2015 Javascript newb here. Anyone willing to help would be greatly appreciated. Thanks in advance! Btw, I'm using a generic js countdown timer from: http://hilios.github...uery.countdown/ called "The Final Countdown for jQuery v2.0.4" It was preloaded in a template that I downloaded for my site. Edited by jakobe, 09 December 2014 - 01:09 AM. I'm working on an email template system where my client will go to a page and copy & paste the source code into their crm system. I'm trying to find a way to automatically replace the image path without the use of echo if possible. I've figured this out already with this script: Code: [Select] <? function GetFileDir($php_self){ $filename = explode("/", $php_self); // THIS WILL BREAK DOWN THE PATH INTO AN ARRAY for( $i = 0; $i < (count($filename) - 1); ++$i ) { $filename2 .= $filename[$i].'/'; } return $filename2; } ?> But I don't wanna have to go in and put Code: [Select] <?php echo GetFileDir("http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']); ?> before all the image paths. So basically anywhere that src="images/whatever.jpg" is listed it will replace "images/" with "http://www.mydomain.com/images/whatever.jpg" is it possible to do this without having to place code before "images" ? I am running three scheduled tasks on my website. I am only allowed three per day by my host. I want to add another one. Can I simply call another php program from within a php program which is currently running ? I'm trying the fetch some geocode data from mapquest. Google doesn't like me right now. I keep running into the query_limit. So I want to set a back up that will go into production when I get that error from the big G. I have my api key and I can put the string in a var. Code: [Select] $geocode = file_get_contents($url) I selected json as the output and when I echo $geocode... here is the first portion of the string....(I want lat & lng) Code: [Select] renderOptions({"results":[{"locations":[{"latLng":{"lng":-112.35984,"lat":34.58752},..... Now for the life of me, I can't do anything with it. I've tried json_decode() with the true argument there and not. Code: [Select] $output = json_decode($geocode, true); $output = json_decode($geocode); vardump($output) is NULL. So, I thought, well maybe I don't need to decode it, but I can't figure out how to parse it. I'm lost. This admittedly is my first attempt as trying to work with a jason object, but jeesh, it doesn't seem like it should be that hard. Can someone start me in the right direction? I have a simple form that connects to this php page. Only two variables, "ArticleDescription" & "URL". I've tried a number of things, several of which are listed below, but have had no success. I'm certain it's just my idiocy but am requesting some help with this. I KNOW it's an easy fix, it's just over my head, I'm only four days into programming, so I'm a complete newb. Your kindness is requested. ---- <?php // connection mysql_select_db("doofyd5_comments", $con); $ArticleDescription=mb_convert_encoding($ArticleDescription, 'UTF-8', 'UTF-8'); $URL=htmlspecialchars($URL, ENT_QUOTES); $ArticleDescription=str_replace('\"','"',$ArticleDescription); $sql="INSERT INTO web_articles (ArticleDescription, URL) VALUES ('$_POST[ArticleDescription]','$_POST[URL]')"; if (mysql_query($sql,$con)) { header ("location:desiredurl"); require_once('desiredurl"); exit(); } else { echo "You may have added a single quote to the article description!"; } mysql_close($con) ?> ---- I have an array I want to define in Php and then sort it. I am pretty new to Php and don't know the syntax or what funcs to use. Here's the array I want: user_email, user_name, hours_worked_per_week, total_earned There will be about 120 users, and I want to sort them ascending alphabetically on user_email A couple months back, I asked on a gaming forum if anyone knew of a website that would track your *Steam Wishlist and email you when one of your wishlist games went on sale. No one at the time knew of a **solution, so I decided to buy "PHP, MySQL and Javascript" and try to roll my own. I managed to get the basics working. After the basics, I started thinking about fun stuff I could do with the data I collected from Steam regarding the games that go on sale regularly. The first part of my code file_get_content's the ***sale page(s) of games, and sucks out the games name, regular price, sale price, and the games homepage URL on Steam. This is enough to accomplish my basic task. The second part is where I need help, and that's getting more details on the game. The additional details I want to get about the game include its Publisher and Developer, and to get that detail I need to go to the games homepage URL I previously got from the global sale page. The issue is this: Some games have an age-restriction limitation, and you have to fill out a date form before entering the games homepage. An example of one of those pages would be: http://store.steampowered.com/agecheck/app/1250/ I want to be able to POST a legal age to the above URL, and then (this is where I'm hazy) "re-load" the same URL, authorized by my previous POST. Is that possible? * Steam is a digital download service for computer games. ** Subsequently, there was another website found. But I was well into developing my solution and having fun. *** Example: http://store.steampowered.com/search/?specials=1 Hi there, I'm new to this (2 days into it) but I've managed to rummage together 2 tables, and PHP to input into the database. My issue now is that I want to merge one of the two tables into the other. I've managed to do this, but for some reason I'm getting duplicate entries from the 2nd table. Code: //mysql connection $query = "SELECT ArticleDescription, URL FROM top_web_articles"or die ("query is messed up"); $result = mysql_query($query); while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { mysql_query("INSERT INTO web_articles (ArticleDescription, URL) SELECT ArticleDescription, URL FROM top_web_articles") or die ("Failed merge!"); } echo ("Successful merge!"); ?> Does anyone have any suggestions as to where I went wrong? Thanks in advance, Doofy. What is the easiest way of finding out in php what date a certain day falls on? ie: I want to know what date is the 3rd Thursday of every month. for example, this month would be " The third Thursday of this month falls on : 18th November " Whats the best way of doing that in php? Thanks,, |