Tuesday, 17 October 2017

How to Send Bulk Email in PHP using PHPMailer with Ajax JQuery



Most of the Website has the sending of email feature like send single email or bulk email. So In this post we have discuss topic like how can we send bulk email by using PHP script with PHPMailer Ajax and Jquery. We have use PHPMailer Library because PHP mail() function will not work on localhost. So we have discuss how can we send single or bulk email from localhost in PHP with PHPMailer by using Ajax Jquery. So we can send single or bulk email without refresh or webpage.

We have use SMTP for send bulk mail because SMTP us the most suggested way to send email from localhost or online server. If we have use SMTP to send mail so PHP has nice library PHPMailer library which allow to send email via SMTP by providing required credential. If you have any web hosting email account then your hosting company will provide SMTP credential like username, password, outgoing and incoming server address and port number. By using this information you can configured this details into PHPMailer class and then after you can send email from your script.

In this post we have make simple application from which we can send bulk email to customer by single click. Here we have use Jquery with Ajax so we can send email without refresh of web page. When we have click on button then it will collect email from checkboxes data attribute by using Jquery and after collecting data it will send this data to Ajax request and via Ajax request it will transfer to PHP script and in this we have use PHPMailer class with required SMTP configuration and it will send bulk email and after sending all email successfully it will send data to Ajax request and it will display on web page. This way we can use Ajax with Jquery for Send bulk email by using PHP with PHPMailer Library.






Source Code


index.php



<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
$query = "SELECT * FROM customer ORDER BY customer_id";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<!DOCTYPE html>
<html>
 <head>
  <title>Send Bulk Email using PHPMailer with PHP Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Send Bulk Email using PHPMailer with PHP Ajax</h3>
   <br />
   <div class="table-responsive">
    <table class="table table-bordered table-striped">
     <tr>
      <th>Customer Name</th>
      <th>Email</th>
      <th>Select</th>
      <th>Action</th>
     </tr>
     <?php
     $count = 0;
     foreach($result as $row)
     {
      $count++;
      echo '
      <tr>
       <td>'.$row["customer_name"].'</td>
       <td>'.$row["customer_email"].'</td>
       <td>
        <input type="checkbox" name="single_select" class="single_select" data-email="'.$row["customer_email"].'" data-name="'.$row["customer_name"].'" />
       </td>
       <td><button type="button" name="email_button" class="btn btn-info btn-xs email_button" id="'.$count.'" data-email="'.$row["customer_email"].'" data-name="'.$row["customer_name"].'" data-action="single">Send Single</button></td>
      </tr>
      ';
     }
     ?>
     <tr>
      <td colspan="3"></td>
      <td><button type="button" name="bulk_email" class="btn btn-info email_button" id="bulk_email" data-action="bulk">Send Bulk</button></td></td>
     </td>
    </table>
   </div>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 $('.email_button').click(function(){
  $(this).attr('disabled', 'disabled');
  var id = $(this).attr("id");
  var action = $(this).data("action");
  var email_data = [];
  if(action == 'single')
  {
   email_data.push({
    email: $(this).data("email"),
    name: $(this).data("name")
   });
  }
  else
  {
   $('.single_select').each(function(){
    if($(this). prop("checked") == true)
    {
     email_data.push({
      email: $(this).data("email"),
      name: $(this).data('name')
     });
    }
   });
  }
  
  $.ajax({
   url:"send_mail.php",
   method:"POST",
   data:{email_data:email_data},
   beforeSend:function(){
    $('#'+id).html('Sending...');
    $('#'+id).addClass('btn-danger');
   },
   success:function(data){
    if(data = 'ok')
    {
     $('#'+id).text('Success');
     $('#'+id).removeClass('btn-danger');
     $('#'+id).removeClass('btn-info');
     $('#'+id).addClass('btn-success');
    }
    else
    {
     $('#'+id).text(data);
    }
    $('#'+id).attr('disabled', false);
   }
   
  });
 });
});
</script>


send_mail.php



<?php
//send_mail.php

