PHP - Setcookie Vs Session?
Hello.
I currently have a site that registered members can login in to and view the member only pages. Eventually I will be adding paypal code to purchase products. I use Session with an IF statement for all my members pages. Would it be beneficial at all to have cookies created for the users with setcookie? Or is this just a security risk waiting to happen? Similar TutorialsHey Guys, I am trying to set a cookie so that when I registered user returns it Auto Logins them in. I am able to accomplish this on my Local server but as Soon as I upload to a web server to test it, it doesn't work. Is anyone able to shed some light on this for me. $usass = $mem['userid']; if (isset($_POST['rem'])) { $year = 3600*24*365; setcookie ("id" , "$usass", time()+$year); } if the code for setting the cookie, and the code for checking the cookie is Below if(isset($_COOKIE['id'])) { $_SESSION['userid'] = $_COOKIE['id']; print "<script>"; print " self.location='loggedin.php';"; // Comment this line if you don't want to redirect print "</script>"; } For some reason I can not get this to work. Any thoughts? if( $row['password'] == $pass && $row['name'] == $user ) { $username = $row['name']; $uid = $row['id']; setcookie("id", $uid, 1400); //creates the first session var setcookie("username", $username, 1400); // second session var setcookie("loggedin", "1", 1400); echo "<script type=\"text/javascript\">alert(\"".$row['name']."Logged in as ".$_COOKIE['username'].".\"); window.location=\"index.php?OMG=loggedin\"</script>"; } I get a message box saying: "[username] Logged in as ." I've searched php.ini for corrupt cookie settings, nothing unusual. Hi, I'm working on a mac with MAMP, phpMyadmin. on localhost, also the mysql server is on my localhost. I've tested in either Safari and Firefox. I'm trying to set my cookie, and it doesn't work, and pulling my hair out. I'm trying out following script which should work, but it doesn't and it's driving me mad. I wanna check the cookie for when a person is or isn't logged in, so that i can show additional data on the .php page <html> <body> <?php $value = "my cookie value"; // send a cookie that expires in 24 hours setcookie("TestCookie",$value, time()+3600*24); // Print individual cookies echo $_COOKIE["TestCookie"]; // Print all cookies print_r($_COOKIE); ?> </body> </html> i have never been able to get this to work but i am at it agian in this code the php is not making the cookie can any one tell me why <?php function getRandomString($length = 5) { $validCharacters = "abcdefghijklmnopqrstuxyvwzABCDEFGHIJKLMNOPQRSTUXYVWZ+-*#&@!?1234567890"; $validCharNumber = strlen($validCharacters); $result = ""; for ($i = 0; $i < $length; $i++) { $index = mt_rand(0, $validCharNumber - 1); $result .= $validCharacters[$index]; } return $result; } setcookie("code", "getRandomString()", 3600000); echo getRandomString(); ?> when a user logs in the cookie isnt being set. am i doing it wrong? if(empty($error)) { $query = $link->query("SELECT * FROM ".TBL_PREFIX."users WHERE u_username = '$username' AND u_password = '".asf_hash($password)."'") or die(print_link_error()); $row = $query->fetchAll(); $num_rows = $query->rowCount(); if($num_rows == 1) { if($row[0]['u_confirmed'] == 1) { setcookie('uid', $row[0]['u_uid'], time() + $session_length); // this cookie isnt being set echo 1; } else { $error = 'You Need To Activate Your Account'; } } else { if(!$error) { echo $lang->incorrect_login_details; } } } im doing a print_r on all cookies and it doesnt appear in the list. $session_length is set at 99999999 I know PHP setcookie can set for all subdomains - by setting parameter 5 to something like ".domain.com". However, I have quite a lot of code that just leaves param 5 blank (so sets for the current subdomain of that server). Hopefully there'd be an easy way how to do this (a server setting?). I know you can use ini_set('session.cookie_domain','http://domain.com'); but that only seems to set the session cookie value, not ones set in PHP. I only really want it to ensure if someone accesses the site through both www.domain.com and domain.com that they use the same cookies. hello i use the fallowing code for my login page but it gives me the fallowing error i was wondering what is the problem? (line 179 is the setcookie) by the way it doesn't set the cookie any help would be appreciated error: Quote Warning: Cannot modify header information - headers already sent by (output started at /home2/sportsh9/public_html/test/login_acc.php:6) in /home2/sportsh9/public_html/test/login_acc.php on line 179 my code: <? include_once('functions.php'); function cleanQuery($string) { if(get_magic_quotes_gpc()) // prevents duplicate backslashes { $string = stripslashes($string); } $badWords = "(delete)|(update)|(union)|(insert)|(drop)|(http)|(--)"; $string = eregi_replace($badWords, "", $string); if (phpversion() >= '4.3.0') { $string = mysql_real_escape_string($string); } else { $string = mysql_escape_string($string); } return $string; } if (isset($_COOKIE['scmuser'])) { echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"1; URL=index.php\">"; }else{ if ($_POST['username']) { //did they supply a password and username $username=cleanQuery($_POST['username']); $password=cleanQuery($_POST['password']); if ($password==NULL || $username==NULL) { ?> <p align="center"> <font color="#FF0000">Username or password wasn't supplied!</font><form action="login_acc.php" method="POST"> <table style="border:1px solid #FFFFFF;" width="90%" align="center"> <tr> <td align="center">Username: </td> <td align="center"> <input type="text" size="20" maxlength="25" name="username" /></td> </tr> <tr> <td align="center">Password: </td> <td align="center"> <input type="password" size="20" maxlength="25" name="password" /></td> </tr> <tr> <td align="center" colspan="2"> <input type="submit" value="Login"/> </td> </tr> <tr> <td align="center" colspan="2"> <a href="register.php">Register</a> - <a href="forgetpass.php">Forgot Your Password?</a> </td> </tr> </table> </form> <? }else{ $query = mysql_query("SELECT username,password FROM users WHERE username = '$username'") or die(mysql_error()); $data = mysql_fetch_array($query); if($data['password'] != $password) { ?> <p align="center"> <font color="#FF0000">The supplied login was incorrect</font><form action="login_acc.php" method="POST"> <table style="border:1px solid #FFFFFF;" width="90%" align="center"> <tr> <td align="center">Username: </td> <td align="center"> <input type="text" size="20" maxlength="25" name="username" /></td> </tr> <tr> <td align="center">Password: </td> <td align="center"> <input type="password" size="20" maxlength="25" name="password" /></td> </tr> <tr> <td align="center" colspan="2"> <input type="submit" value="Login"/> </td> </tr> <tr> <td align="center" colspan="2"> <a href="register.php">Register</a> - <a href="forgetpass.php">Forgot Your Password?</a> </td> </tr> </table> </form> <? }else{ $query = mysql_query("SELECT username,password FROM users WHERE username = '$username'") or die(mysql_error()); $row = mysql_fetch_array($query); setcookie("scmuser", "$username", time()+3600); echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"1; URL=index.php\">"; } } } } ?> thank you I am aiming to use setcookie to refresh the expiry of a cookie on EVERY page request. Is this slow? I'm sure I can design things so i don't need to reset it on every page request, but if it isn't a big deal then I'll do it. Is setcookie slow? I am working on a login script and I am using cookies for the first time. I have it something like this: <?php if (correct user/pass entered) - set user/pass cookies ?> <html> <?php if (user/pass cookies are set) {echo 'you are logged in';} else {echo 'you are NOT logged in';} ?> </html> The problem is that if I enter a valid username and password, and the cookies are set, then I get the message 'you are NOT logged in' unless I leave the page then return to it, or if I refresh, in which case I get the message 'you are logged in'. Its almost as though I cannot use the cookies until I navigate away from the page on which they were set. Am I doing something wrong, or is this the way it works? I hate header errors... I can never figure them out, im getting this error; Warning: Cannot modify header information - headers already sent by (output started at /home/damnpeti/public_html/restrict2.php:6) in /home/damnpeti/public_html/restrict2.php on line 62 Code: <?php $testDB = mysql_connect('localhost', $db_user, $db_pwd); mysql_select_db ($db_name); if (!$testDB) { die('Could not connect: ' . mysql_error()); } $surfer_ip = $_SERVER["REMOTE_ADDR"]; $str_sql = "select * from ".$db_table." where ipaddress='".$surfer_ip."'"; $result = mysql_query($str_sql); if ($row = mysql_fetch_assoc($result)) { $blocked_time = strtotime($row['blocked_time']); if($blocked_time != 0) { $current_time = time(); if($current_time - $blocked_time > 3600*24) //24 hours past { $str_sql = "delete from ".$db_table." where ipaddress='".$surfer_ip."'"; mysql_query($str_sql); $str_sql = "insert into ".$db_table." (ipaddress, surf_index) values('".$surfer_ip."', 1)"; mysql_query($str_sql); } else { die ("<center><div class='errors'>You have accessed this page too many times. To regain access, purchase a license or wait 24 hours.</div></center>"); } } else { if($row['surf_index'] < 2) { $str_sql = "update ".$db_table." set surf_index=surf_index+1 where ipaddress='".$surfer_ip."'"; mysql_query($str_sql); } else { $str_sql = "update ".$db_table." set blocked_time='".date ("Y-m-d H:i:s")."' where ipaddress='".$surfer_ip."'"; mysql_query($str_sql); die ("<center><div class='errors'>You have accessed this page too many times. To regain access, purchase a license or wait 24 hours.</div></center>"); } } } else { $str_sql = "insert into ".$db_table." (ipaddress, surf_index) values('".$surfer_ip."', 1)"; mysql_query($str_sql); } if(!isset($_COOKIE['surf_no'])) setCookie('surf_no', '1'); else setCookie('surf_no', $_COOKIE['surf_no']+1); if ($_COOKIE['surf_no'] > 2) die("<center><div class='errors'>You have accessed this page too many times. To regain access, purchase a license or wait 24 hours.</div></center>"); include 'http://damnitpetitions.com/cut/index3.php'; ?> Line 62 is if ($_COOKIE['surf_no'] > 2) I know it has something to do with the cookie... but Idk? I need the include there. If there include isnt where its at, the script is worthless. I'm stumped on this one. New to sessions and cookies. When somebody logs out, the browser goes to logout.php. It logs them out, but the page shows this error: Warning: setcookie() expects parameter 3 to be long, string given in /data/21/2/40/160/2040975/user/2235577/htdocs/logout.php on line 23 you are now logged out. Code: [Select] <?php session_start(); if(!($_SESSION[id])){ $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_server['PHP_SELF']); // check for trailing slash if ((subst($url, -1) == '/') OR (substr($url, -1) == '\\') ){ $url = substr($url, 0, -1); } $url .= '/index.php'; header("Location: $url"); exit(); } else { $_SESSION = array(); session_destroy(); setcookie ('PHPSESSID'. '', time()-300, '/', '', 0); } $page_title ='logged out!'; echo ' you are now logged out'; 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 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 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'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. I just did a huge import from an app I have been working on. No issues except for this. I uploaded & imported all files & databases from my wampserver (localhost, local server) to my main online server. Before I continue with the problem, I have to give you info on how the files work. I am using a "controller" to view the files. Meaning, from index.php, I call all the files. For example, instead of mysite.com/register.php, its mysite.com/index.php?page=register. The index defines the doctype & html tags etc. The other files that are called through index.php are just pure php code, it does not contain the head & body tags etc. So, the issue is , when the surfer submits a form, i need to set a cookie. this cookie is VERY important. I cannot get it to work. I am getting the header warnings after submit Of course, this is to be expected. But I tried it on my local server, & it worked. I am not very familiar with cookies, this is a side of PHP i never really even touched. I know almost everything but that. So the php code is before the html code on the page, so I figured it was worth a shot. Im guessing the problem here is, since the code being outputted as index.php code + the form page code. So the cookie is being set after the html tags. How can I fix this? I need it to work thru the controller. I cannot just make it a single file, all files on the site needs to be thru this controller, otherwise it will mess everything up. Ino I could just add the code from index.php plus the form page code & just run the php code before all of the html tags, but like I said it has to be called thru index.php. I appreciate your replies, & I hope you guys dont think im an idiot & can understand my question, im terrible with words! I am building an app (PHP and MySQL)and I had been using a lot of GET calls to get info from URLs, but the more I thought about it, the more I didn't like the possibility of people being able to mess with the URLs. So I am in the process of changing everything to use SESSION variables to store data across pages, rather than GET. The way I see it, SESSION variables are completely behind the scenes so they seem to be the better option. Am I right, or is GET better than SESSION for some reason? |