Monday, 25 July 2016

Cookies-Session Concept in php

A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the users computer.

Setting Cookies with  PHP :

PHP provided setcookie() function to set a cookie. This function requires   upto  six arguments and should be called before <html> tag. For each cookie this function has to be called separately.

setcookie(name, value, expire, path, domain, security);


Here is the detail of all the arguments:

Name - This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.

Value -This sets the value of the named variable and is the content that you actually want to store.

Expiry - This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.

Path -This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.

Domain - This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them.

Security - This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.


(1) To set save file name as  : "cookies.php".....

<?php

   setcookie("name", "John Watkin", time()+60, "/","", 0);

   
   setcookie("age", "36", time()+60, "/", "",  0);

   
?>

<html>
<head>
<title>Setting Cookies with PHP</title>
</head>
<body>

</body>
</html>

(2) To display  cookies:

<?php

echo $_COOKIE["name"];


?>


What is a PHP Session?:
When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.
So; Session variables hold information about one single user, and are available to all pages in one application.

Start A PHP Session:

A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP session and set some session variables:

Example

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>

Get PHP Session Variable Values:

Next, we create another page called "demo_session2.php". From this page, we will access the session information we set on the first page ("demo_session1.php").
Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page (session_start()).
Also notice that all session variable values are stored in the global $_SESSION variable:

Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

</body>
</html>

Destroy A PHP Session

To remove all global session variables and destroy the session, use session_unset() and session_destroy():

Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset(); 

// destroy the session 
session_destroy(); 
?>

</body>
</html>
================================================================================================================================================

Write code for  session  hit counter:

<?php
session_start();

if(!isset($_SESSION['count']))
{
$_SESSION['count']=0;
}
else
{
$_SESSION['count']++;
}
echo $_SESSION['count'];
?>
==============================================================================================================================================
Simple   use   of   cookies   :
(1)write   Code to check cookies if not set then prevent  to access content. & redirect to you  “form.php” page:
<html>

<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE[“name”]))
{
echo “Welcome ” . $_COOKIE[“name”] . “<br />”;
}

else
{
header(‘Location:form.php’);

}


?>
</body>
</html>
(2)WRITE  CODE FOR    form.php  where we set cookies..after  visiting…
<?php
setcookie(“name”, “John Watkin”, time()+3600, “/”,””, 0);
?>
<form action=send.php method=post>
Name <input type=text name=name>
email<input type=text name=email>
contact<input type=text name=contact>
<input type=submit name=submit >

</form>

From Validation to Prevent SQL Injection Attack

From   Validation   to   Prevent   SQL   Injection   Attack  :
<html>
  <head>
      <style>
         .error {color: #FF0000;}
      </style>
   </head>
  
   <body>
      <?php
         // define variables and set to empty values
         $nameErr = $emailErr = $genderErr = $websiteErr = "";
         $name = $email = $gender = $class = $course = $subject = "";
        
         if ($_SERVER["REQUEST_METHOD"] == "POST") {
            if (empty($_POST["name"])) {
               $nameErr = "Name is required";
            }
            else
            {
               $name = test_input($_POST["name"]);
            }
           
            if (empty($_POST["email"])) {
               $emailErr = "Email is required";
            }
            else
            {
               $email = test_input($_POST["email"]);
              
               // check if e-mail address is well-formed
               if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                  $emailErr = "Invalid email format";
               }
            }
           
            if (empty($_POST["course"])) {
               $course = "";
            }
            else
            {
               $course = test_input($_POST["course"]);
            }
           
            if (empty($_POST["class"])) {
               $class = "";
            }
            else
            {
               $class = test_input($_POST["class"]);
            }
           
            if (empty($_POST["gender"])) {
               $genderErr = "Gender is required";
            }
            else
            {
               $gender = test_input($_POST["gender"]);
            }
           
            if (empty($_POST["subject"])) {
               $subjectErr = "You must select 1 or more";
            }
            else
            {
               $subject = $_POST["subject"];   
            }
         }
        
         function test_input($data) {
            $data = trim($data);
            $data = stripslashes($data);
            $data = htmlspecialchars($data);
            return $data;
         }
      ?>
                               
      <h2>Absolute classes registration</h2>
     
      <p><span class="error">* required field.</span></p>
     
      <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
         <table>
            <tr>
               <td>Name:</td>
               <td><input type="text" name="name">
                  <span class="error">* <?php echo $nameErr;?></span>
               </td>
            </tr>
           
            <tr>
               <td>E-mail: </td>
               <td><input type="text" name="email">
                  <span class="error">* <?php echo $emailErr;?></span>
               </td>
            </tr>
           
            <tr>
               <td>Time:</td>
               <td> <input type="text" name="course">
                  <span class="error"><?php echo $websiteErr;?></span>
               </td>
            </tr>
           
            <tr>
               <td>Classes:</td>
               <td> <textarea name="class" rows="5" cols="40"></textarea></td>
            </tr>
           
            <tr>
               <td>Gender:</td>
               <td>
                  <input type="radio" name="gender" value="female">Female
                  <input type="radio" name="gender" value="male">Male
                  <span class="error">* <?php echo $genderErr;?></span>
               </td>
            </tr>
           
            <tr>
               <td>Select:</td>
               <td>
                  <select name="subject[]" size="4" multiple>
                     <option value="Android">Android</option>
                     <option value="Java">Java</option>
                     <option value="C#">C#</option>
                     <option value="Data Base">Data Base</option>
                     <option value="Hadoop">Hadoop</option>
                     <option value="VB script">VB script</option>
                  </select>
               </td>
            </tr>
           
            <tr>
               <td>Agree</td>
               <td><input type="checkbox" name="checked" value="1"></td>
               <?php if(!isset($_POST['checked'])){ ?>
               <span class="error">* <?php echo "You must agree to terms";?></span>
               <?php } ?>
            </tr>
           
            <tr>
               <td>
                  <input type="submit" name="submit" value="Submit">
               </td>
            </tr>
           
         </table>
      </form>
     
      <?php
         echo "<h2>Your given values are as :</h2>";
         echo ("<p>Your name is $name</p>");
         echo ("<p> your email address is $email</p>");
         echo ("<p>Your class time at $course</p>");
         echo ("<p>your class info $class </p>");
         echo ("<p>your gender is $gender</p>");
        
         for($i=0; $i < count($subject); $i++)
         {
            echo($subject[$i] . " ");
         }
      ?>
 </body>

