PHP - Need Help With Session And Storing Id In Cookie
I don't know why but I'm failing hard at GoogleFu today. I can't find a tutorial on how to store a session id in a cookie and then call it on the server. session_id says it replaces the cookie it makes if you set the id via session_id, even if it's the same id...but I'm not sure if that really matters.
Can anyone help point me in the right direction to a good tutorial/give me some insight on this subject? I want to store the session id in a cookie to keep a user logged in for 2 weeks or so (unless they log out of course). I did find some tutorials on how to re-route the session handlers for open/close/read/write session functions which allow me to store the session in a database. Is this what I want? Sorry for the newbie question, Thanks, Justin Similar TutorialsI 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 have created an object and assigned values as follows: Code: [Select] $car_object =& new Car(); $car_object->offer = 'Sale'; $car_object->type = 'Sport Car'; $car_object->location = "Buffalo, New york"; How can I store the $car_object inside a session variable? How can I get the $car_object out from the session variable? Please help a novice. Urgent. Here is my code... Code: [Select] <?php mysql_connect("localhost", "user", "pass")or die("cannot connect"); mysql_select_db("database")or die("cannot select DB"); $myemail = mysql_real_escape_string($_POST['myemail']); $mypassword = mysql_real_escape_string($_POST['mypassword']); $mypassword = md5($mypassword); $myemail = stripslashes($myemail); $mypassword = stripslashes($mypassword); $sql="SELECT * FROM users WHERE email='$myemail' and password='$mypassword'"; $result=mysql_query($sql); $count=mysql_num_rows($result); if($count==1){ session_start(); $_SESSION["myemail"]= "$myemail"; header("location:home.php"); } else { header("location:fail.php"); } ?> What can I do to this code so that it will also store first name from the database inside a session? I need some help with this. A user fills out a form, one of the fields is a zip code field. I need to retrieve that value from MySQL store as a session var and set that value as a variable to use with a weather display API. The ID is being stored from the form page. Here is what I have so far, after the values are submitted into the DB. <?php session_start(); $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM Profile WHERE id='{$_SESSION['id']}"); while ($row = mysql_fetch_assoc($result)) { $_SESSION['id'] = $row['id']; $_SESSION['zip'] = $row['zip']; } mysql_close($con); ?> and then for the weather API, I need to set the stored variable to something $zip = 'stored zip code value'; I am having some problems with part of the code. What is going on is a user registers info with a form and is sent an email with a confirmation link. The info that was in a temp DB table is moved to a member table. All of this works fine, but I am trying to be able to store an ID and username associated with their passkey info and echo that variable out. This part I am having trouble with. Code is here. <? session_start(); include('config.php'); // Passkey t from link $passkey=$_GET['passkey']; $tbl_name1="Profile_temp"; // Retrieve data from table where row matches passkey $sql1="SELECT * FROM $tbl_name1 WHERE confirm_code ='$passkey'"; $result1=mysql_query($sql1); // If successfully queried if($result1){ // Count how many row has this passkey $count=mysql_num_rows($result1); // if passkey is found retrieve info from temporary DB if($count==1){ $rows=mysql_fetch_array($result1); $FirstName=$rows['FirstName']; $LastName=$rows['LastName']; $UserName=$rows['UserName']; $Password= md5($rows['Password']); $Password2=md5($rows['Password2']); $email=$rows['email']; $Zip=$rows['Zip']; $Birthday=$rows['Birthday']; $Security=$rows['Security']; $Security2=$rows['Security2']; $tbl_name2="Profile"; // Insert data that retrieves from "temp_members_db" into table "registered_members" $sql2="INSERT INTO $tbl_name2(`FirstName`,`LastName`,`Username`,`Password`,`Password2`,`email`,`Zip`,`Birthday`,`Security`,`Security2`) VALUES ('$FirstName','$LastName','$UserName','$Password','$Password2','$email','$Zip','$Birthday','$Security','$Security2')"; //echo $sql2; $result2=mysql_query($sql2); } // if passkey is not found, display message "Wrong Confirmation code" else { echo "<h2>Sorry, Your passkey was not found.</h2>"; } while ($row = mysql_fetch_assoc($result2)) { $_SESSION['id'] = $row['id']; $_SESSION['UserName']=$user_name; } // if successfully moved data from table"temp_members_db" to table "registered_members" displays message "Your account has been activated" and don't forget to delete confirmation code from table "temp_members_db" if($result2){ echo "<h2>Your account has been activated, </h2>"; echo "$user_name"; echo"<p>You may now upload a profile picture</p>"; // Delete information of this user from table "temp_members_db" that has this passkey $sql3="DELETE FROM $tbl_name1 WHERE confirm_code = '$passkey'"; $result3=mysql_query($sql3); } } ?> getting an error for this part while ($row = mysql_fetch_assoc($result2)) { $_SESSION['id'] = $row['id']; $_SESSION['UserName']=$user_name; } the error is "Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in confirmation.php on line 62" Hi there, I am working on a PHP web form and I have a very simple situation I guess, I have a variable named: $MyVal When I do print_r($MyVal); To see whats inside, I get: SimpleXMLElement Object ( [0] => 8.23 ) Now I am assigning this variable into a session variable so that I can do calculations with it. So I assign: $_SESSION['MySesVal'] = $MyVal; But after assigning to session variable, when I do my calculations: $finalValue = $_SESSION['MySesVal'] * 4; I get 0. So is it because the actual $MyVal variable has some XML stuff as: SimpleXMLElement Object ( [0] => 8.23 ) So what is the right way to properly assign $MyVal variable to a session variable to do calculations. Please reply. All comments and feedbacks are always welcome. Thank you! Hi All, I have a secure website which always checks the cookies is not expired and the session id is set. When someone doesn't browse for the period of the cookie it will expire however the session id stays valid until he logout. A lot of people don't logout so the pages will still be accessable for them or others who use their pc. Is there a way to destroy the session id when the cookies expires? Marco The default PHP Session name on my webspace server is PHPSESSID. Does that mean that the session cookie will be called PHPSESSID? The reason i ask is that in a couple of places i can't use PHP to update the information in the session cookie (because PHP is parsed before the webpage loads) and so i need to use Javascript to update a cookie which i would prefer to be the session cookie used by PHP. I guess i'm asking what the name of the cookie is, how i would refer to it in Javascript (if that is even possible) so that i can update it and whether this would cause any issues with the info already stored in the session cookie by PHP. Cheers NM Hi, I am just recently getting this error message:Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/XXX/chordsandguitar.com/index.php:46) in /home/jchords/chordsandguitar.com/index.php on line 48 this is no doubt related to the fact that my site has been hacked along with 1000's of others that are on dreamhost. I don't know if it's related to php file permissions some of my files may have had had their permission set for read-write when they should not have been. They have all been changed to the more restrictive 755 or 644. So here is how I am using the session_start to store some variables: Code: [Select] session_start(); if (!isset($_SESSION["count"])) { $_SESSION["count"]=0; } else $_SESSION["count"]++; if ($_SESSION["count"] == 0) { $scale_menu = 'C'; $variation_menu = 'maj'; $code_id = '1'; } else { //allows retreiving the value of the drop-downs after the Select button has been pushed // has to be skipped on the first access or overwrites starting vars. to null if (isset($_GET['s_menu'])) $scale_menu = $_GET['s_menu']; else $scale_menu = $_GET['scale_menu']; } So any ideas why I am getting this error? Thanks, Jacques Hi to everyone, I'm new to the forum and I'm posting here because I ended up in a logical problem for my next script development.
I need to get some data of external websites (with vbulletin board), perfectly legal.
Using file_get_contents i can print the page content on my server and then use jquery's powerful selectors to get my data.
The problem is that these data are shown only to logged in users so i would need this script (maybe using cURL?) to either login to the external website and then persists the connection or maybe if the user who is executing my script is already logged in that website then use his login? (most likely impossible I think..)
This is my code so far (found on some sites and merged into this)
$data = array('vb_login_username' => 'Scanu', 'vb_login_password' => 'grgfgrgrfbtgbt'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.vbulletin.org/forum/login.php?do=login"); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_COOKIESESSION, true); curl_setopt($ch, CURLOPT_FAILONERROR, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); curl_setopt($ch, CURLOPT_FRESH_CONNECT, true); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $result = curl_exec($ch); curl_close($ch); $pattern = "#Set-Cookie: (.*?; path=.*?;.*?)\n#"; preg_match_all($pattern, $result, $matches); array_shift($matches); $cookie = implode("\n", $matches[0]); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.vbulletin.org/forum/"); curl_setopt($ch, CURLOPT_COOKIE, $cookie); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_COOKIESESSION, true); curl_setopt($ch, CURLOPT_FAILONERROR, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); curl_setopt($ch, CURLOPT_FRESH_CONNECT, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_POST, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); $result = curl_exec($ch); curl_close($ch); echo $result; ?>It just shows the same page for unregistered users. Any help or advice is appreciated, i'm very new to this type of script.. hey guys im using a session cookie to store a user_id, only if user has clicked to remember me on the login form...that way when autenticating it checks id in db and if matching a user it logs in automatically.
now the problem i want to just remove user_id from a session cookie. if i use the code below to delete the user_id session then it will remove all session cookies.
is there a way just to remove 1 session cookie? thank you
// create session cookie session_start(); session_set_cookie_params('3600', 'C:\Users\Ricky\Desktop\www\BiSi\private\tmp\session', 'http://127.0.0.1/', true, true); ini_set('session.gc_probability', 1); session['user_id'] = 1; //delete session cookies setcookie (session_name(), null, time() - 3600); session_regenerate_id(true);any help/advise would be greatful...cheers guys Hi, I'd like to know the security of assuming session variables and using them for secure membership systems. Could a malicious user not create a session, then change the session username to another user and effectively login as that user? As I see it, no. Because session data is stored on the server and only a session id is stored on the client by way of a cookie. But what if we used cookies? What is the solution to this? Because I know I could easily change ANY variables within a cookie. I guess storing cookie data via db would help. But what is the best practice solution? I see a lot of code which simply checks for a cookie with the variable 'logged_in' to true. It then manages the user by username or userid which are stored within the cookie but which can be changed with ease by a malicious user. hello all, I have a client that wants to protect their web page with a password protected landing page. Once the password is entered the user is directed to a "disclaimer" page that they have to agree to first before going into the site. I have put both the landing page and the disclaimer page in my root directory and then the site I put in a sub directory /cms/ in the main site index.php I check for the post password and then set a $_COOKIE for the user that will expire in 1 month <?php // this goes on the very top of the index.php file in the template you are using //check if user has entered password and needs cookie set if(isset($_POST['fpass']) && !isset($_COOKIE['fpass'])) setcookielive('fpass', $_POST['fpass'], strtotime( '+1 month' )); function setcookielive($name, $value='', $expire=0, $path='', $domain='', $secure=false, $httponly=false) { //set a cookie as usual, but ALSO add it to $_COOKIE so the current page load has access $_COOKIE[$name] = $value; return setcookie($name,$value,$expire,$path,$domain,$secure,$httponly); } The next thing I do is check if a user is trying to access the main site with having the COOKIE - if so I redirect the user to the landing page //check if user has not entered password if (!isset($_COOKIE['fpass']) || $_COOKIE['fpass'] == "") header('location: http://www.mypage.com'); This works fine up to this point. Now my problem is that I also need to check if a user has the month long cookie set but is trying to access the main page without viewing the disclaimer page first. I thought this would work: //check if the user has a cookie set but is on a new session if (isset($_COOKIE['fpass']) && !isset($_SESSION['fpass'])) header('location: http://www.mypage.com/disclaimer.php'); But this only throws the user into a loop of "disclaimer" -> "landing page" -> "disclaimer" etc. They can never get into the main site. How do I check for the cookie and whether the user has visited the disclaimer page - but then allow the user to continue once they go to the disclaimer page? NB: the $_SESSION is not set until the main site. I am confused why I am getting the following error and was wondering if I could get a 2nd pair of eyes.. error: [29-Jul-2010 20:58:01] PHP Warning: session_start() [<a href='function.session-start'>function.session-start</a>]: Cannot send session cookie - headers already sent in /home/curren11/public_html/mysite***.com/file_monitor.php on line 2 [29-Jul-2010 20:58:01] PHP Warning: session_start() [<a href='function.session-start'>function.session-start</a>]: Cannot send session cache limiter - headers already sent (output started at /home/curren11/public_html/mysite***.com/file_monitor.php:2) in /home/curren11/public_html/mysite***.com/file_monitor.php on line 2 Here is the code: <?php session_start(); $root_path = realpath(getcwd()); $error_monitor_file = $root_path.'/file_modify.txt'; $hour = date("H"); $today = date("m-d-Y"); $myFile2 = "file_monitor.php.log"; $fh3 = fopen($myFile2, 'a'); $log_msg = "Last ran on: ".$today." at: ".$hour." \n"; fwrite($fh3, $log_msg); function scan_dir($path) { $out = array(); $files = opendir($path); while ($f = readdir($files)) { $extension = substr($f,-3); if ($f=='.' or $f=='..' or $extension=='jpg' or $extension=='JPG' or $extension=='png' or $extension=='gif' or $f=='file_monitor.php' or $f=='file_modify.txt' or $f=='file_monitor.php.log' or $f =='error_log' ) { continue; } if (is_dir($path.'/'.$f)) { $out = array_merge($out, scan_dir($path.'/'.$f)); } //if (((!is_dir($path.'/'.$f)) && ($f!='.' or $f!='..' or $extension!='jpg' or $extension!='JPG' or $extension!='png' or $extension!='gif')) else // { $out[] = $path. '/'. $f; //} } $_SESSION['all_files'] = $out; return $out; } $a = scan_dir(getcwd()); $count_array = count($_SESSION['all_files']); $loop_count=0; while($loop_count < $count_array) { // file in directory when was it last changed ? $filechange1 = date("m-d-Y-H", filemtime($_SESSION['all_files'][$loop_count])); // was it chnaged today and have I sent out an alert yet? if($filechange1 == $today."-".$hour) { $fh2 = fopen($error_monitor_file, 'a'); fwrite($fh2, "\n alert, file: ".$_SESSION['all_files'][$loop_count]." was changed today within the last hour ! \n"); fclose($fh2); } $loop_count ++; // log file? was it changed this past hour? if (file_exists($error_monitor_file)) { $filechange_log = date("m-d-Y-H", filemtime($error_monitor_file)); if ( ($loop_count == $count_array ) && ($filechange_log == $today."-".$hour ) ) { email(); } } } // function for email... function email() { require_once ('class.phpmailer.php'); $mail = new PHPMailer(); $mail->IsSMTP(); // send via SMTP $mail->Host = "localhost"; // SMTP servers $mail->SMTPAuth = true; // turn on SMTP authentication $mail->Username = "**c66@***ar.com"; // SMTP username $mail->Password = "*****"; // SMTP password $mail->From = "***@***.com"; $mail->FromName = "Colonial Cottage File Changed"; $mail->AddAddress("email@*****.com"); $mail->WordWrap = 50; // set word wrap //$mail->AddAttachment("/var/tmp/file.tar.gz"); // attachment //$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); $mail->IsHTML(true); // send as HTML $mail->Subject ="Unauthorized file changed today!"; $mail->Body = "" ; $mail->AltBody = "This is the text-only body"; if(!$mail->Send()) { exit(); } } if ((file_exists($error_monitor_file)) && $hour == "00") { unlink($error_monitor_file); } fclose($fh3); exit(); ?> Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/bakerde1/public_html/oceangamer.com/login.php:1) in /home/bakerde1/public_html/oceangamer.com/login.php on line 2 Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/bakerde1/public_html/oceangamer.com/login.php:1) in /home/bakerde1/public_html/oceangamer.com/login.php on line 2 These are my error messages, here is my code. I don't know if it is the UTF-8 code at the start, but if it is can anyone recommend a binary editor to remove this. If it isn't what is the problem? <?php session_start(); $username = $_POST['username']; $password = base64_decode($_POST['password']); $errors = array(); if($username == 'User Name' || $username == ''){ $errors[] = 'Please enter a valid username'; } if($password == 'Password' || $password == ''){ $errors[] = 'Please enter a valid password'; } $link = mysql_connect("localhost","*****","******") or die ("Could not connect!"); mysql_select_db("chef"); $query = mysql_query("SELECT * FROM `users` WHERE `username`='$username'"); $numrows = mysql_num_rows($query); if ($numrows!=0) { while($row = mysql_fetch_assoc($query)) { $dbusername = $row['username']; $dbpassword = $row['password']; } if ($username==$dbusername&&$password==$dbpassword) { $_SESSION['user'] = $username; while ($row = mysql_fetch_array($res)) { $type = $row['Type']; } if ($type == "0") { header("location: chefpanel.php"); }else{ header("location: restpanel.php"); } } else $errors[] = 'Username or Password Incorrect'; } else $errors[] = 'Username or Password Incorrect'; ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> Hi girls and boys I am trying to set a variable if a session OR a cookie has been set, but am unsure on how to write the statement... if (isset($_SESSION['name'])||isset($_COOKIE['name'])) {$variable = $_SESSION['name']||$_COOKIE['name'];} Obviously not working there, but just need a pointer here. any help is appreciated... what would be the best way to automate/force session destroy and cookie erase i have a facebook iframe, with facebook login which gets the activation token now the user is not logged out from the login script after he logs out of facebook. any ideas how to force cookie timeout without a logout button? im playing with Code: [Select] <?php session_start(); //Global User Object Var //loggedInUser can be used globally if constructed if (isset($_SESSION['userCakeUser'])) { $obj = casttoclass('stdClass', $_SESSION['userCakeUser']); $_SESSION['userCakeUser'] = $obj; $_SESSION['start'] = time(); // taking now logged in time $_SESSION['expire'] = $_SESSION['start'] + (1 * 60) ; // ending a session in 1 minute } if(isset($_SESSION["userCakeUser"]) && is_object($_SESSION["userCakeUser"])) { $loggedInUser = $_SESSION["userCakeUser"]; } ?> I have several "sites" located in my html directory, and each has a "general" access point and an "administrator" access point:
/var/www/html/site1/index.php /var/www/html/site1/administrator/index.php /var/www/html/site2/index.php /var/www/html/site2/administrator/index.php /var/www/html/site3/index.php /var/www/html/site3/administrator/index.phpAll sites are similar except that data will be specific to site1, site2, or site3, etc. Users who log onto /var/www/html/siteX/index.php are totally unrelated to those who logon to /var/www/html/siteX/administrator/index.php, will have different logon credentials, are stored in different DB tables, and each should have their own session. If a user logs off of either the general or administrator site, it should not effect the other site even if they were previously logged on to both on the same PC (and of course not effect other sites). When a user logs off, I would like to destroy their previous cookie and associated session. Users for either will only use https. I am using Apache to rewrite https://www.mysite.com/ to https://mysite.com/. While I named the administrator site "administrator" above, the administrator user has the ability to change the directory name. I am thinking I need to use session_set_cookie_params to specify where I wish the session cookie to be stored since /var/www/html/siteX/administrator/index.php is a sub-directory to /var/www/html/siteX/index.php, but am not really sure. Sorry for the cryptic post, but I am not very well versed in this subject. How would you recommend setting up cookies/sessions for this scenario? Thank you What I'm trying to accomplish is your average session login w/ a cookie-based "remember me" feature. I can log in fine, I can set cookies, I can access those cookies, and I can use that data to log in just as if the user had logged in manually. The problem is logging out. But the bigger problem is figuring out why. You see, it works perfect. It logs in and it log out, so long as I am outputting data to the page. I was outputting a session variable and the cookies I set to make sure they were all working right; and they were. But then as soon as I disable those echoes, all of a sudden it won't log out anymore. So then I turn them on to see what the data says and BAM, I'm logged out. I log back in fine, I log back out fine, so I turn em off again. I log in fine. I can't log out. I try multiple times. I close my browser and open a new one. Still logged in. I try a few more times, still logged in. I turn the output back on, load the page again and I'm logged out. So... WTF? (my code to follow) 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;?> |