PHP Development
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
 
User Name:
Password:
Remember me
 
Go Back   Dev Articles Community ForumsProgrammingPHP Development

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Display Modes
 
Unread Dev Articles Community Forums Sponsor:
SlickEdit: Code in over 40 languages across 7 platforms. SlickEdit’s unmatched power, speed, and flexibility allows even the most accomplished developers to write better code faster. Download a free trial today!
  #1  
Old June 5th, 2004, 10:31 AM
Archemides Archemides is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: May 2004
Posts: 25 Archemides User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Send a message via ICQ to Archemides Send a message via AIM to Archemides Send a message via Yahoo to Archemides
Cookieless Sessions & User Login

Here is a very simple demonstration of the beginnings of a login page and user
validation using sessions which do not require cookies to be enabled in the
browser.

These two little scripts are based upon what I learned from

"PHP in Easy Steps" by Mike McGrath (published by Barnes & Noble)
ISBN 0-7607-4786-5
(under $20USD)

Page 120 is "Sessions without Cookies"

There is a way to make an unique session identifier available across
an entire website without requiring the browser to accept cookies.

This method appends the unique identifier to the URL in each hyperlink
to other pages on that website.

In HTML we achieve this as follows:

PHP Code:
<a href="target.php?<?php echo(SID); ?>"link </a



while in PHP we do something like this:

PHP Code:
echo "<p><a href=\"session2.php?echo(SID)\">Session 2</a><p>"


Past these two small scripts, and save them as session1.php
and session2.php.

Run session1.php

You should see the session ID displayed (a very long number)

If you click on the link and go to session2.php you should see
the count of visits.

But, if you close your browser (which ends the session),
then reopen the browser and attempt to run session2.php
FIRST (i.e. bypass the session1.php script, which is the
beginnings of a login page), then you should see an error
message warning that the secretpassword is not correct,
and a link to return you to session1.php.

If you return to session1.php, and THEN go back to
session2.php, then everything should work normally,
and you can pass back and forth, and see the persistance
of the variable $count, as it increments with each visit.

Each php script must have session_start(); as its first line.

The example in the Mike McGrath's book, on page 121 omits
session_start(); in the session2.php script, and it does work
fine in his example, but my modified example would not work
until I added session_start(); as the first line.

Since I am also a beginner, teaching myself PHP, please
do offer suggestions and/or corrections to this post.


Initially, I keyed in a simple, modified version of the book's
two examples.

I wanted to demonstrate certain things to myself.
I wanted to always be able to display the session ID.

To my surprise, I noticed that if I started with session1.php
then the SID which I saved persisted between the two scripts.
However, if I launched session2.php first from the browser,
which should test as invalid in password, I noticed that the
SID no longer displayed in either script. I cannot account
for this behavior, but I did succeed in capturing the SID
in a variable so that I could display it in either script.

I discovered that each time one registers a session variable,
it is re-initialized, so one must be careful to initialize
only once.

I then added session.htm as a simple post, to pass a
password to session1 from user input, so that one might
test the behavior of a correct and an incorrect password.
You will notice that the variable $cpassword only has a value
upon the first call to session1.php from session.htm

As you bounce back and forth between session1.php and
session2.php, the $cpassword is no longer initialized.

Also notice that the session persists until you close your
browser. So, if you want to try something different, you
must close your browser and then re-open it.

