Training, Open Source computer languages

This is page http://www.wellho.net/forum/Writing-PHP/Sessions-Problem.html

Our email: info@wellho.net • Phone: 01144 1225 708225

 
For 2023 (and 2024 ...) - we are now fully retired from IT training.
We have made many, many friends over 25 years of teaching about Python, Tcl, Perl, PHP, Lua, Java, C and C++ - and MySQL, Linux and Solaris/SunOS too. Our training notes are now very much out of date, but due to upward compatability most of our examples remain operational and even relevant ad you are welcome to make us if them "as seen" and at your own risk.

Lisa and I (Graham) now live in what was our training centre in Melksham - happy to meet with former delegates here - but do check ahead before coming round. We are far from inactive - rather, enjoying the times that we are retired but still healthy enough in mind and body to be active!

I am also active in many other area and still look after a lot of web sites - you can find an index ((here))
Sessions Problem

Posted by bschultz (bschultz), 10 June 2009
I've got a problem.  I'm trying to build a "members only" area that stores session data across multiple pages for database connections.  The problem that I'm finding is that some users (mostly IE 7) are not able to login because the session data is empty.

You will notice a line...

Quote:
///////////////////////////////////////////////    THIS LINE APPEARS TO CAUSE IE7 SOME PROBLEMS!!!!!!! //////////////////////////////////////////
//                  session_regenerate_id (TRUE);
///////////////////////////////////////////////    THIS LINE APPEARS TO CAUSE IE7 SOME PROBLEMS!!!!!!! //////////////////////////////////////////


...that appeared to be causing me the problem...but now I'm still having users that get the access-denied header...meaning an empty session.

Here's the code for the login...see anything that might be causing this?  Thanks!

Code:
<?php
ob_clean();
ob_start();
//////////// SET COOKIE DIRECTORY
if (isset($_SERVER['HTTP_HOST'])) {
   if(strpos($_SERVER['HTTP_HOST'], ':') != -1){
       $domain = substr($_SERVER['HTTP_HOST'], 0, strpos($_SERVER['HTTP_HOST'], ':'));
   }
   else{
       $domain = $_SERVER['HTTP_HOST'];
   }
   $domain = preg_replace('`^www.`', '', $domain);
 // Per RFC 2109, cookie domains must contain at least one dot other than the
 // first. For hosts such as 'localhost', we don't set a cookie domain.
 if (count(explode('.', $domain)) > 2) {
     ini_set('session.cookie_domain', $domain);
 }
}
//////////// END SET COOKIE DIRECTORY
     //Start session
     session_start();
     
     //Include database connection details
     require_once('config.php');

/////////////ERROR REPORTING . . . COMMENT OUT WHEN GOING LIVE! /////////////////////////////////
//echo ini_get('display_errors');
//if (!ini_get('display_errors')) {
//    ini_set('display_errors', 1);
//}
//echo ini_get('display_errors');
/////////////  END OF ERROR REPORTING  /////////////////////////////////

    //Domain Info used to header redirects
    $host  = $_SERVER['HTTP_HOST'];
    $uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');

     //Array to store validation errors
     $errmsg_arr = array();
     
     //Validation error flag
     $errflag = false;
     
     //Connect to mysql server
     $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
     if(!$link) {
           die('Failed to connect to server: ' . mysql_error());
     }
     
     //Select database
     $db = mysql_select_db(DB_DATABASE);
     if(!$db) {
           die("Unable to select database");
     }
     
     //Function to sanitize values received from the form. Prevents SQL injection
     function clean($str) {
           $str = @trim($str);
           if(get_magic_quotes_gpc()) {
                 $str = stripslashes($str);
           }
           return mysql_real_escape_string($str);
     }
     
     //Sanitize the POST values
     $login = clean($_POST['login']);
     $password = clean($_POST['password']);
     
     //Input Validations
     if($login == '') {
           $errmsg_arr[] = 'Login ID missing';
           $errflag = true;
     }
     if($password == '') {
           $errmsg_arr[] = 'Password missing';
           $errflag = true;
     }
     
     //If there are input validations, redirect back to the login form
     if($errflag) {
           $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
           session_write_close();

echo "<meta http-equiv=Refresh content=1;url='login-form.php'>";
//$extra1 = 'login-form.php';
//header("Location: http://$host$uri/$extra1");
exit;
     }
     
     //Create query
     $qry="SELECT * FROM members WHERE login='$login' AND passwd='".md5($password)."'";
     $result=mysql_query($qry);
     
     //Check whether the query was successful or not
     if($result) {
           if(mysql_num_rows($result) == 1) {
                 //Login Successful


///////////////////////////////////////////////    THIS LINE APPEARS TO CAUSE IE7 SOME PROBLEMS!!!!!!! //////////////////////////////////////////
//                  session_regenerate_id (TRUE);
///////////////////////////////////////////////    THIS LINE APPEARS TO CAUSE IE7 SOME PROBLEMS!!!!!!! //////////////////////////////////////////
                 $member = mysql_fetch_assoc($result);
                 $_SESSION['SESS_MEMBER_ID'] = $member['member_id'];
                 $_SESSION['SESS_FIRST_NAME'] = $member['firstname'];
                 $_SESSION['SESS_LAST_NAME'] = $member['lastname'];
                 $_SESSION['SESS_ADDRESS'] = $member['address'];
                 $_SESSION['SESS_CITY'] = $member['city'];
                 $_SESSION['SESS_STATE'] = $member['state'];
                 $_SESSION['SESS_LOGIN'] = $member['login'];
                 $_SESSION['SESS_CAPTAIN'] = $member['captain'];
                 $_SESSION['SESS_TEAM'] = $member['team_name'];
                 $_SESSION['SESS_MANUAL_TEAM'] = $member['manual_team'];
     
                 session_write_close();

//echo "<meta http-equiv=Refresh content=1;url='member-index.php'>";

$extra2 = 'member-index.php';
header("Location: http://$host$uri/$extra2");
exit;

           }else {
                 //Login failed
                 
//echo "<meta http-equiv=Refresh content=1;url='login-failed.php'>";

$extra3 = 'login-failed.php';
header("Location: http://$host$uri/$extra3");
exit;
           }
     }else {
           die("Query failed");
     }
