SitePoint Sponsor

User Tag List

Results 1 to 16 of 16
  1. #1
    SitePoint Addict
    Join Date
    Jul 2011
    Location
    Hyderabad,India.
    Posts
    327
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    login using time

    hi all,
    i have database namely shopping for login with 3 fields
    namely id,username and password as shown below
    Code:
    create table login(id auto increment primary key,username varchar(20),password varchar(30));
    it will be shown as
    id username password
    1 admin admin123
    2 ravi ravi123

    i have also written a code in php so that when ever the new user enters using the time function it should
    be stored in the database
    below is he code....
    Code:
    <?php
    if (!isset($_SESSION)) 
    {
     session_start();
    }
    $now = time();
    // time the session should have expired
    $limit = $now;
    // check the time of the last activity
    if (isset($_SESSION['last_activity']) && ($_SESSION['last_activity'] < $limit)) 
    {
     // clear the session array 
     $_SESSION = array();
     header('Location:logout.php');
     exit;
    } 
    else 
    {
    // the current time
    $_SESSION['last_activity'] = $now;
    }
    ?>
    tell me how to modify the above code so that when the new user logins that must be stored in the login table.....

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,861
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    How do you distinguish between two people with the same login and password so as to know which id belongs to who?
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  3. #3
    SitePoint Addict
    Join Date
    Jul 2011
    Location
    Hyderabad,India.
    Posts
    327
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    reply

    first when the new user logins it will ask for his details and once he fills his details and next time
    again when he enters it should not ask for his details because for first time when he registered
    his details will be stored in the database

  4. #4
    SitePoint Addict
    Join Date
    Jul 2011
    Location
    Hyderabad,India.
    Posts
    327
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by felgall View Post
    How do you distinguish between two people with the same login and password so as to know which id belongs to who?
    below is the code i have written.tell me how to modify in the below code
    first the session must be stored if he is a new person and it must check whether the users session
    is same as stored in the database.if same then continue else give new session to him.....

    Code:
    <?php
    if (!isset($_SESSION)) 
    {
     session_start();
    }
    $now = time();
    $limit = $now;
    if (isset($_SESSION['last_activity']) && ($_SESSION['last_activity'] < $limit)) 
    {
     $_SESSION = array();
     header('Location:logout.php');
     exit;
    } 
    else 
    {
    // the current time
    $_SESSION['last_activity'] = $now;
    }
    ?>

  5. #5
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,748
    Mentioned
    73 Post(s)
    Tagged
    0 Thread(s)
    if (!isset($_SESSION))
    {
    session_start();
    }

    This will never fire. $_SESSION is a superglobal. It always exists.
    session_start should be called on every page. Remove your if.

    if (isset($_SESSION['last_activity']) && ($_SESSION['last_activity'] < $limit))
    You've just set $limit to $now, which is set to time(). Unless the user has been visiting your site multiple times every second, $_SESSION['last_activity'] < $limit will always be true. $limit should have a value subtracted from it to figure out the allowed time of inactivity.

  6. #6
    SitePoint Addict
    Join Date
    Jul 2011
    Location
    Hyderabad,India.
    Posts
    327
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    reply

    whether this will work

    Code:
    <?php
     session_start();
    if(!isset($_SESSION))
    {
    $now = time();
    $limit = $now;
    if (isset($_SESSION['last_activity']) && ($_SESSION['last_activity'] < $limit)) 
    {
     $_SESSION = array();
     header('Location:logout.php');
     exit;
    } 
    else 
    {
    // the current time
    $_SESSION['last_activity'] = $now;
    }
    }
    ?>

  7. #7
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,748
    Mentioned
    73 Post(s)
    Tagged
    0 Thread(s)
    if(!isset($_SESSION))

    As i said, $_SESSION is ALWAYS set. So this check will always fail.

    Are you perhaps trying to say
    if(!isset($_SESSION['last_activity']))

    ?

  8. #8
    SitePoint Addict
    Join Date
    Jul 2011
    Location
    Hyderabad,India.
    Posts
    327
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    reply

    below is the code i have written for a user he can
    enter any time so that for next time it remembers him....
    is it correct......
    Code:
    <?php
    session_start();
    //connect to database
    $db = mysql_connect("localhost","root","") or die(mysql_error());
    mysql_select_db("shopping", $db) or die(mysql_error());
    mysql_set_charset("utf8", $db) or die(mysql_error());
    $islogged = FALSE;
    if(isset($_SESSION["last_activity"])) 
    {
      if(time() - $_SESSION["last_activity"] > LIMIT ) 
      {
        session_destroy();
        header("Location:logout.php");
        exit;
      }
      $_SESSION["last_activity"] = time();
      $islogged = TRUE;
    }
    else 
    {
      if(isset($_POST["username"]) && isset($_POST["password"])) 
      {
        $result = mysql_query(
          "SELECT DISTINCT * FROM login WHERE " .
          "`username` = '{$_POST["username"]}' AND " .
          "`password` = '{$_POST["password"]}'"
        );
        if(!$result) die( mysql_error());
        if( mysql_num_rows($result)) 
    	{
          $_SESSION["last_activity"] = time();
          header("Location:products.php");
    	  die();
    	  $islogged = TRUE;
        }
        else 
    	{
          $error = "username and password do not match";
        }
      }
    }
    ?>
    
    <?php if(!$islogged): ?>
    <form action="<?php $_SERVER['HTTP_REQUEST']?>" method="POST">
    <?php if( isset($error) ): ?>
    <p><?php $error?></p>
    <?php endif; ?>
    Username:<input type="text" name="username" value="<?php isset($_POST['username']) ? $_POST['username'] : ''?>"
    </br>
    Password:<input type="password" name="password" value="<?php isset($_POST['password']) ? $_POST['password'] : ''?>"
    </br>
    <input type="submit" name="login" value="log in">
    </form>
    <?php endif; ?>

  9. #9
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,748
    Mentioned
    73 Post(s)
    Tagged
    0 Thread(s)
    if(time() - $_SESSION["last_activity"] > LIMIT )

    LIMIT is undefined.

    DISTINCT shouldnt be necessary in your query - make username a Unique field in your database.

    PHP Code:
          header("Location:products.php");
          die();
          
    $islogged TRUE
    the last line is pointless - die(); will stop all processing immediately.

    PHP Code:
    <?php $error?>
    needs to be
    PHP Code:
    <?php echo $error?>
    Query needs sanitizing as well.

  10. #10
    SitePoint Addict
    Join Date
    Jul 2011
    Location
    Hyderabad,India.
    Posts
    327
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    how to define LIMIT then

  11. #11
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,748
    Mentioned
    73 Post(s)
    Tagged
    0 Thread(s)
    put a number there?

  12. #12
    SitePoint Addict
    Join Date
    Jul 2011
    Location
    Hyderabad,India.
    Posts
    327
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    do u mean like this one define("LIMIT", 10);

  13. #13
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,748
    Mentioned
    73 Post(s)
    Tagged
    0 Thread(s)
    you can do it that way, or you could just put a number where the word LIMIT is in your original code.

  14. #14
    SitePoint Addict
    Join Date
    Jul 2011
    Location
    Hyderabad,India.
    Posts
    327
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    when we define limit by some number say 20 then by closing the browser in 10 sec
    the session will ends no.....
    what is the use of defining a limit......

  15. #15
    SitePoint Enthusiast Adam Chrapkowski's Avatar
    Join Date
    Sep 2011
    Location
    Poland
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sessions base on PHPSESSID cookie on browser side and session timeout on server side.

  16. #16
    SitePoint Addict
    Join Date
    Jul 2011
    Location
    Hyderabad,India.
    Posts
    327
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    here is my simple shopping cart example.....
    1)database as "db.php"
    Code:
    <?php
    session_start();
    //connect to database
    mysql_connect("localhost","root","") or die("mysql_error()");
    mysql_select_db("shopping") or die("mysql_error()");
    ?>
    2)functions as "functions.php"
    Code:
    <?php
    function get_product_name($pid)
    {
     $result=mysql_query("select name from products where serial=$pid");
     $row=mysql_fetch_array($result);
     return $row['name'];
    }
    function get_price($pid)
    {
      $result=mysql_query("select price from products where serial=$pid");
      $row=mysql_fetch_array($result);
      return $row['price'];
    }
    function remove_product($pid)
    {
      $pid=intval($pid);
      $max=count($_SESSION['cart']);
      for($i=0;$i<$max;$i++)
    	{
          if($pid==$_SESSION['cart'][$i]['productid'])
    	   {
    		unset($_SESSION['cart'][$i]);
    		break;
    	   }
        }
    	$_SESSION['cart']=array_values($_SESSION['cart']);
    }
    function get_order_total()
     {
    	$max=count($_SESSION['cart']);
    	$sum=0;
    	for($i=0;$i<$max;$i++)
    	{
    	 $pid=$_SESSION['cart'][$i]['productid'];
    	 $q=$_SESSION['cart'][$i]['qty'];
    	 $price=get_price($pid);
    	 $sum+=$price*$q;
    	}
    	return $sum;
     }
    function addtocart($pid,$q)
    {
    	if($pid<1 or $q<1) return;
    		
    	if(is_array($_SESSION['cart']))
    	{
    		if(product_exists($pid)) return;
    		$max=count($_SESSION['cart']);
    		$_SESSION['cart'][$max]['productid']=$pid;
    		$_SESSION['cart'][$max]['qty']=$q;
    	}
    	else
    	{
    	 $_SESSION['cart']=array();
    	 $_SESSION['cart'][0]['productid']=$pid;
    	 $_SESSION['cart'][0]['qty']=$q;
    	}
    }
    function product_exists($pid)
    {
    	$pid=intval($pid);
    	$max=count($_SESSION['cart']);
    	$flag=0;
    	for($i=0;$i<$max;$i++)
    	{
    	 if($pid==$_SESSION['cart'][$i]['productid'])
    	  {
    		$flag=1;
    		break;
    	  }
    	}
    	return $flag;
    }
    ?>
    3)products as "products.php"
    Code:
    <?php
    include("db.php");
    include("functions.php");
    if($_REQUEST['command']=='add' && $_REQUEST['productid']>0)
    {
     $pid=$_REQUEST['productid'];
     addtocart($pid,1);
     header("location:shoppingcart.php");
     exit();
    }	
    ?>
    <!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">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Products</title>
    <script language="javascript">
    	function addtocart(pid)
    	{
    		document.form1.productid.value=pid;
    		document.form1.command.value='add';
    		document.form1.submit();
    	}
    </script>
    </head>
    <body>
    <form name="form1">
    	<input type="hidden" name="productid" />
        <input type="hidden" name="command" />
    </form>
    <div align="center">
    <h1>Products</h1>
    <table border="0" cellpadding="2px" width="500px">
    	<?php
    	$result=mysql_query("select * from products");
    	while($row=mysql_fetch_array($result))
    	{
    	 ?>
        <tr>
           <td><img src="<?php echo $row['picture']?>" /></td>
              <td> <b> <?php echo $row['name']?></b><br />
                	   <?php echo $row['description']?><br />
                       Price:<big style="color:red">
                       $<?php echo $row['price']?></big><br /><br />
                 <input type="button" value="Add to Cart" onclick="addtocart(<?php echo $row['serial']?>)" />
    		  </td>
    	</tr>
            <tr><td colspan="2"><hr size="4" /></td></tr>
            <?php } ?>
        </table>
    </div>
    </body>
    </html>
    4)shopping cart as "shopingcart.php"
    Code:
    <?php
    include("db.php");
    include("functions.php");
    	
    if($_REQUEST['command']=='delete' && $_REQUEST['pid']>0)
    {
     remove_product($_REQUEST['pid']);
    }
    else if($_REQUEST['command']=='clear')
    {
     unset($_SESSION['cart']);
    }
    else if($_REQUEST['command']=='update')
    {
    $max=count($_SESSION['cart']);
    for($i=0;$i<$max;$i++)
    {
     $pid=$_SESSION['cart'][$i]['productid'];
     $q=intval($_REQUEST['product'.$pid]);
     if($q>0 && $q<=999)
      {
    	$_SESSION['cart'][$i]['qty']=$q;
      }
      else
      {
    	$msg='Some products not updated!, quantity must be a number between 1 and 999';
      }
    }
    }
    ?>
    <!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">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Shopping Cart</title>
    <script language="javascript">
    function del(pid)
    {
    if(confirm('Do you really mean to delete this item'))
    {
    document.form1.pid.value=pid;
    document.form1.command.value='delete';
    document.form1.submit();
    }
    }
    function clear_cart()
    {
    if(confirm('This will empty your shopping cart, continue?'))
    {
    document.form1.command.value='clear';
    document.form1.submit();
    }
    }
    function update_cart()
    {
    document.form1.command.value='update';
    document.form1.submit();
    }
    </script>
    </head>
    <body>
    <form name="form1" method="post">
    <input type="hidden" name="pid" />
    <input type="hidden" name="command" />
    <div style="margin:1px auto; width:600px;" >
     <div style="padding-bottom:10px">
      <h1 align="center">Your Shopping Cart</h1>
       <input type="button" value="Continue Shopping" onclick="window.location='products.php'" />
      </div>
        <div style="color:#F00"><?php echo$msg?></div>
        <table border="0" cellpadding="5px" cellspacing="1px" style="font-family:Verdana, Geneva, sans-serif; font-size:11px; background-color:#E1E1E1" width="100%">
        <?php
    	if(is_array($_SESSION['cart']))
    	{
        echo '<tr bgcolor="white" style="font-weight:bold"><td>Serial</td><td>Name</td><td>Price</td><td>Qty</td><td>Amount</td><td>Options</td></tr>';
    	$max=count($_SESSION['cart']);
    	for($i=0;$i<$max;$i++)
    	{
    	$pid=$_SESSION['cart'][$i]['productid'];
    	$q=$_SESSION['cart'][$i]['qty'];
    	$pname=get_product_name($pid);
    	if($q==0) continue;
    	?>
        <tr  bgcolor="white"><td><?php echo $i+1?></td><td><?php echo $pname?></td>
         <td>$ <?php echo get_price($pid)?></td>
         <td><input type="text" name="product<?php echo $pid?>" value="<?php echo $q?>" maxlength="3" size="1" /></td>                    
         <td>$ <?php echo get_price($pid)*$q?></td>
         <td><a href="javascript:del(<?php echo $pid?>)">Remove</a></td>
    	</tr>
        <?php					
    	}
    	?>
    	<tr>
    	 <td><b>Order Total: $<?php echo get_order_total()?></b></td><td colspan="5" align="right">
    	 <input type="button" value="Clear Cart" onclick="clear_cart()">
    	 <input type="button" value="Update Cart" onclick="update_cart()">
    	 <input type="button" value="Place Order" onclick="window.location='billing.php'">
    	 </td>
    	</tr>
      <?php
        }
    	else
    	{
    	 echo "<tr bgColor='white'><td>There are no items in your shopping cart!</td>";
    	}
     ?>
       </table>
     </div>
    </form>
    </body>
    </html>
    5)lastli billing as "billing.php"
    Code:
    <?php
    	include("db.php");
    	include("functions.php");
    	if($_REQUEST['command']=='update')
    	{
    	$name=$_REQUEST['name'];
    	$email=$_REQUEST['email'];
    	$address=$_REQUEST['address'];
    	$phone=$_REQUEST['phone'];
    	$result=mysql_query("insert into customers values('','$name','$email','$address','$phone')");
    	$customerid=mysql_insert_id();
    	$date=date('Y-m-d');
    	$result=mysql_query("insert into orders values('','$date','$customerid')");
    	$orderid=mysql_insert_id();
    		
    	$max=count($_SESSION['cart']);
    	for($i=0;$i<$max;$i++)
    	 {
    	  $pid=$_SESSION['cart'][$i]['productid'];
    	  $q=$_SESSION['cart'][$i]['qty'];
    	  $price=get_price($pid);
    	  mysql_query("insert into order_detail values($orderid,$pid,$q,$price)");
    	 }
    	 die('Thank You! your order has been placed!');
    	}
    ?>
    <!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">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Billing Info</title>
    <script language="javascript">
    	function validate()
    	{
    		var f=document.form1;
    		if(f.name.value=='')
    		{
    		 alert('Your name is required');
    		 f.name.focus();
    		 return false;
    		}
    		f.command.value='update';
    		f.submit();
    	}
    </script>
    </head>
    <body>
    <form name="form1" onsubmit="return validate()">
     <input type="hidden" name="command" />
      <div align="center">
         <h1 align="center">Billing Info</h1>
           <table border="0" cellpadding="2px">
             <tr><td>Order Total:</td><td><?php echo get_order_total()?></td></tr>
             <tr><td>Cust Name:</td><td><input type="text" name="name" /></td></tr>
             <tr><td>Address:</td><td><input type="text" name="address" /></td></tr>
             <tr><td>Email:</td><td><input type="text" name="email" /></td></tr>
             <tr><td>Phone:</td><td><input type="text" name="phone" /></td></tr>
             <tr><td></td><td><input type="submit" value="Place Order" /></td></tr>
           </table>
      </div>
    </form>
    </body>
    </html>
    tell me for this simple shopping cart how to check whether the user entered is already registered in database or not
    if he is the new user then using the session that must be stored in the database
    or else if he is old user he must continue......
    below is database
    Code:
    -- Table structure for table `customers`
    
    CREATE TABLE IF NOT EXISTS `customers` (
      `serial` int(11) NOT NULL auto_increment,
      `name` varchar(20) collate latin1_general_ci NOT NULL,
      `email` varchar(80) collate latin1_general_ci NOT NULL,
      `address` varchar(80) collate latin1_general_ci NOT NULL,
      `phone` varchar(20) collate latin1_general_ci NOT NULL,
      PRIMARY KEY  (`serial`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ;
    
    -- Table structure for table `orders`
    
    CREATE TABLE IF NOT EXISTS `orders` (
      `serial` int(11) NOT NULL auto_increment,
      `date` date NOT NULL,
      `customerid` int(11) NOT NULL,
      PRIMARY KEY  (`serial`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ;
    
    -- Table structure for table `order_detail`
    
    CREATE TABLE IF NOT EXISTS `order_detail` (
      `orderid` int(11) NOT NULL,
      `productid` int(11) NOT NULL,
      `quantity` int(11) NOT NULL,
      `price` float NOT NULL
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
    
    -- Table structure for table `products`
    
    CREATE TABLE IF NOT EXISTS `products` (
      `serial` int(11) NOT NULL auto_increment,
      `name` varchar(20) collate latin1_general_ci NOT NULL,
      `description` varchar(255) collate latin1_general_ci NOT NULL,
      `price` float NOT NULL,
      `picture` varchar(80) collate latin1_general_ci NOT NULL,
      PRIMARY KEY  (`serial`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=7 ;
    
    
    INSERT INTO `products` (`serial`, `name`, `description`, `price`, `picture`) VALUES
    (1, 'View Sonic LCD', '19" View Sonic Black LCD, with 10 months warranty', 250, 'images/lcd.jpg'),
    (2, 'IBM CDROM Drive', 'IBM CDROM Drive', 80, 'images/cdrom-drive.jpg'),
    (3, 'Laptop Charger', 'Dell Laptop Charger with 6 months warranty', 50, 'images/charger.jpg'),
    (4, 'Seagate Hard Drive', '80 GB Seagate Hard Drive in 10 months warranty', 40, 'images/hard-drive.jpg'),
    (5, 'Atech Mouse', 'Black colored laser mouse. No warranty', 5, 'images/mouse.jpg'),
    (6, 'Nokia 5800', 'Nokia 5800 XpressMusic is a mobile device with 3.2" widescreen display brings photos, video clips and web content to life', 299, 'images/mobile.jpg');


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •