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

Friday, 21 August 2015

How To Generate Password Using PHP

When we are building any application from where authentication required, then we need to generate strong password. This article will explain how we can generate password using PHP. Here we have just created one function “generateStrongPassword” having 2 parameters one is length and second is strength. Using these parameters we can customize the generated password.

<?php
function generateStrongPassword($length=9, $strength=4) {
 $vowels = 'aeuy';
 $string = 'bcdfghjmnpqrstvz';
 if ($strength & 1) {
 $string .= 'BCDFGHJLMNPQRSTVWXZ';
 }
 if ($strength & 2) {
 $vowels .= "AEUY";
 }
 if ($strength & 4) {
 $string .= '23456789';
 }
 if ($strength & 8) {
 $string .= '@#$!';
 }

 $password = '';
 $alt = time() % 2;
 for ($i = 0; $i < $length; $i++) {
 if ($alt == 1) {
 $password .= $string[(rand() % strlen($string))];
 $alt = 0;
 } else {
 $password .= $vowels[(rand() % strlen($vowels))];
 $alt = 1;
 }
 }
 return $password;
}
?>

If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries. 

Autocomplete search using php, mysql and ajax

We know what is autocomplete in input type, that is make some predefined entered texts come under the input type box, while focusing on the input type, similarly we are searching some content from mysql database, this actually see image style search concept to suggest some data for select before we get the exact search, for that we are using this kind of search, and this is very simple to make search in php, mysql with ajax and jquery. let see it in brief.

 

as like you see in the above image, the search will be comes like that by using php, mysql and ajax with jquery.

DATABASE DETAILS

database name-->phpmvcbug

table name --> autocomplete

column names --> id, name, email


DB.PHP
<?php
$connection = mysql_connect('localhost','root','') or die(mysql_error());
$database = mysql_select_db('phpmvcbug') or die(mysql_error());
?>

the above is database file.

INDEX.PHP
<div class="content">
<input type="text" class="search" id="searchid" placeholder="Search for people" /> 
 Ex:arunkumar, shanmu, vicky<br /> 
<div id="result"></div>
</div>

just give this input type only in index page with AJAX. you can see the ajax coding below here that is also comes in index page


AJAX
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function(){
$(".search").keyup(function() 
{ 
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!='')
{
    $.ajax({
    type: "POST",
    url: "search.php",
    data: dataString,
    cache: false,
    success: function(html)
    {
    $("#result").html(html).show();
    }
    });
}return false;    
});

jQuery("#result").live("click",function(e){ 
    var $clicked = $(e.target);
    var $name = $clicked.find('.name').html();
    var decoded = $("<div/>").html($name).text();
    $('#searchid').val(decoded);
});
jQuery(document).live("click", function(e) { 
    var $clicked = $(e.target);
    if (! $clicked.hasClass("search")){
    jQuery("#result").fadeOut(); 
    }
});
$('#searchid').click(function(){
    jQuery("#result").fadeIn();
});
});
</script>

the above all for make action in SEARCH page with out refreshing the page.


SEARCH.PHP
<?php
include('db.php');
if($_POST)
{
$q=$_POST['search'];
$sql_res=mysql_query("select id,name,email from autocomplete where name 
                      like '%$q%' or email like '%$q%' order by id LIMIT 5");
while($row=mysql_fetch_array($sql_res))
{
$username=$row['name'];
$email=$row['email'];
$b_username='<strong>'.$q.'</strong>';
$b_email='<strong>'.$q.'</strong>';
$final_username = str_ireplace($q, $b_username, $username);
$final_email = str_ireplace($q, $b_email, $email);
?>
<div class="show" align="left">
<img src="author.PNG" style="width:50px; height:50px; float:left; margin-right:6px;" />
 <span class="name"><?php echo $final_username; ?></span>&nbsp;<br/> 
<?php echo $final_email; ?><br/>
</div>
<?php
}
}
?>

that's it. as like the usual fetch from database with like and here we are just adding str_ireplace, that's it. and other thinks are as like we know, that is very simple one. let's try this. and each of our entering text that wil comes as in strong letter.

 

If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.

Username live availability Check using php and Ajax

Username live availability is one of the most important thing the database field, why because mostly we have to different kind of username and unique name for all users. then only we can identify the individual user, so for here we are going to check the database field for already existing username availability. so here we are using php fetch coding and AJAX live check without refreshing of the page.

DATABASE

<?php
$conn = mysql_connect("localhost","root","") or die("Database not connected");
$db=mysql_select_db("phpmvcbug", $conn) or die("Database not connected");
?>

database name is --> mvcbugase

table name is --> usernames

Check Database coding

<?php
include('db.php');
if(isset($_POST['username']))
{
$username = $_POST['username'];
$sql = mysql_query("select id from usernames where username='$username'");
if(mysql_num_rows($sql))
{
echo '<STRONG>'.$username.'</STRONG> is already in use.';
}
else
{
echo 'OK';
}
}
?>

AJAX

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#username").change(function() 
{ 
var username = $("#username").val();
var msgbox = $("#status");

if(username.length > 4)
{
$("#status").html('<img src="loader.gif" align="absmiddle">Checking availability...');

$.ajax({  
    type: "POST",  
    url: "ajax.php",  
    data: "username="+ username,  
    success: function(msg){  
   $("#status").ajaxComplete(function(event, request){ 
    if(msg == 'OK')
    { 
    
        $("#username").removeClass("red");
        $("#username").addClass("green");
        msgbox.html('<img src="available.png" align="absmiddle">');
    }  
    else  
    {  
         $("#username").removeClass("green");
         $("#username").addClass("red");
        msgbox.html(msg);
    }  
   
   });
   } 
   
  }); 

}
else
{
$("#username").addClass("red");
$("#status").html('<font color="#cc0000">Please nter atleast 5 letters</font>');
}
return false;
});

});
</script>