I experimented with the no-cache option, but it does not
seem to make any difference in behavior (i.e. it does
not somehow force a reload of the script such that the
session would be a new session.


PHP Code:
//====== save as session.htm

<form action="session1.php" method="post">
<
br>If you enter secretyou are authorizedanything else and you are not.<br>
    
password: <input type="text" name="cpassword"><br>
    <
input type="submit">
</
form>

//====== save as session1.php


<?php
 session_start
();
 
header("Cache-Control:no-cache");
 echo 
"cpassword = $cpassword <br>";
 if ( !
session_is_registered("sessionpassword")) {
  
session_register("sessionpassword");
  
$sessionpassword "INITIALIZE";
//  session_register("SIDVALUE");
//  $SIDVALUE = SID;
  
  
if ( !session_is_registered("SIDVALUE")) {
   
session_register("SIDVALUE");
   
$SIDVALUE SID;
   echo 
"SIDVALUE = $SIDVALUE <br>";
 }
}

// if ( $sessionpassword == "INITIALIZE") {
//   $sessionpassword =   $cpassword;
// }
  
  
if ( $cpassword != "") {
   
$sessionpassword =   $cpassword;
   
$cpassword "";
 }

 echo (
$SIDVALUE);
 echo (
"<p> sessionpassword = $sessionpassword <p>" ) ;
 echo 
"<p><a href=\"session2.php?echo(SID)\">Session 2</a><p>";
?>

//==================

// save as session2.php

<?php
 session_start
();
 
header("Cache-Control:no-cache");
 if ( !
session_is_registered("SIDVALUE")) {
   
session_register("SIDVALUE");
   
$SIDVALUE SID;
   echo 
"SIDVALUE = $SIDVALUE <br>";
//  echo "<p><a href=\"session1.php?echo(SID)\">Proceed to Login page</a><p>";
  
echo "<p><a href=\"session.htm\">1Proceed to Login page</a><p>";
  exit();
 }


if ( !
session_is_registered("sessionpassword")) {
  echo(
"1You did not login properly!  $sessionpassword<p>");
//  echo "<p><a href=\"session1.php?echo(SID)\">Proceed to Login page</a><p>";
  
echo "<p><a href=\"session.htm\">2Proceed to Login page</a><p>";
  exit();
}

if (
$sessionpassword != "secret") {
     echo(
"2You did not login properly!<p>");
 
//    echo "<p><a href=\"session1.php?echo(SID)\">Proceed to Login page</a><p>";
     
echo "<p><a href=\"session.htm\">3Proceed to Login page</a><p>";
     exit();
}

if ( !
session_is_registered("count")) {
  
session_register("count");
}


$count++;
echo 
$SIDVALUE "<BR>";
echo (
"<br>You have been here $count times. <br>");
 
echo (
"sessionpassword = $sessionpassword  <p>") ;
 
 
echo 
"<p><a href=\"session1.php?echo(SID)\">Session 1</a><p>";
 
 echo(
SID);

?> 

Last edited by edwinbrains : June 6th, 2004 at 01:35 PM. Reason: [php] and [/php] added

Reply With Quote
  #2  
Old June 5th, 2004, 11:02 AM
Archemides Archemides is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: May 2004
Posts: 25 Archemides User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Send a message via ICQ to Archemides Send a message via AIM to Archemides Send a message via Yahoo to Archemides
session_register vs $_SESSION

I have just received this useful advice from IRC #phpfreaks - I must now study up on $_SESSION so that I may implement this suggestion in my example scripts.

==========
(from IRC #phpfreaks)

You should really assign session variables to $_SESSION, not use session_register(). not only is it faster but it will also work accross more enviroments. certain people trying your example there may not be able to use it.

Reply With Quote
  #3  
Old June 5th, 2004, 11:29 AM
Archemides Archemides is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: May 2004
Posts: 25 Archemides User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Send a message via ICQ to Archemides Send a message via AIM to Archemides Send a message via Yahoo to Archemides
Destroying a Session and other tips!

I did a google search to see if anyone warns against using session_register over $_SESSION, as I was advised in IRC
#phpfreaks channel.

I did not find any warnings so far, but the following URL tells me something I wanted to know about
how to destroy a session.



http://www.phpnull.com/showthread.p...goto=nextoldest
Let's say for example that you wanted to create a part of your site which is only visible to logged in users. You can use sessions to do this. Take a look at the code below.

Eg:
PHP Code:
PHP Code:
 session_register("logged_in"); 
$_SESSION['logged_in'] = "yes"; [/php


The code above firstly registers a 
new global session variable called logged_inNextwe grab the newly created session variable from the $_SESSION ($HTTP_SESSION_VARS in PHP versions before 4.1.0super global array and set its value to yes. If you place this code on your page so as it is only evaluated after a successful user loginthen we can go to the members only page, and check for the value of $_SESSION['logged_in'], and if it returns yes (as it should for logged in usersthen we know that the user is logged in and can continue to output the page.

Let's take a look at the members only page. We'll call it members.php.

PHP Code:
[
php]<?php 
if(!session_is_registered("logged_in")) { 
    die(
"You must be logged in to view this page"); 

if(
$_SESSION['logged_in'] != "yes") { 
    die(
"You must be logged in to view this page"); 

// Guests have been stopped, output the page normally. 
echo "You are a logged in user, and can therefore view this page!"
?> 


Ok, let's break down the code above.

The first thing we do, is check to see if the global session variable logged_in is registered for the user viewing the page. If it is not, the page terminates and an error message is shown to the guest.

PHP Code:
PHP Code:
if(!session_is_registered("logged_in")) { 
    die(
"You must be logged in to view this page"); 




Next, we check the value of the global session variable logged_in, and if it doesn't equal yes then the page terminates in exactly the same way.

PHP Code:
PHP Code:
if($_SESSION['logged_in'] != "yes") { 
    die(
"You must be logged in to view this page"); 




By this point, we have stopped all users who have no logged_in session information, and all users who have another value for the logged_in session information. This is just to make sure that there is no getting around the block for "ordinary" users. This now means that the only users still viewing the page are the ones who are logged in, so you can continue to output your page normally.

Checking whether a session is registered
As mentioned above, the function session_is_registered(); will check to see if a global session variable exists. The syntax is:

Code:
PHP Code:
 session_is_registered(name); 


How do I find use each sessions unique id?
Every user session is identified by a unique session id, which is usually just a long string of numbers and letters such as c0eb8989e012b537b86bf68686e139b7. You can use this session id simply by calling the function session_id();

Eg:

PHP Code:
PHP Code:
<?php 
session_start
(); 
$sid session_id(); 
echo 
"Your session id is ".$sid
?>


Unregistering session information
If you want to unregister a global session variable without completely destroying the session, you can do so by using the session_unregister(); function. The syntax is:

Code:
PHP Code:
 session_unregister(name); 

For example, when a user logs out, you could destroy the logged_in session variable by using this code:

PHP Code:
PHP Code:
 session_unregister("logged_in"); 





Destroying a session

You can completely destroy a session by using the session_destroy(); function. For example, the following script would completely destroy the active user session:

PHP Code:
<?php 
session_start
(); 
// Unset all global session variables. 
session_unset(); 
// Destroy the session. 
session_destroy(); 
?>

Last edited by edwinbrains : June 6th, 2004 at 01:35 PM. Reason: [php] and [/php] added

Reply With Quote
  #4  
Old June 5th, 2004, 02:20 PM
Archemides Archemides is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: May 2004
Posts: 25 Archemides User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Send a message via ICQ to Archemides Send a message via AIM to Archemides Send a message via Yahoo to Archemides
Next Step: Create users table & mysql password()

We may take what we have learned about sessions and
use it as a foundation for a user login password validation
routine.


Let's create a simple html post form to pass nick, email and password to a
php validation script, which we have yet to write
PHP Code:
// save as userlogin.htm

<form action="userlogin.php" method="post">

    
nick: <input type="text" name="cnick"><br>
    
email: <input type="text" name="cemail"><br>
    
password: <input type="text" name="cpassword"><br>
    <
input type="submit">

</
form




userlogin.php has not been written yet, but the following shows how it might
look for the user in a user table, and test for a valid password.

We might start with the simple beginnings of a script to show
that our submit form is working and that we can access
the variables which it passed

PHP Code:
//save as userlogin.php
 
<?php
 session_start
();
 
header("Cache-Control:no-cache");
 echo 
"cnick = $cnick <br>";
 echo 
"cemail = $cemail <br>";
 echo 
"cpassword = $cpassword <br>";
 
$encrypted password("$cpassword");
 echo 
"password(cpassword) = $encrypted <br>";
 exit(); 


OOPS!! PHP does NOT have a password() function! Only MySQl has a password() function.


Creating a user table and adding one test record
PHP Code:
// save as createuser.php


<?php 


$conn 
mysql_connect("$location","$username","$password"); 
if (!
$conn) die ("Could not connect MySQL"); 
mysql_select_db($database,$conn) or die ("Could not open database"); 
 

 

mysql_query("CREATE TABLE user (
    id INT not null primary key auto_increment,
    nick VARCHAR(40),
    email VARCHAR(40),
    password VARCHAR(40),
    testpassword VARCHAR(40))"
);

$insert "INSERT INTO user (id, nick, email, password, testpassword)
    VALUES ('', 'testnick', 'testemail', 'testpassword', '')"
;

    
mysql_query($insert) or die ("Could not add data to the table");

?> 




Exploring the MySQL password() function.

PHP has no password() function to correspond to the MySQL password() function.

One simple minded way to access the password() in php would be to use a
mysql update command to write a password to a field, and then read it back.

Of course, the idea of password() is that the user has privacy, and not even the
webmaster knows the actual password. But for educational purposes, it is interesting
for us to look at what the mysql password() function generates.


PHP Code:
// save as listoneuser.php

<?php 

// obviously here, you must supply your own actual mysql username and password,etc.

$conn mysql_connect("$location","$username","$password");
if (!
$conn) die ("Could not connect MySQL"); 
mysql_select_db($database,$conn) or die ("Could not open database"); 
 

$cpassword "testpassword";

$query "update user set testpassword = password('$cpassword') where id = '1'";
$result mysql_query($query);


echo 
"First, let's examine our test row in users, selecting it by id = 1.";

$query "SELECT * FROM user WHERE id = '1'";
$result mysql_query($query); 
$numrows mysql_num_rows($result); 

 

echo 
"You have $numrows user(s) in the database";

echo(
"<table>\n");

echo(
"<tr><th>id</th><th>nick</th><th>email</th><th>password</th><th>testpassword</th></td></tr> <p>");

while(
$row mysql_fetch_array($result)){ 

    echo(
"<tr><td>$row[id]</td><td>$row[nick]</td><td>$row[email]</td><td>$row[password]</td><td>$row[testpassword]</td></tr>\n");




echo(
"<table>\n");

echo 
"<hr>";

echo 
"Now, let's use the mysql password function to do a select on a match to testpassword using the MySQL password() function.";


$query "SELECT * FROM user WHERE testpassword = password('$cpassword')";
$result mysql_query($query);
$numrows mysql_num_rows($result);

echo 
"You have $numrows user(s) in the database";


echo(
"<table>\n");


echo(
"<tr><th>id</th><th>nick</th><th>email</th><th>password</th><th>testpassword</th></tr>\n");

while(
$row mysql_fetch_array($result)){

    echo(
"<td>$row[id]</td><td>$row[nick]</td><td>$row[email]</td><td>$row[password]</td><td>$row[testpassword]</td><p>");

}
echo(
"</table>there <p>");
?> 

Last edited by edwinbrains : June 6th, 2004 at 01:36 PM. Reason: [php] and [/php] added

Reply With Quote
  #5  
Old June 5th, 2004, 03:12 PM
Archemides Archemides is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: May 2004
Posts: 25 Archemides User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Send a message via ICQ to Archemides Send a message via AIM to Archemides Send a message via Yahoo to Archemides
User/Password Validation

User/Password Validation


Here is a userlogin.htm with default valid test values

PHP Code:
<form action="userlogin.PHP" method="post">
    <
p>Submit with default values to be validated, or change one or more
    values slightly so 
as to see a  failure validation.<p>


    
nick: <input type="text" name="cnick" value="testnick"> <br>
    
email: <input type="text" name="cemail" value="testemail"> <br>
    
password: <input type="text" name="cpassword" value="testpassword"><br>
    <
input type="submit">
</
form





Here is a slightly more elaborate userlogin.php

PHP Code:
<?php
 session_start
();
 
header("Cache-Control:no-cache");
 echo 
"cnick = $cnick <br>";
 echo 
"cemail = $cemail <br>";
 echo 
"cpassword = $cpassword <br>";

 
$conn mysql_connect("$location","$username","$password");
 if (!
$conn) die ("Could not connect MySQL");
 
mysql_select_db($database,$conn) or die ("Could not open database");

 
$query "SELECT * FROM user WHERE nick = '$cnick' and email = '$cemail' and password(password) = password('$cpassword')";
 
$result mysql_query($query);
 
$numrows mysql_num_rows($result);

echo 
"You have $numrows user(s) in the database";

if (
$numrows == 1) {
 echo 
"<p>This user has been validated.";
  
$row mysql_fetch_array($result);
  echo 
"<p>id = " .  $row[id];
  echo 
"<p>nick = " $row[nick];
  echo 
"<p>email = " $row[email];
  echo 
"<p>password = " $row[password];
  echo 
"<p>testpassword = " $row[testpassword];
} else {
 echo 
"<p>This user has failed validation.";
}

?>

Last edited by edwinbrains : June 6th, 2004 at 01:36 PM. Reason: [php] and [/php] added

Reply With Quote
  #6  
Old June 5th, 2004, 04:18 PM
Archemides Archemides is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: May 2004
Posts: 25 Archemides User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Send a message via ICQ to Archemides Send a message via AIM to Archemides Send a message via Yahoo to Archemides
Capturing info on users who log in

Let's add some more fields to our user table and capture some information
about users who validate.


PHP Code:
// save as alterusertable.php and test it with userlogin.htm

<?php 


$conn 
mysql_connect("$location","$username","$password"); 
if (!
$conn) die ("Could not connect MySQL"); 

mysql_select_db($database,$conn) or die ("Could not open database"); 


mysql_query("ALTER TABLE user ADD date_created DATETIME");

mysql_query("ALTER TABLE user ADD date_modified DATETIME");

mysql_query("ALTER TABLE user ADD date_lastvisit DATETIME");

mysql_query("ALTER TABLE user ADD ip_address VARCHAR(30)");

mysql_query("ALTER TABLE user ADD referrer VARCHAR(60)");

mysql_query("ALTER TABLE user ADD browser VARCHAR(60)");

mysql_query("ALTER TABLE user ADD visits INT");


$query "update user set date_created = now() where id = '1'";
$result mysql_query($query);

$query "update user set date_modified = now() where id = '1'";
$result mysql_query($query);


$query "update user set date_lastvisited = now() where id = '1'";
$result mysql_query($query);


$fields mysql_list_fields("$database""user"$conn);
$columns mysql_num_fields($fields);

for (
$i 0$i $columns$i++) {
   echo 
mysql_field_name($fields$i) . "<br>";
}

?> 



===========================

Now, let's capture some information about users who validate:


PHP Code:
// save this as userlogin.php

<?php
 session_start
();
 
header(