Showing posts with label PHP session_start. Show all posts
Showing posts with label PHP session_start. Show all posts

Monday, 20 July 2015

PHP: Store value from Dropdown in SESSION Using Ajax with Lightbox

Storing the value from dropdown box in session using ajax programming with lightbox means user will have only focus to dropdown box. Lightbox will be overlayed on website, so the dropdown box can easily get selected by user. Here is the tutorial, source code and demo link

index.php
<?php
session_start();
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var height=$(window).height();
var width=$(window).width();
$(".black-overlay").css("display","block");
$(".form-area").css("display","block");
$(".black-overlay").css("height",height);
$(".form-area").css("margin-top",height/2);
$(".form-area").css("margin-left",width/2.6);

$('#city').change(function(){
$(".black-overlay").css("display","none");
$(".form-area").css("display","none");
var area=$('#city option:selected').val();
$.ajax({
type: "POST",
url: "ajax.php",
data: "area="+area ,
success: function(html){
$('#area').val(html);
}
});
});
});
</script>
<style type="text/css">
.black-overlay
{
background:#000;
opacity: 0.6;
position:fixed;
top: 0;
left: 0;
width: 100%;
z-index: 110000;
display:none;
}
.form-area
{
width: 300px;
margin:0 auto;
position: fixed;
z-index: 10000000;
display:none;
}
#city
{
padding: 7px 13px;
width: 226px;
height: 43px;
border: 1px solid #fff;
line-height: 50px;
font-size: 21px;
color: #000;
}
.select-city-text
{
color: #fff;
text-transform: uppercase;
font-family: verdana;
font-size: 20px;
margin: 0 0 8px 0;
letter-spacing: 9px;
}
</style>

</head>

<body>
<div class="black-overlay">
</div>

<form method="post" action="" class="form-area">
<div class="select-city-text">Select City</div>
<select id="city">
<option>Bangalore</option><option>Mysore</option><option>Bagalkot</option><option>Bangalore</option><option>Basavakalyan</option><option>Belgaum</option><option>Bellary</option><option>Bhadravati</option><option>Bidar</option><option>Bijapur</option><option>Bommanahalli</option>
</select>
</form>
<input type="text" id="area" />
</body>
</html>
ajax.php
Data passed to ajax.php will be stored in a SESSION
<?php
session_start();
if(!empty($_POST['area']))
{
$_SESSION['area']=$_POST['area'];
echo $_SESSION['area'];
}

?>

PHP: Ajax PHP Login Page with bootstrap design

Database
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(100) NOT NULL,
  `password` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
)

Bootstrap code
Add below code in index file <head></head> tag
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>

Html
Bootstrap form i have take sample bootstrap form in bootstrap website.
<body>
  <div class="modal-dialog">
    <div class="modal-content col-md-8">
      <div class="modal-header">
        <h4 class="modal-title"><i class="icon-paragraph-justify2"></i> User Login</h4>
      </div>
      <form method="post" id="login_form">
        <div class="modal-body with-padding">
          <div class="form-group">
            <div class="row">
              <div class="col-sm-10">
                <label>Username *</label>
                <input type="text" id="username" name="username" class="form-control required">
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="row">
              <div class="col-sm-10">
                <label>Password *</label>
                <input type="password" id="password" name="password" class="form-control required" value="">
              </div>
            </div>
          </div>
        </div>
        <div class="error" id="logerror"></div>
        <!-- end Add popup  --> 
        <div class="modal-footer">
          <input type="hidden" name="id" value="" id="id">
          <button type="submit" id="btn-login" class="btn btn-primary">Submit</button>             
        </div>
      </form>
    </div>
  </div>
</body>

Html & ajax code
Above form we seialize() data to pass ajax.php file. if post data (username,password) available page redirect to profile php. Add below code under the above form.
$('#login_form').validate(); - Validate to login form.
<script> 
$(document).ready(function(){
  $('#login_form').validate();  
  $(document).on('click','#btn-login',function(){
    var url = "login.php";      
    if($('#login_form').valid()){
      $('#logerror').html('<img src="ajax.gif" align="absmiddle"> Please wait...'); 
      $.ajax({
      type: "POST",
      url: url,
      data: $("#login_form").serialize(), // serializes the form's elements.
      success: function(data)
      {
        if(data==1) {              
              window.location.href = "profile.php";
        }
        else {  $('#logerror').html('The email or password you entered is incorrect.');
              $('#logerror').addClass("error"); }
        }
        });
    }
    return false;
  });
});
</script>