if(isset($_POST['email_data']))
{
 require 'class/class.phpmailer.php';
 $output = '';
 foreach($_POST['email_data'] as $row)
 {
  $mail = new PHPMailer;
  $mail->IsSMTP();        //Sets Mailer to send message using SMTP
  $mail->Host = 'smtpout.secureserver.net';  //Sets the SMTP hosts of your Email hosting, this for Godaddy
  $mail->Port = '80';        //Sets the default SMTP server port
  $mail->SMTPAuth = true;       //Sets SMTP authentication. Utilizes the Username and Password variables
  $mail->Username = 'xxxxxxxxxx';     //Sets SMTP username
  $mail->Password = 'xxxxxxxxxx';     //Sets SMTP password
  $mail->SMTPSecure = '';       //Sets connection prefix. Options are "", "ssl" or "tls"
  $mail->From = 'info@webslesson.com';   //Sets the From email address for the message
  $mail->FromName = 'Webslesson';     //Sets the From name of the message
  $mail->AddAddress($row["email"], $row["name"]); //Adds a "To" address
  $mail->WordWrap = 50;       //Sets word wrapping on the body of the message to a given number of characters
  $mail->IsHTML(true);       //Sets message type to HTML
  $mail->Subject = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'; //Sets the Subject of the message
  //An HTML or plain text message body
  $mail->Body = '
  <p>Sed at odio sapien. Vivamus efficitur, nibh sit amet consequat suscipit, ante quam eleifend felis, mattis dignissim lectus ipsum eget lectus. Nullam aliquam tellus vitae nisi lobortis, in hendrerit metus facilisis. Donec iaculis viverra purus a efficitur. Maecenas dignissim finibus ultricies. Curabitur ultricies tempor mi ut malesuada. Morbi placerat neque blandit, volutpat felis et, tincidunt nisl.</p>
  <p>In imperdiet congue sollicitudin. Quisque finibus, ipsum eget sagittis pellentesque, eros leo tempor ante, interdum mollis tortor diam ut nisl. Vivamus odio mi, congue eu ipsum vulputate, consequat hendrerit sapien. Aenean mauris nibh, ultrices accumsan ultricies eget, ultrices ut dui. Donec bibendum lectus a nibh interdum, vel condimentum eros auctor.</p>
  <p>Quisque dignissim pharetra tortor, sit amet auctor enim euismod at. Sed vitae enim at augue convallis pellentesque. Donec rhoncus nisi et posuere fringilla. Phasellus elementum iaculis convallis. Curabitur laoreet, dui eget lacinia suscipit, quam erat vehicula nulla, non ultrices elit massa eu dolor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam vulputate mauris vel ultricies tempor.</p>
  <p>Mauris est leo, tincidunt sit amet lacinia eget, consequat convallis justo. Morbi sollicitudin purus arcu. Suspendisse pellentesque interdum enim non consectetur. Etiam eleifend pharetra ante a feugiat.</p>
  ';

  $mail->AltBody = '';

  $result = $mail->Send();      //Send an Email. Return true on success or false on error

  if($result["code"] == '400')
  {
   $output .= html_entity_decode($result['full_error']);
  }

 }
 if($output == '')
 {
  echo 'ok';
 }
 else
 {
  echo $output;
 }
}

?>

Friday, 13 October 2017

Send an Email on Form Submission using PHP with PHPMailer



Sending of an Email is most required feature of any Website for connect user to system, so in this post we have discuss how can we send email on form submission by using PHP script with PHPMailer Library class. PHPMailer class is an other alternative of PHP mail() function to send an Email by using SMTP settings. If you have an Email hosting account then you can use this PHPMailer class for send an email from your website by provide SMTP credential.

In this post we have learn how can we send email from localhost in PHP script by using PHPMailer. If you have use PHP mail() function for send an email then you have to set Email configuration in your php.ini file but if you have use PHPMailer class then you can use any Email hosting account for send an email on form submission or any event in your website as you set.

Here we will learn how to use PHPMailer in PHP and how can we configure into our PHP script or form submission event. For use this class we have required SMTP username and password and we also know SMTP host server name also. If you do not know, so please collect this information first for use this class, without knowing this information we can not configured PHPMailer class into our web application. If we have successfully configured SMTP settings then we can send Email via SMTP server in PHP using PHPMailer. In this post we have make simple contact form for user to send his or her feedback to owner of website via Email send using PHPMailer.






Source Code


index.php



<?php
//index.php

$error = '';
$name = '';
$email = '';
$subject = '';
$message = '';

function clean_text($string)
{
 $string = trim($string);
 $string = stripslashes($string);
 $string = htmlspecialchars($string);
 return $string;
}