index page

<input type="text" name="username" id="username" style="margin-top:35px;" />&nbsp;
<span id="status"></span>

span id="status" is for show the result of the output.

that's it. for live availability check username using php, mysql, and Ajax. 

 

If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.

Thursday, 20 August 2015

Comment System using PHP and MySql

Here we are going to see about comment system suing PHP and MySql, here it is useful to all webpage feedback system like user comments Displays at the end of all WebPages that’s what we are going to see here.

 

The above is Sample output image,  so here we are going to create a database with values, they are like 


DATABASE

database name --> downdropcomment
table name --> commenttable
table values --> name--> varchar(20)
job --> varchar (25)
message --> varchar (250)

the above is database format

  CODE
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Comment system using php and mysql</title>
</head>
<body>
<form name="comment" method="post" action="comment.php" onSubmit="return validation()">
<table width="500" border="0" cellspacing="3" cellpadding="3" style="margin:auto;">
  <tr>
    <td align="right" id="one">Name :<span style="color:#F00;">*</span></td>
    <td><input type="text" name="namename" id="tnameid"></td>
  </tr>
  <tr>
    <td align="right" id="one">Work :<span style="color:#F00;">*</span></td>
    <td><input type="text" name="job" id="tjobid"></td>
  </tr>
  <tr>
    <td align="right" id="one"></td>
    <td><textarea name="message" id="tmessageid"></textarea></td>
  </tr>
  <tr>
  <td align="right" id="one"></td>
  <td><input type="submit" name="submit" id="submit" value="Submit Comment"></td>
  </tr>
</table>
</form>
</body>
</html>


FORM IMAGE



And then have to create a comment insert code. 