login.php
extract($_POST); it will convert serialize data to array data.
mysqli_real_escape() string -  check post data special characters.
$db - Database config
<?php
$db = new mysqli('localhost', 'root', '', 'mostlikers');
session_start();
    if($_POST['username']!="" && $_POST['password']!=""):
        extract($_POST);
        $username=mysqli_real_escape_string($db,$_POST['username']);
        $pass_encrypt=md5(mysqli_real_escape_string($db,$_POST['password']));
        $fetch=$db->query("SELECT * FROM `users` WHERE username='$username' AND `password` = '$pass_encrypt'");
        $count=mysqli_num_rows($fetch);
        if($count=="1") :
           $row=mysqli_fetch_array($fetch);
           $_SESSION['login_username']=$row['username'];   
           echo 1; 
        else :
          echo 0;
        endif;
    else :
        header("Location:index.php");
    endif;
?>


profile.php
If user session value is empty, this will redirect to index page.
<?php
session_start();
$check=$_SESSION['login_username'];
if(!isset($check))
{
    header("Location:index.php");
}
?>
<h3 align="center"> Hellow <?php echo $_SESSION['login_username']; ?></h3>
<h2 align="center" >Welcome to mostlikers</h2>
<h4 align="center">  click here to <a href="logout.php">LogOut</a>
</h4>

logout.php
It clear all session data after data clean redirect to login page.
<?php
session_start();
if(session_destroy())
{
header("Location: index.php");
}
?>

Tuesday, 2 June 2015

Mysql: create a simple input / update query to mysql

<?php 
  session_start
(); 
  if (!
ob_start("ob_gzhandler")) 
      
ob_start(); 
  
header("Expires: Mon, 26 Jul 1997 03:00:00 GMT"); 
  
header("Cache-Control: no-cache"); 
  
header("Pragma: no-cache"); 

  
//  url to host 
  
$url "localhost"; 
  
// database user 
  
$dbuser "Your dbuser name"; 
  
//  database user's password 
  
$pwrd "dbuser password"; 

  
//  Show the information_schema 
  
$show_information_schema 1; 

  
$con mysql_connect($url$dbuser$pwrd) or die(mysql_error()); 
  
mysql_set_charset("utf8"$con); ?> 
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<script type="text/javascript">
function GetXmlHttpObject(handler)
{
var objXMLHttp=null
if (window.XMLHttpRequest)
{
     objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
     objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}

function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
         document.getElementById("txtResult").innerHTML= xmlHttp.responseText;
}
else {
         //alert(xmlHttp.status);
}
}

// Will populate data based on input
function htmlData(url, qStr)
{
if (url.length==0)
{
     document.getElementById("txtResult").innerHTML="";
     return;
}
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
     alert ('Please use a browser that support "HTTP Request"');
     return;
}

url=url+"?"+qStr;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true) ;
xmlHttp.send(null);
}
</script>
</head>
<body>
<?php 
  
//  ##############  # FUNCTION START  #  ############## 

  
function get_db($con) 
    { 
      
$i 0; 
      
$res = array(); 

      
$db_list mysql_list_dbs($con); 

      
$cnt mysql_num_rows($db_list); 
      while (
$i $cnt) 
        { 
          
array_push($resmysql_db_name($db_list$i)); 
          
$i++; 
        } 
      if (
count($res) >= 1) 
        { 
          
array_unshift($res"Select database"); 
          return 
$res; 
        } 
      else 
          return array(
" No tables :-( "); 
    } 
  
//  --------------  - 

  
function desc_table($use_table$con) 
    { 
      
$sql "desc $use_table"; 
      
$result mysql_query($sql$con); 

      if (!
is_object($result) && !$result == false) 
        { 
          
$array = array(); 
          while (
$ar mysql_fetch_assoc($result)) 
            { 
              
$tmp[0] = $ar['Field']; 
              
$tmp[1] = $ar['Type']; 
              
array_push($array$tmp); 
            } 
        } 
      return 
$array; 
    } 

  