if(isset($_POST["submit"]))
{
 if(empty($_POST["name"]))
 {
  $error .= '<p><label class="text-danger">Please Enter your Name</label></p>';
 }
 else
 {
  $name = clean_text($_POST["name"]);
  if(!preg_match("/^[a-zA-Z ]*$/",$name))
  {
   $error .= '<p><label class="text-danger">Only letters and white space allowed</label></p>';
  }
 }
 if(empty($_POST["email"]))
 {
  $error .= '<p><label class="text-danger">Please Enter your Email</label></p>';
 }
 else
 {
  $email = clean_text($_POST["email"]);
  if(!filter_var($email, FILTER_VALIDATE_EMAIL))
  {
   $error .= '<p><label class="text-danger">Invalid email format</label></p>';
  }
 }
 if(empty($_POST["subject"]))
 {
  $error .= '<p><label class="text-danger">Subject is required</label></p>';
 }
 else
 {
  $subject = clean_text($_POST["subject"]);
 }
 if(empty($_POST["message"]))
 {
  $error .= '<p><label class="text-danger">Message is required</label></p>';
 }
 else
 {
  $message = clean_text($_POST["message"]);
 }
 if($error == '')
 {
  require 'class/class.phpmailer.php';
  $mail = new PHPMailer;
  $mail->IsSMTP();        //Sets Mailer to send message using SMTP
  $mail->Host = 'smtpout.secureserver.net';  //Sets the SMTP hosts
  $mail->Port = '80';        //Sets the default SMTP server port
  $mail->SMTPAuth = true;       //Sets SMTP authentication. Utilizes the Username and Password variables
  $mail->Username = 'xxxxxxxxxx';     //Sets SMTP username
  $mail->Password = 'xxxxxxxxxx';     //Sets SMTP password
  $mail->SMTPSecure = '';       //Sets connection prefix. Options are "", "ssl" or "tls"
  $mail->From = $_POST["email"];     //Sets the From email address for the message
  $mail->FromName = $_POST["name"];    //Sets the From name of the message
  $mail->AddAddress('info@find2rent.com', 'Name');//Adds a "To" address
  $mail->AddCC($_POST["email"], $_POST["name"]); //Adds a "Cc" address
  $mail->WordWrap = 50;       //Sets word wrapping on the body of the message to a given number of characters
  $mail->IsHTML(true);       //Sets message type to HTML    
  $mail->Subject = $_POST["subject"];    //Sets the Subject of the message
  $mail->Body = $_POST["message"];    //An HTML or plain text message body
  if($mail->Send())        //Send an Email. Return true on success or false on error
  {
   $error = '<label class="text-success">Thank you for contacting us</label>';
  }
  else
  {
   $error = '<label class="text-danger">There is an Error</label>';
  }
  $name = '';
  $email = '';
  $subject = '';
  $message = '';
 }
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>Send an Email on Form Submission using PHP with PHPMailer</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <div class="row">
    <div class="col-md-8" style="margin:0 auto; float:none;">
     <h3 align="center">Send an Email on Form Submission using PHP with PHPMailer</h3>
     <br />
     <?php echo $error; ?>
     <form method="post">
      <div class="form-group">
       <label>Enter Name</label>
       <input type="text" name="name" placeholder="Enter Name" class="form-control" value="<?php echo $name; ?>" />
      </div>
      <div class="form-group">
       <label>Enter Email</label>
       <input type="text" name="email" class="form-control" placeholder="Enter Email" value="<?php echo $email; ?>" />
      </div>
      <div class="form-group">
       <label>Enter Subject</label>
       <input type="text" name="subject" class="form-control" placeholder="Enter Subject" value="<?php echo $subject; ?>" />
      </div>
      <div class="form-group">
       <label>Enter Message</label>
       <textarea name="message" class="form-control" placeholder="Enter Message"><?php echo $message; ?></textarea>
      </div>
      <div class="form-group" align="center">
       <input type="submit" name="submit" value="Submit" class="btn btn-info" />
      </div>
     </form>
    </div>
   </div>
  </div>
 </body>
</html>

Wednesday, 11 October 2017

Create Stylish Toggles Checkboxes & Use in Form with PHP Ajax



This tutorial is on How to Make Stylish toggles button from Check box HTML tag by using Bootstrap Toggle Jquery plugin and after creating checkbox toggle button how can we pass value of that button into Form by using Jquery and Insert into Mysql table by using Ajax with PHP. We all know web application must be with stylish user interface, so if UI of any web application has something different then it will attract more user and user can also easily understand how can we use this application.

Bootstrap Toggle plugin will convert simple check box into highly flexible toggles button. So if user has come on site then he can understand how can use our web application. If you we have use Bootstrap for our web application UI then this plugin can be easily integrate into our application. Because this plugin is compatible with Bootstrap Library.

Suppose you have developed simple form and in this you have used checkbox tag for any purpose, but simple checkbox UI is very common and we can see in any web based application but if you want to make form something different UI for checkbox then we can use this plugin because it will convert simple checkbox into stylish toggle button with two option and user can select option and by using this plugin we can use single checkbox for select one option from two available option. This plugin will easily to user.

So, this post we have discuss how to initialize this plugin and we have also discuss some basic option like how can we define text on toggle button how can we change background color of toggle button. Then after we will seen how can we use value of toggle button as form field and lastly how can insert value of toggle button into Mysql table by using Ajax with PHP.






Source Code



<?php
//index.php
?>
<!DOCTYPE html>
<html>
 <head>
  <title>Make Stylish Toggles Checkboxes  & Use in Form with PHP Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
  <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
 </head>
 <body>
  <br /><br />
  <div class="container" style="width:600px;">
   <h2 align="center">Make Stylish Toggles Checkboxes & Use in Form with PHP Ajax</h2><br /><br />
   <form method="post" id="insert_data">
    <div class="form-group">
     <label>Enter Name</label>
     <input type="text" name="name" id="name" class="form-control" />
    </div>
    <div class="form-group">
     <label>Define Gender</label>
     <div class="checkbox">
      <input type="checkbox" name="gender" id="gender" checked />
     </div>
    </div>
    <input type="hidden" name="hidden_gender" id="hidden_gender" value="Male" />
    <br />
    <input type="submit" name="insert" id="action" class="btn btn-info" value="Insert" />
   </form>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
 $('#gender').bootstrapToggle({
  on: 'Male',
  off: 'Female',
  onstyle: 'success',
  offstyle: 'danger'
 });

 $('#gender').change(function(){
  if($(this).prop('checked'))
  {
   $('#hidden_gender').val('Male');
  }
  else
  {
   $('#hidden_gender').val('Female');
  }
 });

 $('#insert_data').on('submit', function(event){
  event.preventDefault();
  if($('#name').val() == '')
  {
   alert("Please Enter Name");
   return false;
  }
  else
  {
   var form_data = $(this).serialize();
   $.ajax({
    url:"insert.php",
    method:"POST",
    data:form_data,
    success:function(data){
     if(data == 'done')
     {
      $('#insert_data')[0].reset();
      $('#gender').bootstrapToggle('on');
      alert("Data Inserted");
     }
    }
   });
  }
 });

});
</script>


insert.php



<?php
//insert.php

if(isset($_POST["name"]))
{
 $connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
 $query = "
 INSERT INTO tbl_users (name, gender) 
 VALUES(:name, :gender)
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
   ':name'   => $_POST['name'],
   ':gender'  => $_POST['hidden_gender']
  )
 );

 $result = $statement->fetchAll();
 if(isset($result))
 {
  echo 'done';
 }
}

