[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

PHP Sessions work on WAMP localhost but not on LAMP Online hosting

Posted on 2007-07-21
19
Medium Priority
?
1,934 Views
Last Modified: 2013-12-12
Hi All
I have created a php site, on my local host I use WAMP. And it works fine..on the linux server the login process does not work. This is simply because of the fact that global registers are of on the server.
I have to find a work around to this.
I will display and describe the relevant pieces of code below. The sessions process provide access to the backoffice to authors that want to post on the site..there are different sections for different topics in the backoffice. And the database table for authors contains all the section and a yes/no switch to determine if the author has access to a particular section

In the login page I have a form that direct the input to validate.php ( i have setup the backoffci)

  $sql = "SELECT *
           FROM author
           WHERE name = '$userId'
                 AND password = '$hash'";

   $result = mysql_query($sql)
             or die('Query failed. ' . mysql_error());
     
   if (mysql_num_rows($result) == 1) {
      // the user id and password match,
      // set the session
      $_SESSION['db_is_logged_in'] = true;
        $row = mysql_fetch_array($result);
         $count = 0;

//what happens here is that I check the mysql result to see to which sections the author has access..the code below would result in $_SESSION['politics'] = true or $_SESSION['fun'] = false for example, this worked quite well on windows. And the process itself works fine on the Linux host.

            foreach($row as $key=>$value) {
            $$key = $value;
            //echo $count;
            if($count > 9)
            {
            session_register($key);
            $_SESSION[$key] = $value;
            }            
            $count++;
            }

The real problems begin when the backoffice of the site is entered after validate.php...the author do not have access to their sections,  the session code in the inner sections is simple :

I have include a session.php file in every backoffice file.
The file starts with
session_start()
and some code follows...however the session variable created previously in validate.php are not availabe anymore ...
if I do print_r($_SESSION) I only get one registered session variable instead of the 13 + variables that should be available.
I have read on the internet that global variables can cause this problem...on my hosting I cant change that setting is there a php work around
0
Comment
Question by:http:// thevpn.guru
  • 10
  • 9
19 Comments
 
LVL 17

Expert Comment

by:psimation
ID: 19537650
Use the correct syntax for accessing variables -  this way your code will work whether globals is turned on or off.

If you POST variables via a Form, then access them on the action page by $_POST['form_filed_name']
If you append the variable in your URl, the access them on the resulting page by $_GET['var_name_in_url']

Also, instead of using session_register(), just make sure that your session is started on the page where you want to assign variables into session; the action of doing this:

$_SESSION['whatever'] = "some_value";

is enough to "register" the variable and it's value - but again, only if you started the session on the page itself.



0
 
LVL 19

Author Comment

by:http:// thevpn.guru
ID: 19537692
I did the
$_SESSION['whatever'] = "some_value";
but only on the validate page..I dont get it what is the idea of using session if I have to reassign the value of the session variables in everypage...

As for using GET or POST...I use the following approach

In validate.php I register and assign values to all session variables that I need. and then redirect the browser to the mainpage. I dont use a form. However even if I would want to use a form and execute something like a javascript this.submit.form or use GET to send session variables through the URL...that is not feasible for me ...take the following example into the consideration...
I parse the variables through either the URL or through a POST form...I retrieve the results on the target page and act accordingly...however the target page itself contains many forms some POST and some GET depending on the case...once one of those forms is submitted the variables passed previously will cease to exist....so NO that is not what I want...I want my session registers to work throughout my site...what else are sessions good for..

Thanks for your help
0
 
LVL 17

Expert Comment

by:psimation
ID: 19537887
session_start() is the key to your problems.  You don't have to register session variables on each page, you just need to ensure that your session stays in tact throughout the life of your application, regardless of where the user navigates to.

To ensure that, You MUST have session_start() at the very top of each page in your application, else the session is broken, and your session variables will be lost.

For instance, if you have something like this:

page1.php -> page2.php -> page3.php

If you forget to put session_start() at the top of page2.php (but it is there on page3.php and page1.php) then there is a good chance that session_start() will start a NEW session on page3.php, thereby destroying all the variables you added to the $_SESSION[] array on page1.php , and page2.php- even if you use session_register. session _start() should actually have been called something more desciptive, like "session_manage()" or "session_controll()", because it doesn't just START a session, it also RESUMES it if it detects an existing session.

Using $_SESSION['whatever'] = "xxx" for the first time is equivalent to "registering" the variable called 'whatever', and if your session remains in tact, the value will remain "xxx" until you do $_SESSION['whatever'] = "yyy" on some other page in the session.

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 19

Author Comment

by:http:// thevpn.guru
ID: 19538001
hhmmm....psimation..I think I have one loose link where there is no session_start i need to check it out and get back to you on it..if it works the points are all yours
0
 
LVL 19

Author Comment

by:http:// thevpn.guru
ID: 19538168
Psimation...what I did was the following...I start a session validate.php and register the session variables..after that I redirect the browser to mainpage.php where I do a session_start() on the top of the page..what I did on the top of the page is the following
in mainpage.php
session_start();
print_r($_SESSION);
exit();
what I get printed is the following:
Array ( [db_is_logged_in] => 1 )

If I do:
print_r($_SESSION);
exit();

on the bottom of the validate.php page that directly leads to mainpage.php
I get the following :

Array ( [db_is_logged_in] => 1 [5] => true [Interviews] => true [6] => false [24Hours] => false [7] => false [Components] => false [8] => true [Politics] => true [9] => true [Economics] => true [10] => true [Culture] => true [11] => true [Health] => true [12] => false [Sports] => false [13] => true [Arts] => true [14] => true [Fashion] => true [15] => false [Journal] => false [16] => true [Technology] => true [17] => true [Misc] => true [18] => true [Youth] => true [19] => false [Writer] => false [20] => true [Opinions] => true [21] => true [Research] => true [22] => false [FromWorld] => false [23] => true [Space] => true [24] => true [Problems] => true [25] => true [Jokes] => true [26] => true [Syria] => true [27] => false [Morocco] => false [28] => false [Egypt] => false [29] => true [Gulf] => true [30] => true [ChangePass] => true [31] => true [AdminPanel] => true [32] => true [archive] => true [name] => admin [id] => deaad8bceef8234e852edbb563f8f7fd [adadID] => 1 [retries] => 1 )


I dont get it....
0
 
LVL 19

Author Comment

by:http:// thevpn.guru
ID: 19538183
I mean why is only [db_is_logged_in] => 1  passed..
0
 
LVL 17

Expert Comment

by:psimation
ID: 19538197
Can you post all your code?
0
 
LVL 19

Author Comment

by:http:// thevpn.guru
ID: 19538209
Validate.php

<?php
session_start();
$errorMessage = '';
//print_r($_POST);
if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) {
   include("../connexion.php");
   $userId = $_POST['txtUserId'];
   $password = $_POST['txtPassword'];
   $hash = $password;
   // check if the user id and password combination exist in database
   $sql = "SELECT *
           FROM author
           WHERE name = '$userId'
                 AND password = '$hash'";
   $result = mysql_query($sql)
             or die('Query failed. ' . mysql_error());
 
   if (mysql_num_rows($result) == 1) {
      // the user id and password match,
      // set the session
        //echo "in here";
      $_SESSION['db_is_logged_in'] = true;
        $row = mysql_fetch_array($result);
         $count = 0;
            foreach($row as $key=>$value) {
            $$key = $value;
            if($count > 9)
            {
            session_register($key);
            $_SESSION["$key"] = $value;
            //echo $_SESSION[$key];
            }            
            $count++;
            }
            
            //print_r($_SESSION);
      // after login we move to the main page
        session_register('name');
      $_SESSION['name'] = $_POST['txtUserId'];
        $id = session_id();
        session_register('id');
            $_SESSION['id'] = $id;
            
            
        session_register('adadID');       
        $_SESSION['adadID'] = 1;      
                    
        session_register('retries');
        $_SESSION['retries'] = TRUE;
        //print_r($_SESSION);
        //exit();
        header( 'Location: sitemap/mainpage.php' )
        
        ?>
        <script type="text/javascript">
        window.location = 'sitemap/mainpage.php';
        </script>
        <?php
 
   }
   else {
      $_SESSION['retries'] = FALSE;           
        ?>
        <script type="text/javascript">
        window.location = './index.php';
        </script>
        <?php   }
  mysql_close();
}
?>


in mainpage.php

<?php
session_start();
print_r($_SESSION);.....rest of code..
0
 
LVL 19

Author Comment

by:http:// thevpn.guru
ID: 19539970
Any comments psimation.."thanks for following up on my other posts as well"
0
 
LVL 17

Expert Comment

by:psimation
ID: 19539978
I've basically just "cleaned" you existing code a bit for easier readability ( ie, as little lines a spossible) - but I still can't really see where the session vars could get lost. - only way that I can see as of now if the fact that you are redirecting the user; not sure if that breaks a session or not...

here is the code so far:

<?php
session_start();
$errorMessage = '';
if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) {
   include("../connexion.php");
   $userId = $_POST['txtUserId'];
   $password = $_POST['txtPassword'];
   $hash = $password;
    $sql = "SELECT * FROM author WHERE name = '$userId' AND password = '$hash'";
   $result = mysql_query($sql) or die('Query failed. ' . mysql_error());
 
   if (mysql_num_rows($result) == 1) {
      $_SESSION['db_is_logged_in'] = true;
      $row = mysql_fetch_array($result);
      $count = 0;
            foreach($row as $key=>$value) {
              $$key = $value;
                  if($count > 9) {
                        session_register($key);
                        $_SESSION["$key"] = $value;
                  }            
            $count++;
        }
      $_SESSION['name'] = $_POST['txtUserId'];
      $id = session_id();
      $_SESSION['id'] = $id;
      $_SESSION['adadID'] = 1;                
      $_SESSION['retries'] = TRUE;
      header( 'Location: sitemap/mainpage.php' );      
      echo "
      <script type=\"text/javascript\">
      window.location = 'sitemap/mainpage.php';
      </script>
      ";
   } else {
      $_SESSION['retries'] = FALSE;            
      echo"
      <script type=\"text/javascript\">
      window.location = './index.php';
      </script>
      ";
   }
        mysql_close();
}
?>
0
 