//  --------------  - 
  
function sql_insert($array$use_table) 
    { 
      
$sql_value ""; 
      
$sql_str "\$sql_query = \"INSERT INTO " $use_table " ("; 

      foreach (
$array as $key => $value) 
        { 
          
$sql_str .= $value[0] . ", "; 
        } 

      
$sql_str substr_replace($sql_str"", -2) . " )VALUES ("; 

      foreach (
$array as $key => $value) 
        { 
          switch (
substr($value[1], 04)) 
            { 
              case 
"char": 
                  
$sql_value .= ' "$' $value[0] . '" ,'; 
                  break; 
              case 
"date": 
                  
$sql_value .= ' "$' $value[0] . '" ,'; 
                  break; 
              case 
"int(": 
                  
$sql_value .= ' $' $value[0] . ' ,'; 
                  break; 
              case 
"text": 
                  
$sql_value .= ' "$' $value[0] . '" ,'; 
                  break; 
              case 
"date": 
                  
$sql_value .= ' "$' $value[0] . '" ,'; 
                  break; 
              case 
"tiny": 
                  
$sql_value .= ' $' $value[0] . ' ,'; 
                  break; 
              case 
"varc": 
                  
$sql_value .= ' "$' $value[0] . '" ,'; 
                  break; 
            } 
        } 

      
$sql_str .= substr_replace($sql_value"", -2) . " )"; 

      return 
$sql_str '";'; 
    } 

  
//  --------------  - 

  
function sql_update($array$use_table) 
    { 
      
$sql_str "\$sql_query = 'UPDATE " $use_table " SET "; 

      foreach (
$array as $key => $value) 
        { 
          switch (
substr($value[1], 04)) 
            { 
              case 
"char": 
                  
$sql_str .= $value[0] . ' = "\'.$' $value[0] . '.\'" ,'; 
                  break; 
              case 
"date": 
                  
$sql_str .= $value[0] . ' = \'.$' $value[0] . '.\', '; 
                  break; 
              case 
"int(": 
                  
$sql_str .= $value[0] . ' = \'.$' $value[0] . '.\', '; 
                  break; 
              case 
"text": 
                  
$sql_str .= $value[0] . ' = "\'.$' $value[0] . '.\'", '; 
                  break; 
              case 
"time": 
                  
$sql_str .= $value[0] . ' = \'.$' $value[0] . '.\', '; 
                  break; 
              case 
"tiny": 
                  
$sql_str .= $value[0] . ' = \'.$' $value[0] . '.\', '; 
                  break; 
              case 
"varc": 
                  
$sql_str .= $value[0] . ' = "\'.$' $value[0] . '.\'", '; 
                  break; 
            } 
        } 

      return 
substr_replace($sql_str"", -2) . " WHERE "; 
    } 

  
//  --------------  - 

  
function get_tables($con$dbname) 
    { 
      
$sql "SHOW TABLES FROM $dbname"; 
      
$result mysql_query($sql); 
      
$res = array(); 
      if (!
$result) 
        { 
          echo 
"DB Error, could not list tables\n"; 
          echo 
'MySQL Error: ' mysql_error(); 
          die; 
        } 

      while (
$row mysql_fetch_row($result)) 
        { 
          
array_push($res$row[0]); 
        } 
      
array_unshift($res"Select table"); 
      return 
$res; 
    } 

  
//  --------------  - 

  
function create_post_var($ar) 
    { 
      foreach (
$ar as $k => $v) 
        { 
          echo 
'$' $v[0] . ' = mysql_real_escape_string($_POST[' "'$v[0]'" ']);<br>'; 
        } 
    } 

  
//  --------------  - 

  
function create_get_var($ar) 
    { 
      foreach (
$ar as $k => $v) 
        { 
          echo 
'$' $v[0] . ' = mysql_real_escape_string($_GET[' "'$v[0]'" ']);<br>'; 
        } 
    } 

  