?>

Sunday, 8 October 2017

Insert Dynamic Multi Select Box Data using Jquery Ajax PHP



In this tutorial we are going to learn how to insert multiple select box data into mysql table by using Ajax jquery with php. In this post we will make stylish multi select box with easy to use user interface, so for this we have use Jquery plugin light weight multi select, by using this light weight jquery plugin we can converts multi select box into two different selection box, when we have click on particular option of left select box then that value will be append into right select box and suppose we want to remove value from right select box then we have simply click on particular option that value will be removed from right box to left. This type of user interface we should use if we have multiple option select and from this interface we can easily understand which option we have select and which are left for selecting.

We will make simple dynamic dropdown list box for insert country state and multiple city data into table, from country and state drop down box we can select single data but from city multi select we can select multiple city at the same time. And lastly all select box data has been dependent on it's parent select box. That means city data depend on state selection and state data depend on country selection. In short all dropdown list are dynamic dependent. If we want to select with multiple item from single select box and this plugin is light weight and it is easy to use. If we have go to user interface wise it is easy to understand to user which option he has select from select box, but this plugin has one draw back is that it is not responsive. So here we have discuss how to insert multi select box data by using light weight multi select jquery plugin with Ajax and PHP.




Source Code


database_connection.php



<?php
//database_connection.php
$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
?>


index.php



<?php
//index.php

include('database_connection.php');

$country = '';

$query = "
 SELECT country FROM country_state_city GROUP BY country ORDER BY country ASC
";
$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

foreach($result as $row)
{
 $country .= '<option value="'.$row["country"].'">'.$row["country"].'</option>';
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>Insert Dynamic Multi Select Box Data using Jquery Ajax PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="jquery.lwMultiSelect.js"></script>
  <link rel="stylesheet" href="jquery.lwMultiSelect.css" />
 </head>
 <body>
  <br /><br />
  <div class="container" style="width:600px;">
   <h2 align="center">Insert Dynamic Multi Select Box Data using Jquery Ajax PHP</h2><br /><br />
   <form method="post" id="insert_data">
    <select name="country" id="country" class="form-control action">
     <option value="">Select Country</option>
     <?php echo $country; ?>
    </select>
    <br />
    <select name="state" id="state" class="form-control action">
     <option value="">Select State</option>
    </select>
    <br />
    <select name="city" id="city" multiple class="form-control">
    </select>
    <br />
    <input type="hidden" name="hidden_city" id="hidden_city" />
    <input type="submit" name="insert" id="action" class="btn btn-info" value="Insert" />
   </form>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){

 $('#city').lwMultiSelect();

 $('.action').change(function(){
  if($(this).val() != '')
  {
   var action = $(this).attr("id");
   var query = $(this).val();
   var result = '';
   if(action == 'country')
   {
    result = 'state';
   }
   else
   {
    result = 'city';
   }
   $.ajax({
    url:'fetch.php',
    method:"POST",
    data:{action:action, query:query},
    success:function(data)
    {
     $('#'+result).html(data);
     if(result == 'city')
     {
      $('#city').data('plugin_lwMultiSelect').updateList();
     }
    }
   })
  }
 });

 $('#insert_data').on('submit', function(event){
  event.preventDefault();
  if($('#country').val() == '')
  {
   alert("Please Select Country");
   return false;
  }
  else if($('#state').val() == '')
  {
   alert("Please Select State");
   return false;
  }
  else if($('#city').val() == '')
  {
   alert("Please Select City");
   return false;
  }
  else
  {
   $('#hidden_city').val($('#city').val());
   $('#action').attr('disabled', 'disabled');
   var form_data = $(this).serialize();
   $.ajax({
    url:"insert.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     $('#action').attr("disabled", "disabled");
     if(data == 'done')
     {
      $('#city').html('');
      $('#city').data('plugin_lwMultiSelect').updateList();
      $('#city').data('plugin_lwMultiSelect').removeAll();
      $('#insert_data')[0].reset();
      alert('Data Inserted');
     }
    }
   });
  }
 });

});
</script>


fetch.php



<?php
//fetch.php

if(isset($_POST['action']))
{
 include('database_connection.php');

 $output = '';

 if($_POST["action"] == 'country')
 {
  $query = "
  SELECT state FROM country_state_city 
  WHERE country = :country 
  GROUP BY state
  ";
  $statement = $connect->prepare($query);
  $statement->execute(
   array(
    ':country'  => $_POST["query"]
   )
  );
  $result = $statement->fetchAll();
  $output .= '<option value="">Select State</option>';
  foreach($result as $row)
  {
   $output .= '<option value="'.$row["state"].'">'.$row["state"].'</option>';
  }
 }
 if($_POST["action"] == 'state')
 {
  $query = "
  SELECT city FROM country_state_city 
  WHERE state = :state
  ";
  $statement = $connect->prepare($query);
  $statement->execute(
   array(
    ':state'  => $_POST["query"]
   )
  );
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   $output .= '<option value="'.$row["city"].'">'.$row["city"].'</option>';
  }


 }
 echo $output;
}

?>


insert.php



<?php
//insert.php