<?php
include("db.php");
if(isset($_POST['submit']))
{
 $name=$_POST['namename'];
 $job=$_POST['job'];
 $message=$_POST['message'];
 $insert=mysql_query("insert into commenttable
                (name,job,message)values
                ('$name','$job','$message')")or die(mysql_error());
 header("Location:index.php");
 }
?>


And then display the comment.

<?php
include("db.php");
$select=mysql_query("select * from commenttable");
while($row=mysql_fetch_array($select))
{
 echo "<div id='sty'>";
 echo "<img src='files/fav icon.png'"."' width='50px' 
                                                height='50px' 
                                                align='left' />";
 echo "<div id='nameid'>".$row['name']."</div>";
 echo "<div id='msgid'>".$row['message']."</div>";
 echo "</div><br />";
}
?>

OUTPUT IMAGE

that's it comment system is ready.

If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.

Choose state and city based on country using Jquery

It’s  for choosing state and city based on choosing the country, when we choose a country, in a second select option field will show the states, what are all presents in the country, that is the concept. Let see how it works.

lwhen we choose the country, we can automatically show, what are the state are the in the country, for that we are using this code and script.

Script


<script type="text/javascript">
var country_arr = new Array("Afghanistan", "India", "USA", "Vietnam");

var s_a = new Array();
s_a[0]="";
s_a[1]="Badakhshan|Badghis|Baghlan|Balkh|Bamian|Farah|Faryab|Ghazni|Ghowr|Helmand|
       Herat|Jowzjan|Kabol|Kandahar|Kapisa|Konar|Kondoz|Laghman|Lowgar|Nangarhar|
       Nimruz|Oruzgan|Paktia|Paktika|Parvan|Samangan|Sar-e Pol|Takhar|Vardak|Zabol";
s_a[2]="Andhra Pradesh|Arunachal Pradesh|Assam|Bihar|Chhattisgarh|Goa|Gujarat|Haryana|
       Himachal Pradesh|Jammu and Kashmir|Jharkhand|Karnataka|Kerala|Madhya Pradesh|
       Maharashtra|Manipur|Meghalaya|Mizoram|Nagaland|Odisha(Orissa)|Punjab|Rajasthan|
       Sikkim|Tamil Nadu|Tripura|Uttar Pradesh|Uttarakhand|West Bengal";
s_a[3]="Alabama|Alaska|Arizona|Arkansas|California|Colorado|Connecticut|Delaware|
        Florida|Georgia|Hawaii|Idaho|Illinois|Indiana|Iowa|ansas|Kentucky|Louisiana|
        Maine|Maryland|Massachusetts|Michigan|Minnesota|Mississippi|Missouri|Montana|
        Nebraska|Nevada|New Hampshire|New Jersey|New Mexico|New York|North Carolina|
        North Dakota|Ohio|Oklahoma|Oregon|Pennsylvania|Rhode Island|South Carolina|
        South Dakota|Tennessee|Texas|Utah|Vermont|Virginia|Washington|West Virginia|
        Wisconsin|Wyoming";

s_a[4]="Ba Ria|Bạc Liêu|Bắc Giang|Bắc Ninh|Bảo Lộc|Biên Hòa|Bến Tre|Buôn Ma Thuột|
       Cà Mau|Cam Pha|Cao Lãnh|Đà Lạt|Điện Biên Phủ|Đông Hà|Đồng Hới|Hà Tĩnh|Hạ Long|
       Hải Dương|Hòa Bình|Hội An|Huế|Hưng Yên|Kon Tum|Lạng Sơn|Lào Cai|Long Xuyên|
       Móng Cái|Mỹ Tho|Nam Định|Ninh Bình|Nha Trang|Cam Ranh|Phan Rang-Tháp Chàm|
       Phan Thiết|Phủ Lý|Pleiku|Quảng Ngãi|Quy Nhơn|Rạch Giá|Sóc Trăng|Sơn La|Tam Kỳ|
       Tân An|Thái Bình|Thái Nguyên|Thanh Hóa|Trà Vinh|Tuy Hòa|Tuyen Quang|Uong Bi| 
      Việt Trì|Vinh|Vĩnh Yên|Vĩnh Lon|Vũng Tàu|Yên Bái";

function print_country(country){
    //given the id of the <select> tag as function argument, it inserts <option> tags
    var option_str = document.getElementById(country);
    option_str.length=0;
    option_str.options[0] = new Option('Select Country','');
    option_str.selectedIndex = 0;
    for (var i=0; i<country_arr.length; i++) {
    option_str.options[option_str.length] = new Option(country_arr[i],country_arr[i]);
    }
}

function print_state(state, selectedIndex){
    var option_str = document.getElementById(state);
    option_str.length=0;    // Fixed by Julian Woods
    option_str.options[0] = new Option('Select State','');
    option_str.selectedIndex = 0;
    var state_arr = s_a[selectedIndex].split("|");
    for (var i=0; i<state_arr.length; i++) {
    option_str.options[option_str.length] = new Option(state_arr[i],state_arr[i]);
    }
}

 </script>

  the above script is sample script of select state based on country, when we select the country, that will show the second dropdown select box will show the states, the above is script,

Program

Select the Country :
<select onchange="print_state('state',this.selectedIndex);" id="country" name ="country"> 
</select>
<br />
State in the above country :
<select name ="state" id ="state"></select>
<script language="javascript">print_country("country");</script>

that's it, enjoy with the demo. 

If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.

Simple Pagination with loading effect using Qjuery, PHP and MySql

Simple Pagination is the matter of showing limited data in a particular page, here i'm using Jquery, php, mysql. if we have more number of data in a single page, we just make it to show a particular data in a page. for that we are using this pagination. just know how the pagination works and know some of the details about pagination and how to make it without page refreshing, let see the tutorial.

 

 in this pagination system, we just use three things Jquery,PHP, and mysql database, and here we see what are all needed for this pagination system.

  1. index.php

  2. pagination.php

  3. db.php

  4. indexscript

  5. Jquery.min.js

    the above all files are needed to run this pagination. 
    database name -->phpmvcbug
    table name --> pagination
    column names --> id, name, designation, place

    DB.PHP

    <?php
    $mysql_hostname = "localhost";
    $mysql_user = "root";
    $mysql_password = "";
    $mysql_database = "phpmvcbug";
    $con = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong");
    mysql_select_db($mysql_database, $con) or die("Opps some thing went wrong");
    ?>
    

    PAGINATION.PHP

    include the database file, and assign the number of data have to view in the page. then follow the below code.
    <?php
    include('db.php');
    $per_page = 4; 
    if($_GET)
    {
    $page=$_GET['page'];
    }
    $start = ($page-1)*$per_page;
    $select_table = "select * from pagination order by id limit $start,$per_page";
    $variable = mysql_query($select_table);
    ?>
        <table width="800px">
            <?php
            $i=1;
            while($row = mysql_fetch_array($variable))
            {
                $name=$row['name'];
                $design=$row['designation'];
                $place=$row['place'];
            ?>
            <tr>
            <td style="color:#999;"><?php echo $i++; ?></td>
            <td><?php echo $name; ?></td>
            <td><?php echo $design; ?></td>
            <td><?php echo $place; ?></td></tr>
            <?php
            }
            ?>
    </table>
    

    SCRIPT

    the script is comes under in the page of index or where you need it. just call the script with as what have you assigned in the page, make it for as the coding is given by you.
    <script type="text/javascript" src="jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
        function Display_Load()
        {
            $("#load").fadeIn(1000,0);
            $("#load").html("<img src='load.gif' />");
        }
        function Hide_Load()
        {
            $("#load").fadeOut('slow');
        };
        $("#paginate li:first").css({'color' : '#FF0084'}).css({'border' : 'none'});
        Display_Load();
        $("#content").load("pagination.php?page=1", Hide_Load());
        $("#paginate li").click(function(){
            Display_Load();
            $("#paginate li")
            .css({'border' : 'solid #193d81 1px'})
            .css({'color' : '#0063DC'});
            $(this)
            .css({'color' : '#FF0084'})
            .css({'border' : 'none'});
            var pageNum = this.id;
            $("#content").load("pagination.php?page=" + pageNum, Hide_Load());
        });
    });
    </script>

    INDEX.PHP

    first add the database file, and assign the number, how many data have to view in page. then select the table to fetch the data.
    <?php
    include('db.php');
    $per_page = 4; 
    $select_table = "select * from pagination";
    $variable = mysql_query($select_table);
    $count = mysql_num_rows($variable);
    $pages = ceil($count/$per_page)
    ?>
    
    
    <body>
    
    <div id="content" ></div>
    <div class="link" align="center">
                <ul id="paginate">
                    <?php
                      for($i=1; $i<=$pages; $i++)
                    {
                        echo '<li id="'.$i.'">'.$i.'</li>';
                    }
                    ?>
                </ul>   
    </div>
    <div style="clear:both"></div>
    <div id="load" align="center" ></div>
    
    </body>

    CSS

    make as you need for you design with the CSS.
    <style type="text/css">
    body { 
    margin: 0; 
    padding: 0; 
    font-family:Tahoma, Geneva, sans-serif; 
    font-size:18px;
    }
    
    #content{ 
    margin:0 auto; 
    border:0px green dashed; 
    width:800px; 
    min-height:150px; 
    margin-top:100px;
    }
    #load { 
    width:30px;
    padding-top:50px;
    border:0px green dashed;
    margin:0 auto;
    }
    #paginate
    {
    text-align:center;
    border:0px green solid;
    width:500px;
    margin:0 auto;
    }
    .link{
    width:800px; 
    margin:0 auto; 
    border:0px green solid;
    }
    
    li{ 
    list-style: none; 
    float: left;
    margin-right: 16px; 
    padding:5px; 
    border:solid 1px #193d81;
    color:#0063DC; 
    }
    li:hover
    { 
    color:#FF0084; 
    cursor: pointer; 
    }
    </style>
    

    try this code.
  6. If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.

     