//  ##############  # FUNCTION END  #  ############## 

  
if (isset($_GET['db'])) 
    { 
      if (
$_GET['db'] == 'Select database') 
          die; 
      
$_SESSION['database'] = $_GET['db']; 
      
$dbname mysql_real_escape_string($_GET['db']); 
      
$table_list get_tables($con$dbname); ?> 

<p></p>
<select value="lopper" name="table_list"
onchange="htmlData(m_insert.php, table=+this.value)" />
<?php 
      
foreach ($table_list as $k => $v) 
        { 
          echo 
'<option>' $v '</option>'; 
        } 
      echo 
'</select></p>'; 

      die; 
    } 

  if (isset(
$_GET['table'])) 
    { 
      
$db_selected mysql_select_db($_SESSION['database'], $con); 

      
$table mysql_real_escape_string($_GET['table']); 

      
$table_array desc_table($table$con); 

      
$sql_str sql_insert($table_array$table); 

      
$sql_update sql_update($table_array$table); 

      echo 
'<p>Table: ' $table '</p>'; 

      echo 
'<p>' $sql_str '</p>'; 

      echo 
'<p>' $sql_update '</p><br>'; 

      echo 
'<p>$_POST to variable</p>'; 
      
create_post_var($table_array); 

      echo 
'<p>$_GET to variable</p>'; 
      
create_get_var($table_array); 
    } 
  else 
    { 
      
$dbs get_db($con); 

      if (
$show_information_schema) 
        { 
          
//  remove information_schema from database list 
          
$res array_search('information_schema'$dbs); 
          unset(
$dbs[$res]); 
        } 
?> 

<select name="db_list"
onchange="htmlData(m_insert.php, db=+this.value)" />
    
 <?php 
      
foreach ($dbs as $k => $v) 
        { 
          echo 
'<option>' $v '</option>'; 
        } 
      echo 
'</select>'; 

      echo 
'<div id="txtResult"> </div>'; 
      die; 
    } 
?>

Thursday, 4 September 2014

PHP Sessions

An alternative way to make data accessible across the various pages of an entire website is to use a PHP Session.
A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.
The location of the temporary file is determined by a setting in the php.ini file called session.save_path. Bore using any session variable make sure you have setup this path.
When a session is started following things happen:
  • PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
  • A cookie called PHPSESSID is automatically sent to the user's computer to store unique session identification string.
  • A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443.
When a PHP script wants to retrieve the value from a session variable, PHP automatically gets the unique session identifier string from the PHPSESSID cookie and then looks in its temporary directory for the file bearing that name and a validation can be done by comparing both values.
A session ends when the user loses the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration.

Starting a PHP Session:

A PHP session is easily started by making a call to the session_start() function.This function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call to session_start() at the beginning of the page.
Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session.
The following example starts a session then register a variable called counter that is incremented each time the page is visited during the session.
Make use of isset() function to check if session variable is already set or not.
Put this code in a test.php file and load this file many times to see the result:
<?php
   session_start();
   if( isset( $_SESSION['counter'] ) )
   {
      $_SESSION['counter'] += 1;
   }
   else
   {
      $_SESSION['counter'] = 1;
   }
   $msg = "You have visited this page ".  $_SESSION['counter'];
   $msg .= "in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php  echo ( $msg ); ?>
</body>
</html>

Destroying a PHP Session:

A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.
Here is the example to unset a single variable:
<?php
   unset($_SESSION['counter']);
?>
Here is the call which will destroy all the session variables:
<?php
   session_destroy();
?>

Turning on Auto Session:

You don't need to call start_session() function to start a session when a user visits your site if you can set session.auto_start variable to 1 in php.ini file.

Sessions without cookies:

There may be a case when a user does not allow to store cookies on their machine. So there is another method to send session ID to the browser.
Alternatively, you can use the constant SID which is defined if the session started. If the client did not send an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an empty string. Thus, you can embed it unconditionally into URLs.
The following example demonstrates how to register a variable, and how to link correctly to another page using SID.
<?php
   session_start();

   if (isset($_SESSION['counter'])) {
      $_SESSION['counter'] = 1;
   } else {
      $_SESSION['counter']++;
   }
?>
   $msg = "You have visited this page ".  $_SESSION['counter'];
   $msg .= "in this session.";
   echo ( $msg );
<p>
To continue  click following link <br />
<a  href="nextpage.php?<?php echo htmlspecialchars(SID); >">
</p>
The htmlspecialchars() may be used when printing the SID in order to prevent XSS related attacks.