if(isset($_POST['country']))
{
 include('database_connection.php');
 $query = "
 INSERT INTO country_state_city_form_data (country, state, city) 
 VALUES(:country, :state, :city)
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
   ':country'  => $_POST['country'],
   ':state'  => $_POST['state'],
   ':city'   => $_POST['hidden_city']
  )
 );
 $result = $statement->fetchAll();

 if(isset($result))
 {
  echo 'done';
 }

}

?>





Wednesday, 4 October 2017

How to create PHP Login Script using Cookies



If you are looking for tutorial on How to create PHP Login Logout page by using Cookies, then you have come to right place, in this post we have describe How to make PHP login script by using Cookies. We have already describe How to Create PHP Login form by using Session with different option like PHP PDO, object Oriented and in Codeigniter also. But in all post we have use Session for make PHP login logout script. But here we have implement Cookies for developed PHP Login Logout script.

We all know Session are more secured than Cookies. Sessions data are store on server while Cookies data are store on user browser. Cookies are lighter than Session and Cookies can be easily hack. These are all drawback of using Cookies for Login system. But here we have only describe we can also use Cookies for developing Login system in PHP. We have make this tutorial only for learning purpose.

So, In this post we will make simple Login form with logout form. For password verification we have use password_verify() hash method for validate encrypted password. If user has enter proper data then after in this script we have create one cookie variable which we can access from whole system by using setcookies function. After creating coookie variable now we want to validate that cookie variable, so we have use isset() function, by using this function we can validate this $_COOKIE variable. After login into system now we want to logout from system, for logout from system also we have setcookie() and by using this function we can also destroy cookie value also. So, this way we can use setcookie() function we can create or destroy value also. After destroying cookie value now we can logout from system. This way we can use COOKIE for developing login form in PHP







Source Code


database_connection.php



<?php
//database_connection.php
$connect = new PDO("mysql:host=localhost;dbname=testing2", "root", "");
?>


login.php



<?php
//login.php

include("database_connection.php");

if(isset($_COOKIE["type"]))
{
 header("location:index.php");
}

$message = '';

if(isset($_POST["login"]))
{
 if(empty($_POST["user_email"]) || empty($_POST["user_password"]))
 {
  $message = "<div class='alert alert-danger'>Both Fields are required</div>";
 }
 else
 {
  $query = "
  SELECT * FROM user_details 
  WHERE user_email = :user_email
  ";
  $statement = $connect->prepare($query);
  $statement->execute(
   array(
    'user_email' => $_POST["user_email"]
   )
  );
  $count = $statement->rowCount();
  if($count > 0)
  {
   $result = $statement->fetchAll();
   foreach($result as $row)
   {
    if(password_verify($_POST["user_password"], $row["user_password"]))
    {
     setcookie("type", $row["user_type"], time()+3600);
     header("location:index.php");
    }
    else
    {
     $message = '<div class="alert alert-danger">Wrong Password</div>';
    }
   }
  }
  else
  {
   $message = "<div class='alert alert-danger'>Wrong Email Address</div>";
  }
 }
}


?>

<!DOCTYPE html>
<html>
 <head>
  <title>How to create PHP Login Script using Cookies</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <h2 align="center">How to create PHP Login Script using Cookies</h2>
   <br />
   <div class="panel panel-default">

    <div class="panel-heading">Login</div>
    <div class="panel-body">
     <span><?php echo $message; ?></span>
     <form method="post">
      <div class="form-group">
       <label>User Email</label>
       <input type="text" name="user_email" id="user_email" class="form-control" />
      </div>
      <div class="form-group">
       <label>Password</label>
       <input type="password" name="user_password" id="user_password" class="form-control" />
      </div>
      <div class="form-group">
       <input type="submit" name="login" id="login" class="btn btn-info" value="Login" />
      </div>
     </form>
    </div>
   </div>
   <br />
   <p>Admin email - john_smith@gmail.com</p>
   <p>Admin Password - password</p>
   <p>All user password is 'password'</p>
  </div>
 </body>
</html>


logout.php



<?php
//logout.php
setcookie("type", "", time()-3600);

header("location:login.php");

?>


index.php



<?php
//index.php