?>


Posted by bschultz (bschultz), 10 June 2009
I should add that I can't personally repeat the problem...and I do have IE7...so it's not EVERYBODY with IE7 having problems.

Posted by admin (Graham Ellis), 10 June 2009
I've never used session_regenerate_id - never found the need - and its manual pages are scattered with warnings and problems.  My suggestion would be to find another and cleaner way of achieving your ends - code the application more conventionally

Why are you producing a new cloned session, and simply not holding a status variable to show what yor current page is / your logged in status within your initial session?  That would be so much easier ... what we do all the time and it avoids all these problems!

Posted by bschultz (bschultz), 10 June 2009
I thought you needed a session_write_close(); prior to a header redirect.

The session_regenerate_id (TRUE);  line was commented out a week ago, and I thought that solved the problem...but some people still can't login at times.

The part

Code:
//////////// SET COOKIE DIRECTORY
if (isset($_SERVER['HTTP_HOST'])) {
   if(strpos($_SERVER['HTTP_HOST'], ':') != -1){
  $domain = substr($_SERVER['HTTP_HOST'], 0, strpos($_SERVER['HTTP_HOST'], ':'));
   }
   else{
  $domain = $_SERVER['HTTP_HOST'];
   }
   $domain = preg_replace('`^www.`', '', $domain);
 // Per RFC 2109, cookie domains must contain at least one dot other than the
 // first. For hosts such as 'localhost', we don't set a cookie domain.
 if (count(explode('.', $domain)) > 2) {
ini_set('session.cookie_domain', $domain);
 }
}
//////////// END SET COOKIE DIRECTORY


was something I stumbled upon in troubleshooting the first problem.  The page that this code resides on is a "shared" directory for four websites.  I wanted to make sure that someone wasn't going from one domain to another, and losing their original session.  The links are all relative, so that shouldn't happen, but just wanted to make sure it didn't.

I'm a bit confused as to what you mean by this

Quote:
...simply not holding a status variable to show what yor current page is / your logged in status within your initial session?  That would be so much easier ... what we do all the time and it avoids all these problems!


I'm setting the session variables for login and password and such...if they aren't being kept from one page to the next, a session status variable wouldn't help either, would it..as it would return "false" and redirect to the login page?

I'll admit that this is my first attempt at storing session variables...so I still have lots to learn.

Thanks Graham.

Posted by admin (Graham Ellis), 12 June 2009
For most uses, sessions are very easy indeed to use.   A session_start() at the top of your code, and reading and writing $_SESSION superglobal array members as necessary to save data between successive pages for an individual user is really all you need to start.   You don't need things like session_write_close().

The one addition is to add a session_destroy() when someone logs out (or on a system that they're using for online shopping, when they complete their order) to avoid 'droppings' being left behind - e.g. order placed twice due to bad use of the back button.

Sharing a session across several domains on the same server is likely to be problematic, as sessions are cookie based and typically tied to a domain - but you have said that all links are relative within a site, so that's actually not a problem.

My general advise has to be "simplify" ... I'm getting confused as I read / try to help with references to functions that are new to me, and I've been around for a while. Goodness - there much be something amiss (at least with maintainiablity of code) if I'm having trouble.

Finally, your specfic request for me to explain my comment further.  I use a variable within my session ($_SESSION[current] is my ususal choice) which I test / set to 00 initially, and I then change as I go through the application so that it always stores the page number that the user is currently on.  Example:
0 - not logged in
1 - logged in, displaying top personal message and menu
2- Viewing data
3 - Adding new personal message
4 (and session then cleared) logged out
10 - logged in as admin, admin menu offered
and so on.

This way, the whole top level code of the application goes at a single easy script / URL and there's no need for complex conditions to work out which page you're displaying through a long series of status variables.

Source code example here ... and you can run it on our server from there too

Posted by bschultz (bschultz), 14 June 2009
Graham,

Sorry, but I've been out of town for a few days.

What functions are you talking about?  

Quote:
I'm getting confused as I read / try to help with references to functions that are new to me, and I've been around for a while.


As always, thank you VERY much!

Posted by admin (Graham Ellis), 15 June 2009
Not only the one you deleted, but also your session_write_close and your various ini_set calls relating to sessions.    For a first use of sessions, Brian, what you have looks very much more complex than I would have anticipated!

Posted by bschultz (bschultz), 16 June 2009
I had already gotten rid of session_write_close...the error reporting was also shut off when it went "live".

I haven't heard of any other complaints of people not being able to log in, so removing session_write_close may have done the trick.

The code started much more simplified...it got a fair amount of tweaking when people couldn't log in.  I thought the problem was with the "shared" directory...so the session directory path section got added.

I've thought of removing everything I added...and then just removing the session_regenerate and the session_write_close and seeing if it still worked.  I may just leave it, though, since it's working now (it seems)!

Thanks Graham.



This page is a thread posted to the opentalk forum at www.opentalk.org.uk and archived here for reference. To jump to the archive index please follow this link.

© WELL HOUSE CONSULTANTS LTD., 2024: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 793803 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho