Jump to content

Recommended Posts

I can not find out what is wrong here.  I'm trying to access a session to write something to it from anyother page.  I have a custom handler which I'll copy below.  If anyone has a good session handler, let me know where I can get it.

The following is my sess.php file (NOTE: the database information has been removed)

[code]<?php
/*
// MySQL Database Description

CREATE TABLE sessions (
  ses_id varchar(32) NOT NULL default '',
  ses_time int(11) NOT NULL default '0',
  ses_start int(11) NOT NULL default '0',
  ses_value text NOT NULL,
  PRIMARY KEY  (ses_id)
);
*/

/* Create new object of class */
$ses_class = new session();

/* Change the save_handler to use the class functions */
session_set_save_handler (array(&$ses_class, '_open'),
                          array(&$ses_class, '_close'),
                          array(&$ses_class, '_read'),
                          array(&$ses_class, '_write'),
                          array(&$ses_class, '_destroy'),
                          array(&$ses_class, '_gc'));

/* Start the session */
session_start();

class session
{
    /* Define the mysql table you wish to use with
      this class, this table MUST exist. */
    var $ses_table = "sessions";

    /* Change to 'Y' if you want to connect to a db in
      the _open function */
    var $db_con = "Y";

    /* Configure the info to connect to MySQL, only required
      if $db_con is set to 'Y' */
    var $db_host = "";
    var $db_user = "";
    var $db_pass = "";
    var $db_dbase = "";

    /* Create a connection to a database */
    function db_connect() {
        $mysql_connect = @mysql_pconnect ($this->db_host,
                                          $this->db_user,
                                          $this->db_pass);
        $mysql_db = @mysql_select_db ($this->db_dbase);

        if (!$mysql_connect || !$mysql_db) {
            return FALSE;
        } else {
            return TRUE;
        }
    }

    /* Open session, if you have your own db connection
      code, put it in here! */
    function _open($path, $name) {
        if ($this->db_con == "Y") {
            $this->db_connect();
        }

        return TRUE;
    }

    /* Close session */
    function _close() {
        /* This is used for a manual call of the
          session gc function */
        $this->_gc(0);
        return TRUE;
    }

    /* Read session data from database */
    function _read($ses_id) {
        $session_sql = "SELECT * FROM " . $this->ses_table
                    . " WHERE ses_id = '$ses_id'";
        $session_res = @mysql_query($session_sql);
        if (!$session_res) {
            return '';
        }

        $session_num = @mysql_num_rows ($session_res);
        if ($session_num > 0) {
            $session_row = mysql_fetch_assoc ($session_res);
            $ses_data = $session_row["ses_value"];
            return $ses_data;
        } else {
            return '';
        }
    }

    /* Write new data to database */
    function _write($ses_id, $data) {
        $session_sql = "UPDATE " . $this->ses_table
                    . " SET ses_time='" . time()
                    . "', ses_value='$data' WHERE ses_id='$ses_id'";
        $session_res = @mysql_query ($session_sql);
        if (!$session_res) {
            return FALSE;
        }
        if (mysql_affected_rows ()) {
            return TRUE;
        }

        $session_sql = "INSERT INTO " . $this->ses_table
                    . " (ses_id, ses_time, ses_start, ses_value)"
                    . " VALUES ('$ses_id', '" . time()
                    . "', '" . time() . "', '$data')";
        $session_res = @mysql_query ($session_sql);
        if (!$session_res) {   
            return FALSE;
        }        else {
            return TRUE;
        }
    }

    /* Destroy session record in database */
    function _destroy($ses_id) {
        $session_sql = "DELETE FROM " . $this->ses_table
                    . " WHERE ses_id = '$ses_id'";
        $session_res = @mysql_query ($session_sql);
        if (!$session_res) {
            return FALSE;
        }        else {
            return TRUE;
        }
    }

    /* Garbage collection, deletes old sessions */
    function _gc($life) {
        $ses_life = strtotime("-5 minutes");

        $session_sql = "DELETE FROM " . $this->ses_table
                    . " WHERE ses_time < $ses_life";
        $session_res = @mysql_query ($session_sql);


        if (!$session_res) {
            return FALSE;
        }        else {
            return TRUE;
        }
    }
}
?>[/code]

Next, I have my index.php file.  Which looks like this;

[code]<?php
//  start the session for someone logging in.  The purpose for sessions for this
//  site is only to keep track of any admins logged in.  However, this custom
//  session can be used for more.
require('includes/sess.php');
//  load all the variables
require('includes/configure.php');
?>
<!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">
<link href="stylesheet.css" rel="stylesheet" type="text/css">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>B-N</title>
</head>
<body>
  <!-- main table which must be centered -->
  <center> 
  <table width="<?php echo SITE_WIDTH; ?>" border="0" cellspacing="0" cellpadding="0">
    <tr>
  <!-- header for each page -->
  <td bgcolor="#0099FF" height="100" colspan="2"><?php require('includes/header.php'); ?></td>
</tr>
<tr>
  <!-- navigation for each page -->
  <td bgcolor="#0066CC" colspan="2"><?php require('includes/navigation.php'); ?></td>
</tr>
    <tr>
  <!-- left column for each page -->
  <td width="<?php echo COLUMN_WIDTH; ?>" align="left"><?php require('includes/column_left.php'); ?></td>
  <!-- home page for index.php -->
  <!-- paste and copy this entire page and edit this section for your page -->
  <td bgcolor="#00CC99" >
    <center>
  Main Page (index.php)
    </center>  
  </td>
</tr>
<tr>
  <!-- footer for each page -->
  <td colspan="2"><?php require('includes/footer.php'); ?></td>
</tr>
  </table>
  </center>
</body>
</html>[/code]

At the bottom of the footer.php (which i will not display here) there is a link to the admin login.  Here is the login.php file.  (NOTE: The database information has been deleted alone with the encrytpion method.)

[code]<?php
session_start();
require('includes/configure.php');
?>
<!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">
<link href="stylesheet.css" rel="stylesheet" type="text/css">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>B-N : Login</title>
</head>
<body>
  <!-- main table which must be centered -->
  <center> 
  <table width="<?php echo SITE_WIDTH; ?>" border="0" cellspacing="0" cellpadding="0">
    <tr>
  <!-- header for each page -->
  <td bgcolor="#0099FF" height="100" colspan="2"><?php require('includes/header.php'); ?></td>
</tr>
<tr>
  <!-- navigation for each page -->
  <td bgcolor="#0066CC" colspan="2"><?php require('includes/navigation.php'); ?></td>
</tr>
    <tr>
  <!-- left column for each page -->
  <td width="<?php echo COLUMN_WIDTH; ?>" align="left"><?php require('includes/column_left.php'); ?></td>
  <!-- home page for index.php -->
  <!-- paste and copy this entire page and edit this section for your page -->
      <td bgcolor="#00CC99" >
    <?php
  //  set up for any error messages
  $message="";
  //  status if logged in (0=false, 1=true)
  $login_status=0;
 
      $encpass = '';
   
      if(isset($_POST['login'])){
     
            $user = $_POST['username'];
            $pass = crypt($_POST['password'], $encpass);
           
            //  open  connection to the server
            @mysql_pconnect("","","")
              or die("Could not connect to MySQL server!");
 
            //  open connection to the database
            @mysql_select_db("")
              or die("Could not select database!");
           
            //  start checking the table
            $query = "SELECT id, user
                      FROM admin_login 
                      WHERE user = '$user' AND pass = '$pass'";

            $result = mysql_query($query);
           
       
           
            if(mysql_num_rows($result) != 1){
              $message = "Invalid Username/Password";
            } else {
              $login_status=1;
              //  send admin to home page in 3 seconds.  if you want to change the time,
              //  edit the content="3".  any number entered is in seconds.
              echo "<br><center>Login Successful.  Please wait...</center><br>";
           
           
              $_SESSION['user']=$user;
           
           
?>            <meta http-equiv="refresh" content="3;url=http://b-n.com/bn/index.php">
<?php
            }// END if(mysql_num_rows($result) != 1){
          } elseif (isset($_POST['reset'])){
//  reset pass or username!  must find out how to send email
          } elseif (isset($_POST['cancel'])){
            echo "<meta http-equiv=\"refresh\" content=\"0;url=http://b-n.com/bn/index.php\">";
          }//  END  if(isset($_POST['login'])){ 
         
?>
          <center>
    <table border="0">
      <tr>
        <td colspan="2">
          <center>
            <font size="3"><b>Admin Login</b></font><br><br>
    <font size="2">Please login with your username and password.<br>Press the reset button to reset either your                  username or password.<br>Press cancel to return to 'Home'.</font><br><br>
    <font color="#FF0000"><?php if($message) echo $message; ?></font>
          </center>
        </td>
      </tr>
      <tr>
        <td align="right" valign="top">
          Username:<br>
          Password:
        </td>
        <td align="left">
          <form method="post" action"login.php">
                    <input type="text" name="username" size="15" maxlength="15" value="<?php echo (isset($_POST['username'])) ?                                                                            htmlspecialchars($_POST['username']) : ""; ?>"/> <br>
                    <input type="PASSWORD" name="password" size="15" maxlength="20" value="" />
                </td>
    </tr>
  <tr>
    <td colspan="2">
        <center>
                    <input type="submit" name="login" value="Login" />
                    <input type="submit" name="reset" value="Reset" />
                    <input type="submit" name="cancel" value="Cancel" />
                    </center>
                  </form>
        </td>
    </tr>
  </table>
    </center>
  </td>
</tr>
<tr>
  <!-- footer for each page -->
  <td colspan="2"><?php require('includes/footer.php'); ?></td>
</tr>
  </table>
  </center>
</body>
</html>[/code]

Now, keep in mind, the login.php file is still being developed so im sorry for the miss.  My problem is here, in the login.php file.  Once the the user types in the correct username and password, hits login button, i want the session to store the login name. So I put the following code in the login.php file above:

[code]$_SESSION['user']=$user;[/code]

When i try to echo the session user OR if I check the mySQL table there is nothing in the 'value' field.  All i see in the table is that the session was created but the value is nothing.  Now when I try to write to the session in the index.php file, everything works fine.

Why doesn't this work in the login.php file and how can I write to the session?  I need to write to the session on other webpages.

Any help would be nice.

Any again, if anyone sees an error in the session handler let me know, OR if you know of a better one I can get. 

Thanks,

|Wstar|
Link to comment
https://forums.phpfreaks.com/topic/18315-session-not-working-on-other-pages/
Share on other sites

Thanks for the fast reply ober.  I moved session_star(); to the top of every page and it still doesnt work.  I did find something out though.  On the page where i put include('includes/sess.php') I can write to the session just fine.  But on the other pages, i can not, i can only read.

I'm useing echo $_SESSION['user']; to view the user in the session.  AND I'm checking the mySQL database table to see if the data got inserted.

The php version I'm using is 4.3.10.

Is there some code im missing so i can write to the session on other pages? (besides the one in which i include the sess.php file)

Thanks,
|Wstar|
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.