if(!isset($_COOKIE["type"]))
{
 header("location:login.php");
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>How to create PHP Login Script using Cookies</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <h2 align="center">How to create PHP Login Script using Cookies</h2>
   <br />
   <div align="right">
    <a href="logout.php">Logout</a>
   </div>
   <br />
   <?php
   if(isset($_COOKIE["type"]))
   {
    echo '<h2 align="center">Welcome User</h2>';
   }
   ?>
  </div>
 </body>
</html>


Database



--
-- Database: `testing2`
--

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

--
-- Table structure for table `user_details`
--

CREATE TABLE IF NOT EXISTS `user_details` (
  `user_id` int(11) NOT NULL,
  `user_email` varchar(200) NOT NULL,
  `user_password` varchar(200) NOT NULL,
  `user_name` varchar(200) NOT NULL,
  `user_type` enum('master','user') NOT NULL,
  `user_image` varchar(150) NOT NULL,
  `user_status` enum('Active','Inactive') NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `user_details`
--

INSERT INTO `user_details` (`user_id`, `user_email`, `user_password`, `user_name`, `user_type`, `user_image`, `user_status`) VALUES
(1, 'john_smith@gmail.com', '$2y$10$cHpf3TzonURXDENRiRF0de1ycSfnM4NJ27sdwyUCf5L.sewDlkCBe', 'John Smith', 'master', 'john_smith.jpg', 'Active'),
(2, 'dona_huber@gmail.com', '$2y$10$lcLYyNeK1adgzYcBplv45uuXHFuFyWYThnj3nB2SZ/LbQvtWSoGjO', 'Dona Huber', 'user', 'dona_huber.jpg', 'Active'),
(3, 'roy_hise@gmail.com', '$2y$10$XlyVI9an5B6rHW3SS9vQpesJssKJxzMQYPbSaR7dnpWjDI5fpxJSS', 'Roy Hise', 'user', 'roy_hise.jpg', 'Active'),
(4, 'peter_goad@gmail.com', '$2y$10$n1B.FdHNwufTkmzp/pNqc.EiwjB8quQ1tBCEC7nkaldI5pS.et04e', 'Peter Goad', 'user', 'peter_goad.jpg', 'Active'),
(5, 'sarah_thomas@gmail.com', '$2y$10$s57SErOPlgkIZf1lxzlX3.hMt8LSSKaYig5rusxghDm7LW8RtQc/W', 'Sarah Thomas', 'user', 'sarah_thomas.jpg', 'Active'),
(6, 'edna_william@gmail.com', '$2y$10$mfMXnH.TCmg5tlYRhqjxu.ILly8s9.qsLKOpyxgUl6h1fZt6x/B5C', 'Edna William', 'user', 'edna_william.jpg', 'Active');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `user_details`
--
ALTER TABLE `user_details`
  ADD PRIMARY KEY (`user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `user_details`
--
ALTER TABLE `user_details`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=7;

Monday, 2 October 2017

How to Search Table Data by Bootstrap Typeahead with PHP Ajax



Searching of table data is very required feature in any web application, so here we have discuss something like that. In this post we have learn how to search or filter table data by autocomplete textbox using bootstrap typeahead plugin with PHP script with Ajax Jquery. We have already discuss topic on search html data by using Ajax with Jquery and we have also discuss how to use Bootstrap Typeahead plugin for make autocomplete textbox with Ajax PHP. But now here we have seen combination of both that means we have we have learn how to integrate Bootstrap Typeahead plugin for search table data on server side PHP script with Ajax.

Bootstrap Typeahead plugin is used to make Autocomplete that means we have start to type in textbox then it drop down posible data according to what we have type in textbox. In short this plugin add autocomplete feature to any input type textbox to drop down hint to user while he start filling data in textbox. So here we have used this plugin for search table data with autocomplete textbox.

For make autocomplete search box for search HTML data by send Ajax request to PHP script. In this feature user can search any table column data. Here first we want to make autocomplete search textbox so for this we have use Bootstrap Typeahead plugin by using typeahead() method, by using this plugin we can make auto completed textbox like Google or any other social media site. Then after we have want to search table data according to hint given by this plugin, so here we have integrate search query in typeahead() method, so when this plugin return possible data from autocomplete textbox then it also display search or filter data on table also. This way we have use Bootstrap Typeahead plugin for search table data by using autocomplete input text.






Source Code


index.php



<!DOCTYPE html>
<html>
 <head>
  <title>How to Search Table Data by Typehead with PHP Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
 </head>
 <body>
  <br /><br />
  <div class="container">
   <h2 align="center">How to Search Table Data by Typehead with PHP Ajax</h2>
   <br /><br />
   <label>Search Employee Details</label>
   <div id="search_area">
    <input type="text" name="employee_search" id="employee_search" class="form-control input-lg" autocomplete="off" placeholder="Type Employee Name" />
   </div>
   <br />
   <br />
   <div id="employee_data"></div>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
 load_data('');
 
 function load_data(query, typehead_search = 'yes')
 {
  $.ajax({
   url:"fetch.php",
   method:"POST",
   data:{query:query, typehead_search:typehead_search},
   success:function(data)
   {
    $('#employee_data').html(data);
   }
  });
 }
 
 $('#employee_search').typeahead({
  source: function(query, result){
   $.ajax({
    url:"fetch.php",
    method:"POST",
    data:{query:query},
    dataType:"json",
    success:function(data){
     result($.map(data, function(item){
      return item;
     }));
     load_data(query, 'yes');
    }
   });
  }
 });
 
 $(document).on('click', 'li', function(){
  var query = $(this).text();
  load_data(query);
 });
 
});
</script>


fetch.php



<?php
//fetch.php
if(isset($_POST["query"]))
{
 $connect = mysqli_connect("localhost", "root", "", "testing");
 $request = mysqli_real_escape_string($connect, $_POST["query"]);
 $query = "
  SELECT * FROM tbl_employee 
  WHERE name LIKE '%".$request."%' 
  OR gender LIKE '%".$request."%' 
  OR designation LIKE '%".$request."%'
 ";
 $result = mysqli_query($connect, $query);
 $data =array();
 $html = '';
 $html .= '
  <table class="table table-bordered table-striped">
   <tr>
    <th>Name</th>
    <th>Gender</th>
    <th>Designation</th>
   </tr>
  ';
 if(mysqli_num_rows($result) > 0)
 {
  while($row = mysqli_fetch_array($result))
  {
   $data[] = $row["name"];
   $data[] = $row["gender"];
   $data[] = $row["designation"];
   $html .= '
   <tr>
    <td>'.$row["name"].'</td>
    <td>'.$row["gender"].'</td>
    <td>'.$row["designation"].'</td>
   </tr>
   ';
  }
 }
 else
 {
  $data = 'No Data Found';
  $html .= '
   <tr>
    <td colspan="3">No Data Found</td>
   </tr>
   ';
 }
 $html .= '</table>';
 if(isset($_POST['typehead_search']))
 {
  echo $html;
 }
 else
 {
  $data = array_unique($data);
  echo json_encode($data);
 }
}

?>


Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_employee`
--

CREATE TABLE IF NOT EXISTS `tbl_employee` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `gender` varchar(10) NOT NULL,
  `designation` varchar(30) NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=27 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_employee`
--

INSERT INTO `tbl_employee` (`id`, `name`, `gender`, `designation`) VALUES
(1, 'Micheal Bruce', 'Male', 'System Architect'),
(5, 'Clara Gilliam', 'Female', 'Programmer'),
(6, 'Robert L. Hoskins', 'Male', 'Personal secretary'),
(7, 'Walter M. Watkins', 'Male', 'Crane and tower operator'),
(8, 'Stanley L. Gomez', 'Male', 'HVACR technician'),
(9, 'Erik C. Parker', 'Male', 'Graduate teaching assistant'),
(11, 'Stephanie B. Boland', 'Female', 'Adjuster'),
(12, 'Donald P. Fitzgerald', 'Male', 'Pharmacy aide'),
(13, 'Angel Lewis', 'Female', 'Paper goods tender'),
(14, 'Justin Dean', 'Male', 'Magnetic resonance Technolist'),
(15, 'Nora Blake', 'Female', 'Neuroscience nurse'),
(16, 'Russell Fox', 'Male', 'Safe repairer'),
(17, 'Daryl Bradley', 'Female', 'Intructional coordinator'),
(18, 'Benjamin Gonzales', 'Male', 'Musician'),
(19, 'Viola Francis', 'Female', 'Amusement machine servicer'),
(20, 'Reginald Benson', 'Male', 'Management information systems'),
(21, 'Glenda Ray', 'Female', 'Business support assistant'),
(22, 'Paula Vargas', 'Female', 'Electrical engineer'),
(23, 'Mark Armstrong', 'Male', 'Merchandise manager'),
(24, 'Jaime Campbell', 'Female', 'Petroleum pump system operator'),
(25, 'Mike Beck', 'Male', 'Placement officer'),
(26, 'Ann Lowe', 'Female', 'Computer scientist');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_employee`
--
ALTER TABLE `tbl_employee`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_employee`
--
ALTER TABLE `tbl_employee`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=27;

Thursday, 28 September 2017

How to Disable Enable User Login with PHP using Ajax



This is one more web development tutorial by using PHP with Ajax and in this post we are going to learn How admin user can disabled login of any particular user and how he can also enable login of particular user by using PHP script with Ajax Jquery and Mysql. If any sub user login has been disabled by admin then he can not login into system and he has no rights to access system only if admin can again active his login on his end. So this type of topic we have learn in this post. We have already discuss many topic on PHP login system but here we have first time seen how to disable or inactive particular user by admin.

This type of feature is mostly required when we have developed any web application in which there are master user who has all rights to disabled or enable login of any sub user and in that application there are many sub user who can use system. So when admin want to disabled any particular inactive user login then he can easily disabled particular login on single click. In this system master user can view all sub user details and he can also rights to disabled any user login. So after disabled that particular user will not access our system. This things we have made by using PHP with Ajax.

For make this type of system we have use PHP script. For make login script we have use encrypted password, so in this system all password has been stored in encrypted form and this password has been verify by using password_verify() function. Here for login we have use pure PHP server script and then after if suppose master user has login into system then he can view all sub user details with one action button, by clicking that button master user can enabled or disabled particular user login. For load all sub user details we have make jquery function with ajax request and that request has fetch sub user data from user table and display on web page. Then after for disabled and enabled login of sub user while admin click on action button and on that event we have also use Ajax request which send request to server for enable or disabled user login. So for this event we have also use ajax request with PHP script. So this way we have make simple User login enabled and disabled by using PHP script Ajax.





Source Code


database_connection.php



<?php
//database_connection.php
$connect = new PDO('mysql:host=localhost;dbname=testing2', 'root', '');
session_start();
?>


login.php



<?php
include('database_connection.php');
if(isset($_SESSION["type"]))
{
 header("location:index.php");
}
$message = '';
if(isset($_POST["login"]))
{
 if(empty($_POST["user_email"]) || empty($_POST["user_password"]))
 {
  $message = "<div class='alert alert-danger'>Both Fields are required</div>";
 }
 else
 {
  $query = "
  SELECT * FROM user_details 
  WHERE user_email = :user_email
  ";
  $statement = $connect->prepare($query);
  $statement->execute(
   array(
    'user_email' => $_POST["user_email"]
   )
  );
  $count = $statement->rowCount();
  if($count > 0)
  {
   $result = $statement->fetchAll();
   foreach($result as $row)
   {
    if($row["user_status"] == 'Active')
    {
     if(password_verify($_POST["user_password"], $row["user_password"]))
     {
      $_SESSION["type"] = $row["user_type"];
      header("location: index.php");
     }
     else
     {
      $message = '<div class="alert alert-danger">Wrong Password</div>';
     }
    }
    else
    {
     $message = '<div class="alert alert-danger">Your Account has been disabled, please contact admin</div>';
    }
   }
  }
  else
  {
   $message = "<div class='alert alert-danger'>Wrong Email Address</div>";
  }
 }
}
?>

<!DOCTYPE html>
<html>
 <head>
  <title>How to Disable Enable User Login in PHP using Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <h2 align="center">How to Disable Enable User Login in PHP using Ajax</h2>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">Login</div>
    <div class="panel-body">
     <form method="post">
      <span class="text-danger"><?php echo $message; ?></span>
      <div class="form-group">
       <label>User Email</label>
       <input type="text" name="user_email" id="user_email" class="form-control" />
      </div>
      <div class="form-group">
       <label>Password</label>
       <input type="password" name="user_password" id="user_password" class="form-control" />
      </div>
      <div class="form-group">
       <input type="submit" name="login" id="login" class="btn btn-info" value="Login" />
      </div>
     </form>
    </div>
   </div>
   <br />
   <p>Admin email - john_smith@gmail.com</p>
   <p>Admin Password - password</p>
   <p>All user password is 'password'</p>
  </div>
 </body>
</html>


logout.php



<?php
session_start();
session_destroy();
header("location:login.php");
?>


index.php



<?php
//index.php
include("database_connection.php");
if(!isset($_SESSION["type"]))
{
 header("location:login.php");
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>How to Disable Enable User Login in PHP using Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <h2 align="center">How to Disable Enable User Login in PHP using Ajax</h2>
   <br />
   <div align="right">
    <a href="logout.php">Logout</a>
   </div>
   <br />
   <?php
   if($_SESSION["type"] == "user")
   {
    echo '<div align="center"><h2>Hi... Welcome User</h2></div>';
   }
   else
   {
   ?>
   <div class="panel panel-default">
    <div class="panel-heading">User Status Details</div>
    <div class="panel-body">
     <span id="message"></span>
     <div class="table-responsive" id="user_data">
      
     </div>
     <script>
     $(document).ready(function(){
      
      load_user_data();
      
      function load_user_data()
      {
       var action = 'fetch';
       $.ajax({
        url:'action.php',
        method:'POST',
        data:{action:action},
        success:function(data)
        {
         $('#user_data').html(data);
        }
       });
      }
      
      $(document).on('click', '.action', function(){
       var user_id = $(this).data('user_id');
       var user_status = $(this).data('user_status');
       var action = 'change_status';
       $('#message').html('');
       if(confirm("Are you Sure you want to change status of this User?"))
       {
        $.ajax({
         url:'action.php',
         method:'POST',
         data:{user_id:user_id, user_status:user_status, action:action},
         success:function(data)
         {
          if(data != '')
          {
           load_user_data();
           $('#message').html(data);
          }
         }
        });
       }
       else
       {
        return false;
       }
      });
      
     });
     </script>
    </div>
   </div>
   <?php
   }
   ?>
  </div>
 </body>
</html>


Database



--
-- Database: `testing2`
--

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

--
-- Table structure for table `user_details`
--

CREATE TABLE IF NOT EXISTS `user_details` (
  `user_id` int(11) NOT NULL,
  `user_email` varchar(200) NOT NULL,
  `user_password` varchar(200) NOT NULL,
  `user_name` varchar(200) NOT NULL,
  `user_type` enum('master','user') NOT NULL,
  `user_image` varchar(150) NOT NULL,
  `user_status` enum('Active','Inactive') NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `user_details`
--

INSERT INTO `user_details` (`user_id`, `user_email`, `user_password`, `user_name`, `user_type`, `user_image`, `user_status`) VALUES
(1, 'john_smith@gmail.com', '$2y$10$cHpf3TzonURXDENRiRF0de1ycSfnM4NJ27sdwyUCf5L.sewDlkCBe', 'John Smith', 'master', 'john_smith.jpg', 'Active'),
(2, 'dona_huber@gmail.com', '$2y$10$lcLYyNeK1adgzYcBplv45uuXHFuFyWYThnj3nB2SZ/LbQvtWSoGjO', 'Dona Huber', 'user', 'dona_huber.jpg', 'Active'),
(3, 'roy_hise@gmail.com', '$2y$10$XlyVI9an5B6rHW3SS9vQpesJssKJxzMQYPbSaR7dnpWjDI5fpxJSS', 'Roy Hise', 'user', 'roy_hise.jpg', 'Active'),
(4, 'peter_goad@gmail.com', '$2y$10$n1B.FdHNwufTkmzp/pNqc.EiwjB8quQ1tBCEC7nkaldI5pS.et04e', 'Peter Goad', 'user', 'peter_goad.jpg', 'Active'),
(5, 'sarah_thomas@gmail.com', '$2y$10$s57SErOPlgkIZf1lxzlX3.hMt8LSSKaYig5rusxghDm7LW8RtQc/W', 'Sarah Thomas', 'user', 'sarah_thomas.jpg', 'Active'),
(6, 'edna_william@gmail.com', '$2y$10$mfMXnH.TCmg5tlYRhqjxu.ILly8s9.qsLKOpyxgUl6h1fZt6x/B5C', 'Edna William', 'user', 'edna_william.jpg', 'Active');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `user_details`
--
ALTER TABLE `user_details`
  ADD PRIMARY KEY (`user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `user_details`
--
ALTER TABLE `user_details`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=7;