Create Database with MySql and INSERT coding in php

It is basics of PHP, here we are going to see about How to create database and how insert the field values in the database table. for that just follow the below instruction what i given below. as per this just follow to create database and insert in it,

Database Creation:

 Here I’m using WAMP sever, so just go to the localhost as url, and choose phpmyadmin and click on the Database, and fill the name of your database, and click Create.

And the database will be created as the name what we given, 


After the database created, we have to create a table. Name of the table and number of columns we want, and click Go.



The above field will be comes like, how many columns we want. fill all the fields without fail.

 

We have to fill the fields, and click save to finish the table creation

 

And the database and table creation work is over.

Sample form image

 Here we are going to insert values so here we need db.php file mainly,

refer all the above for the database name, database table name, and column name and types. now just follow the coding.

DB.PHP

<?php
$conn=mysql_connect("localhost","root","")or die('Database not connected');
$db=mysql_select_db("downdrop")or die('Database not connected');
?>


And the insert coding comes on the main page

INSERT.PHP

<?php
if(isset($_POST['submit']))
{
 $name=$_POST['namename'];
 $number=$_POST['numbername'];
 $address=$_POST['addname'];
 $insert=mysql_query("insert into ddtable(name,number,address)
values
('$name','$number','$address')");
}
?>


All finished, click on the submit button the result will be comes like,
And finish of Creating Database and Insert coding here.

If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.

db.sql

Database file run in your MySQL to create database and add data in table.


 CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(240) NOT NULL,
  `email` varchar(240) NOT NULL,
  `password` varchar(240) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

  db.php

Edit this file as per your database credentials.


<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$connection = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>

 index.php

Contains PHP code, check user, validate email, create encrypted string to reset password with userid and add some numbers to make it unidentified.

<?php
if($_POST['action']=="password")
{
    $email      = mysqli_real_escape_string($connection,$_POST['email']);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) // Validate email address
    {
        $message =  "Invalid email address please type a valid email!!";
    }
    else
    {
        $query = "SELECT id FROM users where email='".$email."'";
        $result = mysqli_query($connection,$query);
        $Results = mysqli_fetch_array($result);
 
        if(count($Results)>=1)
        {
            $encrypt = md5(1290*3+$Results['id']);
            $message = "Your password reset link send to your e-mail address.";
            $to=$email;
            $subject="Forget Password";
            $from = 'info@phpgang.com';
            $body='Hi, <br/> <br/>Your Membership ID is '.$Results['id'].' <br><br>Click here to reset your password http://demo.phpgang.com/login-signup-in-php/reset.php?encrypt='.$encrypt.'&action=reset   <br/> <br/>--<br>PHPGang.com<br>Solve your problems.';
            $headers = "From: " . strip_tags($from) . "\r\n";
            $headers .= "Reply-To: ". strip_tags($from) . "\r\n";
            $headers .= "MIME-Version: 1.0\r\n";
            $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
 
            mail($to,$subject,$body,$headers);
        }
        else
        {
            $message = "Account not found please signup now!!";
        }
    }
}
?>

