PHP - Cookies And Session Question
What is the best practice to use cookies and sessions? Should i create a cookie and keep inside the cookie the name of the username the user has logged in or a session? How am i supposed to compine theese two? Is there any example or a tutorial on this? For example how does php freaks sessions and cookies work.
Similar TutorialsHello all..... Grasshopper here......... Need help with the following: I have a registration form for a Sport Gym Complex offering a free guest pass if you register...... Where would I implement cookies or sessions to reject 2nd times registrants trying to take advantage of the free guest pass within the year; I have attached the php.file Thanks Steve Ok guys heres the deal. I have been struggling on this for about two weeks and am giving up. Because I'm giving up, I would like to throw this up to you guys to help me out. I am trying to build a login I tried learning sessions but they make no sense to me whatsoever on how the information passes from one to another. So i created my own sessions database, where im uploading the data i need to pass page to page to my db, and repulling it on the next page. In order to do this i needed to create a cookie so I can refrence that data on the next page, main.php. When I run main.php i get an the echo of. "THIS COOKIE AINT FUCKING WORKING". which to me means one of two things. One is either im not creating the cookie right, or two, im not accessing it correctly. But to widdle that down I created the testpoint on if cookie is created and it seems to work fine, cuase im not getting the die(). Im not an advance php programmer by any means, just been self learning for a few months, so bear with me and please break it down as much as possible. I feel that if i can just get a userid created on one page, put it into a cookie, send it, and retreive it when on the next page, i can do the rest from there. If you can see why that is happening then let me know. Thanks in advance. NEVERBEGOSU ---------------------------------- index.php ------------- Code: [Select] <?php include ('srvdbcon.php'); include ('functions/sitebuild.php'); include ('functions/functions.php'); setcookie('user', 'mike'); login(); headcontent(); headermain(); leftcontent(); ?> <div id="content"> <div class="post"> <h1 class="title"><a href="#">Welcome to </a></h1><p class="byline">21 April 2011 by <a href="#"></a></p> <div class="entry"> <p><strong></strong> is a free, 100% Starcraft 2 Replay Center. Our goal is to provide the ability to UPLOAD replays with detailed data, as well as to DOWNLOAD those replays. Our Replay Search function is one of a kind, designed by hand to help you find replays that you are looking for.</p> <p class="links"><a href="#" class="more">About Us</a></p> </div> </div> <div class="post"> <h2 class="title"><a href="#">Latest News</a></h2> <p class="byline">Working hard to get the site up and running. <a href="#"></a></p> <div class="entry"> <h3>Looking for late May Release:</h3> <blockquote> <p>Im working really hard guys. Forgive me for the pushback.</p> </blockquote> <h3>In Production:</h3> <ul> <li>Working on a new template for the site.</li> <li>Continuing developing the search function for replays.</li> <li>In the middle of moving in RL so working hard when I can.</li> <li>Working hard on the member login/registration pages.</li> <li>Started working on the forums</li> </ul> <h3>Finished:</h3> <ul> <li>Got the Upload Page working.</li> <li>Completed the Download style for the site.</li> <li>Finished a few other smaller aspects.</li> </ul> <p class="links"><a href="#" class="more">Read More</a></p> </div> </div> <div class="post"> <h2 class="title"><a href="#">LOOKING FOR HELP </a></h2> <p class="byline"><small>Posted on 22 Aprl 2011 by <a href="#">SCG.Admin</a></small></p> <div class="entry"> <p> is looking for a few people, if willig, to help design the site. The following positions are needed. </p> <ul> <li>Graphics Designer</li> <li>PHP/MYSQL Programmer</li> </ul> <p>If anyone is intrested please contact me at .</p> <p class="links"><a href="#" class="more">Read More</a></p> </div> </div> </div> <?php rightcontent1(); echo "<center><h2>Login</h2></center> "; echo "<form name='log' method='POST' action='" . $PHP_SELF . "'>"; echo "Username:"; echo "<p><input type='text' name='username'>"; echo "<p>Password:"; echo "<p><input type='password' name='password'>"; echo "<p><input type='submit' id='log' name='log' value='Login'>"; echo "<br>"; echo "<h2> Not a Member </h2>"; echo "<p><a href='register.php'>Register</a></p>"; echo "</center>"; rightcontent2(); footerdiv(); ?> ------------------------------------------------------------------------------------------- main.php --------- Code: [Select] <?php include ('srvdbcon.php'); include ('functions/sitebuild.php'); if(!isset($_COOKIE['userid'])); { die ('CANT GET THE FUKCING COOKIE TO WORK'); } headcontent(); headermain(); leftcontent(); ?> <div id="content"> <div class="post"> <h1 class="title"><a href="#">Welcome to </a></h1><p class="byline">21 April 2011 by <a href="#">SCG.Admin</a></p> <div class="entry"> <p><strong></strong> is a free, 100% Starcraft 2 Replay Center. Our goal is to provide the ability to UPLOAD replays with detailed data, as well as to DOWNLOAD those replays. Our Replay Search function is one of a kind, designed by hand to help you find replays that you are looking for.</p> <p class="links"><a href="#" class="more">About Us</a></p> </div> </div> <div class="post"> <h2 class="title"><a href="#">Latest News</a></h2> <p class="byline">Working hard to get the site up and running. <a href="#">SCG.Admin</a></p> <div class="entry"> <h3>Looking for late May Release:</h3> <blockquote> <p>Im working really hard guys. Forgive me for the pushback.</p> </blockquote> <h3>In Production:</h3> <ul> <li>Working on a new template for the site.</li> <li>Continuing developing the search function for replays.</li> <li>In the middle of moving in RL so working hard when I can.</li> <li>Working hard on the member login/registration pages.</li> <li>Started working on the forums</li> </ul> <h3>Finished:</h3> <ul> <li>Got the Upload Page working.</li> <li>Completed the Download style for the site.</li> <li>Finished a few other smaller aspects.</li> </ul> <p class="links"><a href="#" class="more">Read More</a></p> </div> </div> <div class="post"> <h2 class="title"><a href="#">LOOKING FOR HELP </a></h2> <p class="byline"><small>Posted on 22 Aprl 2011 by <a href="#">SCG.Admin</a></small></p> <div class="entry"> <p>SCG.O is looking for a few people, if willig, to help design the site. The following positions are needed. </p> <ul> <li>Graphics Designer</li> <li>PHP/MYSQL Programmer</li> </ul> <p>If anyone is intrested please contact me at </p> <p class="links"><a href="#" class="more">Read More</a></p> </div> </div> </div> <?php rightcontent1(); rightcontent2(); footerdiv(); ?> ---------------- functions.php Code: [Select] <?php function verifylogin() { } function login() { $Login=$_POST['log']; if ($Login) { $username=$_POST['username']; $password=($_POST['password']); $verlogin="SELECT * FROM user WHERE user='$username' AND password='$password'"; $verloginq=mysql_query($verlogin); if(mysql_num_rows($verloginq)!='0') { setcookie('userid' , 'mike'); if (setcookie) { $ip = getenv("REMOTE_ADDR"); $time=time(); $loginquery="INSERT INTO login (id,user,date,ip) VALUES ('','$username','$time','$ip')"; $loginqueryr=mysql_query($loginquery); if ($loginqueryr) { header("location:testmain.php"); } else { die('There was a problem sending info to database: LOGIN.'); } } else { die ('Cookie wont set for some damn reason.');} } else {die ('username/password error');} } else { } } function logout() { } function logcook() { } function logsess() { } ?> MOD EDIT: [code] . . . [/code] BBCode tags added. Warning: Cannot modify header information - headers already sent by (output started at /berw/ugrad1/base/s/seh8/public_html/cs25010/index.php:3) in /berw/ugrad1/base/s/seh8/public_html/cs25010/index.php on line 4 Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /berw/ugrad1/base/s/seh8/public_html/cs25010/index.php:3) in /berw/ugrad1/base/s/seh8/public_html/cs25010/index.php on line 7 Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /berw/ugrad1/base/s/seh8/public_html/cs25010/index.php:3) in /berw/ugrad1/base/s/seh8/public_html/cs25010/index.php on line 7 here is the start of the code, I have do idea what is happening, help please! <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <?PHP setcookie('user', 'sianiuser'); ?> <?php session_start(); if (isset($_SESSION['sianiuser'])) { unset ($_SESSION['sianiuser']); } ?> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/> Hello, I have the following code. I am trying to have it same the searches save for 30 days. I can't tell exactly how long this works for because it does work for a while but when I open the browser the following day, the information is lost. The server time is accurate. Does anyone have any clue to why this might not work? session_set_cookie_params(2592000); session_name('test_mysearches'); session_start(); $rqstsignature = md5($_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING'].print_r($_POST, true));if(!isset($_SESSION['mysearches'])) { $_SESSION['mysearches'] = array($_GET['s']);} else { if ($_GET['s'] != '') { $_SESSION['mysearches'] = array_filter($_SESSION['mysearches'], 'strlen'); if ($_SESSION['LastRequest'] != $rqstsignature) { // not a refresh array_unshift($_SESSION['mysearches'], $_GET['s']); $_SESSION['LastRequest'] = $rqstsignature; while(count($_SESSION['mysearches']) > 5) { array_pop($_SESSION['mysearches']); } } } } () thanks in advance. I'm pulling my hair out here... Here's my problem. I'm about halfway done with my site (It's a site to sell stuff and I'm working on the shopping cart) when I noticed a big problem. I've got session cookies working in every browser (FF, chrome, safari) except Internet Explorer. For some reason IE likes to delete my session cookies so there's nothing there after I click 'view shopping cart'. I've verified that the session is set but then it gets deleted. Now I am using IFrames and I searched for possible causes and tried changing headers, making sure there's no underscores, etc... No joy The problem is that getting the problem to show up would require a lot of copying code onto this page since it's like 4 or 5 pages to get something into the cart and then view the cart itself. What do you folks recommend? Should I just link to the site itself? What's the best way to store shopping cart information? I want things to stay in the cart for up to 2 weeks after they're added, without the need for somebody to log-in to their account to store them. Should I store the information in a database some how and then set a cookie referencing the cart_id in the db? 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! Hi All, first of all. Sorry for signing up to the site and then immediately asking for help. I hate doing it but always seems to be the way people get involved with forums these days and it seems I am no different... So thank you in advance if you are kind enough to answer! Among many personal flaws, my issue is a technical one regarding the ability to retain session variables. Unfortunately whilst the website itself is not complicated, the problem is not as simple as just running session_start(); and letting it get on and do its own thing. So the problem exists around a relatively simple contact form and the basic Turing test that it uses to prove the user is human. The script adds a value to the $_SESSION variable and then on the next page load, tests to see if the variable is still there. As per this little function: function cookiesEnabled() { if ($_SESSION['cookiesEnabledTest']) $_SESSION['cookiesEnabled'] = true; else $_SESSION['cookiesEnabledTest'] = true; } Now for what must be 95% of all users, the variable is still there, proving the the session is being maintained as the user navigates the site. Unfortunately a small group of computers appear to be having difficulties with this for a not too clear reason. The computers have varying browser user agents indicating that they are all (so far) using one of the following: MSIE 8 MSIE 7 MSIE 7 in what appears to be MSIE 6 compatibility mode Now in testing, I can't get MSIE 8 or MSIE 7 to produce the same effect, with exception to MSIE 8 in "InPrivate" browsing mode. In this mode it is easy to see that there is no cookie txt file being created and thus no way of the browser to pass back the session id on the next page load. I can't think of any detail that I have missed out, but if there is anything I have left unclear, please let me know! Thanks again! Felix Hi Guys New to php so stick with me. I'm trying to create a simple login script that will grant a user access to content that is only viewable by those people who are logged in. I'm ok doing the login part and authenticating the password etc. But once the user gets directed to the content page how can I ensure that only a registered user who is logged in sees that page? (probably missing something very obvious here). I've tried reading around but not found much on this specific question. Should I set the user's username and password (which is encrypted) as session variables and authenticate them as the first stage of each page they visit? Or is there a better way of doing this? Don't worry, not looking for you to write the code just a description of the best way of doing it would be great! Thanks, Drongo I have a business social network site on hosting server. I am wondering if sessions are enough secure. ini_set('session.use_only_cookies', 1); //this prevent Session Fixation? session_start(); if($_SESSION['loggedIn'] && $_SESSION['userIP']==$_SERVER["REMOTE_ADDR"]) // extra security //user is logged in, assign all data to this profile from session else //user is not logged in, no data are assigned Would you consider that as enough secure? Hi guys, I was wondering if we have table of seats in a cinema (which makes the quantity to 1) and two users are booking the same seat at the same time on our application. How can we prevent that? I though if we create a session or even update that seat row and then if user doesn't finish the booking/or leave the browser on fora while in 10-15 minutes, that session still remains on. I'm sure we can expire that session how can we prevent both users have the same session and if one doesn't complete the purchase for any reason then how session can automatically update the database after that 15 minutes? Thanks in advance. Hi all a small question. I was wondering if someone knows what would be the approach to achieve the following. on a page I show a random number. If the page refreshes (selfreferencing) It shows a new random number but also a the previous number, and this must be able to repeat itself : ) So to make it more visible: New Random number = 98765 Previous Number = 56412 This is what I have but it's ofc not working because ones the session var has been set it will not show the previous variable but the very first one. <?php session_start(); $random_number .= mt_rand(1,100000); if(!isset($_SESSION['number'])){ $_SESSION['number']=$random_number; } // echo all out: echo 'New random number is: '.$random_number; echo 'Previous number is: '.$_SESSION['number']; ?> I bet i need another variable to store the previous one in but for some reasons my brains don't work at the moment Im pretty new to PHP, but have managed to create a login system for a small site, my question relates to why Im entering a certain piece of code, I understand the code apart from the getting the information from a form and assigning it to a variable, I have a username form with one submit button, (username) which goes to a script called register.php I have this in my php: <?php error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED); $username=$_POST['username']; session_register("username"); header("location:index2.php"); ?> then in my index2.php page i have this: <?php error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED); session_start(); $username= $_SESSION['username']; ?> <!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>My Page</title> </head> <body> <p> Hi <?php echo $username; ?> </p> </body> </html> Ive simplified what ive done here,why am I declaring a variabel to get the form contents? cant I just get the contents? and then register? I dont need a variable.. If I remove the line, it doesnt work obviously.. thanks is it necessary to store users session on db? if so please explain someone why? and block multiple session login. say if im logged in and someone else tries to log into my id from some other place how would i stop that to happen? any idea and example would be appreciated. hi guys. i am trying to set a variable to the session global variable. I've initialized the session with session_start(); at the very beginning of my website, and then i try finding if a session variable has been set like so if(isset($_SESSION['user'])) { print 'user is logged in'; } but this works in reverse. i have not set any session variables, but asking if it is set, results in an affirmative answer. so i am thinking this is because of register_globals. because i went to read about register_globals, and it says that if register_globals is turned off, i cannot use any other varibale except members of the session array. i dont know what that is yet, but a question befo in the php manual it says register_globals is deprecated, and it appears i need to enable it to set other variables as session variables besides it's associative array. if this is true, how to enable register_globals and allow other variables to be used as session variables? 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 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! 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> |