LVL 17

Expert Comment

by:psimation
ID: 19539983
ps, DON'T use session_start() in the connecion.php file that you include on line 5...
0
 
LVL 19

Author Comment

by:http:// thevpn.guru
ID: 19540115
hm..nope just an ordinary mysql_connect..
0
 
LVL 17

Expert Comment

by:psimation
ID: 19540135
OK, just humor me for a while; comment out the redirect and javascript redirect code and replace it with a href to mainpage.php and see if you still "lose" your session vars...
0
 
LVL 19

Author Comment

by:http:// thevpn.guru
ID: 19540160
Same thing
0
 
LVL 17

Expert Comment

by:psimation
ID: 19540174
OK, let's go back a step; you say it works fine on your "localhost", but not when published...

Can you check that your browser is in fact accepting coockies from the published site - it may be that your security settings are preventing coockies for "non local" zone.
0
 
LVL 19

Author Comment

by:http:// thevpn.guru
ID: 19540210
well it is the same on FF ..and IE...and from other PC...and I set the security level to low..and added the site to the trusted sites...nothin changes..

thanks for you help..:)
any more ideas ?
0
 
LVL 17

Expert Comment

by:psimation
ID: 19540229
and the PHP versions and settings on the local and live machines are identical (except for the globals)?
0
 
LVL 19

Author Comment

by:http:// thevpn.guru
ID: 19540237
well .. no I have php 5 with global settings on my wamp localhost and for the online host
Server version: 4.1.21-standard
0
 
LVL 17

Accepted Solution

by:
psimation earned 1500 total points
ID: 19540345
OK, let's try something really basic and see if we can progress:

Do this:

page1.php
<?php
session_start();
$_SESSION['var1'] = "page1";
?>
<a href="page2.php">Click</a>

page2.php
<?php
session_start();
$_SESSION['var2'] = "page2";
echo $_SESSION['var1'];     //should echo "page1"
$_SESSION['var1'] = "page1_revised_on_page2";
?>
<a href="page3.php">Click</a>

page3.php
<?php
session_start();
echo $_SESSION['var1']; //should give "page1_revised_on_page2"
echo "<br>";
echo $_SESSION['var2']; //should give "page2"
?>

0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
This holiday season, we’re giving away the gift of knowledge—tech knowledge, that is. Keep reading to see what hacks, tips, and trends we have wrapped and waiting for you under the tree.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses
Course of the Month17 days, 23 hours left to enroll

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question