Execution if this code send an email (used simple mail() function you can also use SMTP) with a confirmation link which redirect you to reset.php.

 reset.php

Contains PHP code, get encrypted string validate it and show you 2 input password boxes and to enter your new password.

<?php
include('db.php');
if(isset($_GET['action']))
{        
    if($_GET['action']=="reset")
    {
        $encrypt = mysqli_real_escape_string($connection,$_GET['encrypt']);
        $query = "SELECT id FROM users where md5(90*13+id)='".$encrypt."'";
        $result = mysqli_query($connection,$query);
        $Results = mysqli_fetch_array($result);
        if(count($Results)>=1)
        {

        }
        else
        {
            $message = 'Invalid key please try again. <a href="http://demo.phpgang.com/login-signup-in-php/#forget">Forget Password?</a>';
        }
    }
}
elseif(isset($_POST['action']))
{

    $encrypt      = mysqli_real_escape_string($connection,$_POST['action']);
    $password     = mysqli_real_escape_string($connection,$_POST['password']);
    $query = "SELECT id FROM users where md5(90*13+id)='".$encrypt."'";

    $result = mysqli_query($connection,$query);
    $Results = mysqli_fetch_array($result);
    if(count($Results)>=1)
    {
        $query = "update users set password='".md5($password)."' where id='".$Results['id']."'";
        mysqli_query($connection,$query);

        $message = "Your password changed sucessfully <a href=\"http://demo.phpgang.com/login-signup-in-php/\">click here to login</a>.";
    }
    else
    {
        $message = 'Invalid key please try again. <a href="http://demo.phpgang.com/login-signup-in-php/#forget">Forget Password?</a>';
    }
}
else
{
    header("location: /login-signup-in-php");
}
?>

 Used jQuery to match re-entered password

<script>
function mypasswordmatch()
{
    var pass1 = $("#password").val();
    var pass2 = $("#password2").val();
    if (pass1 != pass2)
    {
        alert("Passwords do not match");
        return false;
    }
    else
    {
        $( "#reset" ).submit();
    }
}
</script>

  

If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.