Tuesday, August 27, 2013

How to Logout Via php

<?php
 // If the user is logged in, delete the session vars to log them out
  session_start();
  if (isset($_SESSION['agent_id'])) {
    // Delete the session vars by clearing the $_SESSION array
    $_SESSION = array();

       if (isset($_COOKIE[session_name()])) {
      setcookie(session_name(), '');
    }

    // Destroy the session
    session_destroy();
  }


  setcookie('agent_id', '');
  setcookie('username', '');
   // Redirect to the home page
  $home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/index.php?data=true';
  header('Location: ' . $home_url);
?>

------------

and for login via php

Define Connection Variable in php

<?php
  // Define database connection constants
  define('DB_HOST', 'localhost');
  define('DB_USER', 'hemanjosko');
  define('DB_PASSWORD', 'password');
  define('DB_NAME', 'database-name');
?>

connect.php
-------------------------------------

   $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

you may include this to anywhere, where you want to add the connection of php to mysql

How to Login Via php

<?php  require_once('connect.php'); //add connection variables

  // If the user isn't logged in, try to log them in


      // Connect to the database
    $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

      // Grab the user-entered log-in data
      $user_username = mysqli_real_escape_string($dbc, trim($_POST['username']));
      $user_password = mysqli_real_escape_string($dbc, trim($_POST['password']));

      if(!empty($user_username)) {
 if(!empty($user_password)) {
  // Look up the username and password in the database
        $query = "SELECT agent_id, username FROM hj_buses_agent WHERE username = '$user_username' AND password = '$user_password'";
        $data = mysqli_query($dbc, $query);

        if(mysqli_num_rows($data) == 1) {
          // The log-in is OK so set the user ID and username session vars (and cookies), and redirect to the home page
          $row = mysqli_fetch_array($data);
        $_SESSION['agent_id'] = $row['agent_id'];
          $_SESSION['username'] = $row['username'];
          setcookie('agent_id', $row['agent_id']);
 setcookie('username', $row['username']);  
          $home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/index.php';
          header('Location: ' . $home_url);
          }
        else {
          // The username/password are incorrect so set an error message
        $home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/login.php?data=true';
          header('Location: ' . $home_url);
}
 }else

 {
 echo'<script type="text/javascript">alert("Enter Correct Password");</script>';
 }
 }
      else {
        // The username/password weren't entered so set an error message
     echo'<script type="text/javascript">alert("Enter Username & Password");</script>';
      } ?>