</html>

Dynamic Drop down Example with Ajax -PHP

PERFECT   DROPDWON  GUIDANCE STEP BY STEP:

Dynamic Drop Down code   with Ajax  :

Step 1:

(1)create table categories:
Create table   categories
( id  int    primary key   auto_increment,
catname   varchar(200)
);
(2)create table  food:
Create table food
(id  int primary key auto_increment,
food_name varchar(200),
catname  varchar(200)

);


Step 2:

(1)write  code for  Dropdown.php    file:
<html>
<head>
<script>
function ajax_post()
{

    // Create our XMLHttpRequest object

    var hr = new XMLHttpRequest();

    // Create some variables we need to send to our PHP file

    var url = "food.php";

    var fn = document.getElementById("catname").value;

  
 var vars ="catname="+fn;

    hr.open("POST", url, true);

    // Set content type header information for sending url encoded variables in the request

    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");


    // Access the onreadystatechange event for the XMLHttpRequest object

    hr.onreadystatechange = function() {
     if(hr.readyState == 4 && hr.status == 200) {
      var return_data = hr.responseText;
   document.getElementById("status").innerHTML = return_data;
     }
    }

    // Send the data to PHP now... and wait for response to update the status div

    hr.send(vars); // Actually execute the request

    document.getElementById("status").innerHTML = "processing...";
}

function ajax_submit()
{

    // Create our XMLHttpRequest object

    var hr = new XMLHttpRequest();

    // Create some variables we need to send to our PHP file

    var url = "submit.php";

    var fn = document.getElementById("catname").value;
     var fd = document.getElementById("food_name").value;

  
 var vars ="catname="+fn+"&food_name="+fd;

    hr.open("POST", url, true);

    // Set content type header information for sending url encoded variables in the request

    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");


    // Access the onreadystatechange event for the XMLHttpRequest object

    hr.onreadystatechange = function() {
     if(hr.readyState == 4 && hr.status == 200) {
      var return_data = hr.responseText;
   document.getElementById("status1").innerHTML = return_data;
     }
    }

    // Send the data to PHP now... and wait for response to update the status div

    hr.send(vars); // Actually execute the request

    document.getElementById("status1").innerHTML = "processing...";
}
</script>
</head>
<body>
<table width="40%"border=1>
<tr><td width="50%"><center><select id=catname  onchange="ajax_post();">
<option>SELECT</option>
<?php
$con=mysql_connect("Localhost","root","");
mysql_select_db("suchi",$con);
$sql="select * from categories";
$result=mysql_query($sql);

while($row=mysql_fetch_array($result))
{
echo '<option value="'.$row['catname'].'">';
echo $row['catname'];
echo '</option>';
}

?>
</select></center></td>

 <td width="50%"><div id=status>
<select name=foodname    id=food_name>
<option>SELECT</option>
 <?php

 $con=mysql_connect("Localhost","root","");
mysql_select_db("suchi",$con);
$sql="select * from food";
$result=mysql_query($sql);

while($row=mysql_fetch_array($result))
{
echo '<option value="'.$row['food_name'].'">';
echo $row['food_name'];
echo '</option>';
}
?>
 </select></div></td>
 </tr>
 <tr><td height="30px" colspan=2><div id="status1"></div></td></tr>
 <tr><td colspan=2>
<center><input type=submit   name=submit  value=submit   onclick="ajax_submit();"></center></td></tr>

</table>
</body>
</html>

(2)write code for food.php file:
<html>
<head>
</head>
<body>
<select name=foodname    id=food_name>
<?php
 $food=$_POST['catname'];
 $con=mysql_connect("Localhost","root","");
mysql_select_db("suchi",$con);
$sql="select * from food where catname='$food'";
$result=mysql_query($sql);

while($row=mysql_fetch_array($result))
{
echo '<option value="'.$row['food_name'].'">';
echo $row['food_name'];
echo '</option>';
}
?>
</select>
</body>
</html>
(3)write code for   submit.php  file:
<?php
echo "testing for onclick ".'<Br>';
echo $catname=$_POST['catname'];
echo $foodname=$_POST['food_name'];

?>
==================================================================================================================================================================


Another  dynamic dropdown practice on  state wise city selection..

Create    table   city   :
create   table  city
(id     int,
city     varchar(200),
state    varchar(200)
);
Create   table   mystate:
create  table  mystate
(id      int,
state    varchar(200)
);
create  table  cityrecord:
create    table  cityrecord
(id      int,
state     varchar(200),
city       varchar(200),
name varchar(200),
contact varchar(200)
);


just see following output:
and follow step by step  :




(1)First   write code for     “statedropdown.php”     file  :
<html>
<head>
<script>
function ajax_post()
{

    // Create our XMLHttpRequest object

    var hr = new XMLHttpRequest();

    // Create some variables we need to send to our PHP file

    var url = "city.php";

    var fn = document.getElementById("mystate").value;

 
 var vars ="mystate="+fn;

    hr.open("POST", url, true);

    // Set content type header information for sending url encoded variables in the request

    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");


    // Access the onreadystatechange event for the XMLHttpRequest object

    hr.onreadystatechange = function() {
     if(hr.readyState == 4 && hr.status == 200) {
      var return_data = hr.responseText;
   document.getElementById("status").innerHTML = return_data;
     }
    }

    // Send the data to PHP now... and wait for response to update the status div

    hr.send(vars); // Actually execute the request

    document.getElementById("status").innerHTML = "processing...";
}

function ajax_submit()
{

    // Create our XMLHttpRequest object

    var hr = new XMLHttpRequest();

    // Create some variables we need to send to our PHP file

    var url = "cityrecord.php";

    var fn = document.getElementById("mystate").value;
     var fd = document.getElementById("city").value;
 var nm = document.getElementById("name").value;
     var cn= document.getElementById("contact").value;

 
 var vars ="mystate="+fn+"&city="+fd+"&name="+nm+"&contact="+cn;

    hr.open("POST", url, true);

    // Set content type header information for sending url encoded variables in the request

    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");


    // Access the onreadystatechange event for the XMLHttpRequest object

    hr.onreadystatechange = function() {
     if(hr.readyState == 4 && hr.status == 200) {
      var return_data = hr.responseText;
   document.getElementById("status1").innerHTML = return_data;
     }
    }

    // Send the data to PHP now... and wait for response to update the status div

    hr.send(vars); // Actually execute the request

    document.getElementById("status1").innerHTML = "processing...";
}
</script>
</head>
<body>
name <input type=text id=name>
contact<input type=text id=contact>
<table width="40%"border=1>
<tr><td width="50%"><center><select id=mystate  onchange="ajax_post();">
<option>SELECT</option>



<?php
$con=mysql_connect("Localhost","root","");
mysql_select_db("rajiv",$con);
$sql="select * from mystate";
$result=mysql_query($sql);

while($row=mysql_fetch_array($result))
{
echo '<option value="'.$row['state'].'">';
echo $row['state'];
echo '</option>';
}

?>

</select></center></td>

 <td width="50%"><div id=status>
<select    id=city>
<option>SELECT</option>


 <?php

 $con=mysql_connect("Localhost","root","");
mysql_select_db("rajiv",$con);
$sql="select * from city";
$result=mysql_query($sql);

while($row=mysql_fetch_array($result))
{
echo '<option value="'.$row['city'].'">';
echo $row['city'];
echo '</option>';
}
?>
 </select></div></td>
 </tr>
 <tr><td height="30px" colspan=2><div id="status1"></div></td></tr>
 <tr><td colspan=2>



<center><input type=submit   name=submit  value=submit   onclick="ajax_submit();"></center></td></tr>

</table>
</body>
</html>

(2)write code for  city.php file:
<html>
<head>
</head>
<body>
<select name=city   id=city>
<?php
 $state=$_POST['mystate'];
 $con=mysql_connect("Localhost","root","");
mysql_select_db("rajiv",$con);
$sql="select * from city where state='$state'";
$result=mysql_query($sql);

while($row=mysql_fetch_array($result))
{
echo '<option value="'.$row['city'].'">';
echo $row['city'];
echo '</option>';
}
?>
</select>
</body>
</html>

(3)write  code for cityrecord.php file:
<?php

 $city=$_POST['city'];
 $state=$_POST['mystate'];
 $name=$_POST['name'];
 $contact=$_POST['contact'];


$con=mysql_connect("localhost","root","");
mysql_select_db("rajiv",$con);
$sql="insert into cityrecord(state,city,name,contact) values('$state','$city','$name','$contact')";
$result=mysql_query($sql)or die(mysql_error());
if($result)
{
               echo "inserted";
               }
               else
               {
                              echo "not inserted";
                              }
                             

                              ?>