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

Friday, September 26, 2014

Create an XML file using MYSQL and PHP

In this tutorial am going to show how to create xml file using php and mysql.This script is used to create xml file dynamically.this script will help when you need to create xml file in php and mysql.


Download Script

The content type of the response header must be set to "text/xml".

header ("content-type: text/xml");

DB Connection in php

 mysql_connect('localhost','root','') or die(mysql_error());
 mysql_select_db('database') or die(mysql_error());

SimpleXMLElement is represents an element in an XML document.

Create XML

    //Create XML and stored in your project folder  
    $xmlobj=new SimpleXMLElement($xml);
    //Your file name
    $xmlobj->asXML("text.xml");

Full Source

<?php
        //content type for XML
            header ("content-type: text/xml");
        //DB Connection
            mysql_connect('localhost','root','') or die(mysql_error());
            mysql_select_db('yourdatabase') or die(mysql_error());
        //Create XML
            $xml='<?xml version="1.0" encoding="UTF-8"?>';
        //Query
            $qr=mysql_query("SELECT * FROM `customers` order by id desc") or die(mysql_error());
            $xml.='<userlist>';
            while($res=mysql_fetch_array($qr))
            {
        //Change field names as per your requirement
             $xml.='<user><name>'.$res['name'].'</name><city>'.$res['city'].'</city><state>'.$res['state'].'</state></user>';
            }
            $xml.='</userlist>';
        //Display Content
            echo $xml;
        //Create XML and stored in your project folder    
            $xmlobj=new SimpleXMLElement($xml);
        //Your file name
            $xmlobj->asXML("text.xml");
    ?>

Please share your comments and feedback.Thanks.Please subscribe my updates via email.

Monday, July 21, 2014

Display alexa rank in your website using php

This is very simple php scipt,it is used to display your website alexa rank in website.


Live DemoDownload Script


Replace url="your website url".
file_get_contents is used to read a file into a string.

Php alexa rank Code

<?php $url = file_get_contents('http://data.alexa.com/data?cli=10&dat=snbamz&url=http://codeinnovators.blogspot.in/'); ?>

Full Source Code

<?php

        $url = file_get_contents('http://data.alexa.com/data?cli=10&dat=snbamz&url=http://codeinnovators.blogspot.in/');
      
        //Alexa Rank
        preg_match('/\<popularity url\="(.*?)" text\="([0-9]+)" source\="panel"\/\>/si', $url, $matches);
        $globalrank = ($matches[2]) ? $matches[2] : 0;
       
        //Alexa Sites Linking in
        preg_match('/\<linksin num\="([0-9]+)"\/\>/si', $url, $cocok);
        $alexabacklinks = ($cocok[1]) ? $cocok[1] : 0;
       
        echo "Global Rank : ".$globalrank;
        echo "<br>";
        echo "Alexa Backlinks : ".$alexabacklinks;
        ?>
 
Please share your comments and feedback.Thanks.Please subscribe my updates via email.

Thursday, July 17, 2014

Submit a form without refreshing page using ajax and PHP

This is very simple function.Ajax is used to submit a form without refreshing page.




Live DemoDownload Script


Step 1:
    Need library function.Just copy and paste the below library file.
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

jQuery Code

<script type="text/javascript" >
    $(function() {
        $(".submit").click(function() {
        var name = $("#name").val();
        var email = $("#email").val();
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
      
        var dataString = 'name='+ name + '&email=' + email;
       
        if(name=='')
        {
            $('.success').fadeOut(200).hide();
            $('.error').fadeOut(200).show().html('<div class="notice" align="left">Please enter a name</div>');;
            $("#name").focus();
        }
        else if(email=='')
        {
            $('.success').fadeOut(200).hide();
            $('.error').fadeOut(200).show().html('<div class="notice" align="left">Please enter a email address</div>');;
            $("#email").focus();
        }
        else if(reg.test(email) == false)
          {
                $('.success').fadeOut(200).hide();
                $('.error').fadeOut(200).show().html('<div class="notice" align="left">Please enter a valid email address</div>');;
                $("#email").focus();
          }
        else
        {
            $.ajax({
                type: "POST",
                url: "mail.php",
                data: dataString,
                success: function(){
                $('.success').fadeIn(200).show();
                $('.error').fadeOut(200).hide();
            }
            });
        }
        return false;
        });
    });
    </script>

HTML form

<form method="post" name="form">
  <p>Name:
    <input id="name" name="name" type="text" />
  </p>
  <p>Email:
    <input id="email" name="email" type="email" required />
  </p>
  <span class="error" style="display:none; color:#FF0000"> Please enter valid data</span> <span class="success" style="display:none;color:#33CC66"> Thank You.Your mail has been sent successfully.</span>
  <p>
    <input type="submit" name="submit" value="Submit" class="submit"/>
  </p>
</form>

Please share your comments and feedback.Thanks.Please subscribe my updates via email.

Friday, July 11, 2014

Download file after form submit in PHP

In this article i am going to explain how to download after form submitted in PHP.There are two ways available to download file using php.In this example i have used both methods.

1.Using PHP
2.Using Javascript and meta tag.


readfile() is used to Outputs a file.

PHP Function

$file="test.zip";
        header('Content-type:  application/zip');
        header('Content-Length: ' . filesize('test.zip'));
        header("Content-Disposition: attachment; filename='test.zip'");
        readfile($file);

Javascript function

<script>
    $(document).ready(function(){
      window.setTimeout(function(){
        window.location = 'test.zip';
      }, 1500);
    });
    </script>

Please share your comments and feedback.Thanks.Please subscribe my updates via email.

Sunday, June 22, 2014

CSV to Mysql import in PHP

Today i am going to explain how to import values form CSV to Mysql database.It is very useful to import bulk amount data's very easily.

Let's have look.



Step 1: You need a database connection

db.php

     <?php
        define ("DB_HOST", "localhost"); // set database host
        define ("DB_USER", "root"); // set database user
        define ("DB_PASS",""); // set database password
        define ("DB_NAME","db"); // set database name
      
        $link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
        $db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");
    ?>
 
Create a database and import the following sql query.

users.sql

CREATE TABLE IF NOT EXISTS `student` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `name` varchar(200) NOT NULL,
  `email` varchar(200) NOT NULL,
  `city` varchar(200) NOT NULL,
  `image` blob NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Used functions and Definition:

is_file() — Checks wheather the specified file is a regular file.
fopen - Used to open a file or url.
fgetcsv — Gets line from file pointer and parse for CSV fields

csv.php

      <?php
    if (isset($_POST['csvimport']))
{
  $csv_file = $_FILES['csvfile']['tmp_name'];

  if (!is_file($csv_file))
    exit('File not found.');

  $sql = '';

  if (($handle = fopen( $csv_file, "r")) !== FALSE)
  {
      while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
      {
          $sql .= mysql_query("INSERT INTO `users` SET
            `id` = '$data[0]',
            `name` = '$data[1]',
            `email` = '$data[2]',
            `city` = '$data[3]',
            `image` = '$data[4]'") or die("could not insert into DB");
      }
      fclose($handle);
  }

  exit( "Complete!");
}
?>

csv.html

<form enctype="multipart/form-data" method="POST" action="">
      <input name="csvfile" type="file">
      <input type="submit" name="csvimport" value="Upload">
    </form>

Please share your comments and feedback.Thanks.Please subscribe my updates via email.

Friday, June 20, 2014

Get Userlocation using ip address in PHP

Get Userlocation using ip address in PHP

Let's have look.


index.php

    <?php
            /*Get user ip address*/
            $ip_address=$_SERVER['REMOTE_ADDR'];
          
            /*Get user ip address details with geoplugin.net*/
            $geopluginURL='http://www.geoplugin.net/php.gp?ip='.$ip_address;
            $addrDetailsArr = unserialize(file_get_contents($geopluginURL));
           
            /*Get City name by return array*/
            $city = $addrDetailsArr['geoplugin_city'];
           
            /*Get Country name by return array*/
            $country = $addrDetailsArr['geoplugin_countryName'];
           
            if(!$city){
               $city='Not Define';
            }if(!$country){
               $country='Not Define';
            }
            echo '<strong>IP Address</strong>: '.$ip_address.'<br/>';
            echo '<strong>City</strong>: '.$city.'<br/>';
            echo '<strong>Country</strong>: '.$country.'<br/>';
    ?>
 
Please share your comments and feedback.Thanks.Please subscribe my updates via email.

Friday, June 13, 2014

Auto Refresh using PHP & Jquery

In this post i want to explain how to autorefresh data's.We can fetch values without loading whole page using this script.Most popular Social websites are using this script like twitter,facebook etc.

Let's have look.


Live DemoDownload Script

Create table using the following command.

Mysql Table

        CREATE TABLE IF NOT EXISTS `users` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `uname` varchar(225) NOT NULL,
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

conn.php

<?php
        $conn=mysql_connect("localhost","root","");
        $db=mysql_select_db("autorefresh",$conn); //replace with your DB name
    ?>

JQuery Function

<script type="text/javascript">
    var autorefresh = setInterval(
    function (){
        $('#items').load('count.php').fadeIn("slow"); //Include PHp file for dynamic update
    }, 1000); //refresh every 1000 milliseconds
  
    </script>

Display dynamic results using PHP.I have stored values in mysak and retrived from table.

PHP function

<?php
    $res=mysql_query("select * from users order by id ASC"); ?>
<table width="500" border="1" cellspacing="0" cellpadding="0" style="border:1px solid #ccc;">
  <tr style="border-bottom:1px solid #ccc">
    <td width="250" style="padding:5px;">SNo</td>
    <td width="250" style="padding:5px;">Username</td>
  </tr>
  <?php
    while($row=mysql_fetch_array($res)){ ?>
  <tr>
    <td width="250" style="padding:5px;"><?php echo $row['id'];?></td>
    <td width="250" style="padding:5px;"><?php echo $row['uname'];?></td>
  </tr>
  <?php } ?>
</table>


Please share your comments and feedback.Thanks.Please subscribe my updates via email.

Wednesday, May 28, 2014

Directory (or) Folder Creation in PHP

mkdir function is used to create folder or directory in php.

Syntax:
mkdir($str, 0777, true)

PHP Code

<?php
        if(isset($_POST['createdirectory']))
        {
                $folder='D:\phptest\\'; // Desired folder path
                $foldername=$_POST['foldername'];
                $foldercreate=$folder . $foldername;
            if (!mkdir($foldercreate, 0777, true))
                {
                    die('Failed to create folder...');
                }
            else
                {
                    echo "Folder has been created successfully!";
                }
                    $foldercreate="";
                }
        ?>

HTML Form

 <form action="#" method="post">
      Enter Name of the folder:
      <input type="text" name="foldername" size="15" required />
      <input type="submit" name="createdirectory" value="Create" />
  </form>

Complete Code

 <form action="#" method="post">
  <h3>Directory (or) Folder Creation in PHP:</h3>
  Enter Name of the folder:
  <input type="text" name="foldername" size="15" required />
  <input type="submit" name="createdirectory" value="Create" />
  <?php
if(isset($_POST['createdirectory']))
{
        $folder='D:\phptest\\'; // Desired folder path
        $foldername=$_POST['foldername'];
        $foldercreate=$folder . $foldername;
     if (!mkdir($foldercreate, 0777, true))
        {
            die('Failed to create folder...');
        }
    else
        {
            echo "Folder has been created successfully!";
        }
            $foldercreate="";
        }
?>
  </div>
</form>

Please share your comments and feebback.Thanks.Please subscribe my updates via email.

Saturday, May 17, 2014

Check Username availability in PHP using Ajax

In this article i am going to show how to check Check Username availability in PHP using Ajax.

Lets take a look.



PHP Function

    <?php
include("conn.php");

    if(isset($_POST['username'])){
        $user = $_POST['username'];//Get entered username
        $res = mysql_query("SELECT * FROM users WHERE username='$user'");
        $count = mysql_num_rows($res);//Get total num of users list for entered username
        if($count >= 1){
            echo "Not Available";//Show result if not available
        }else{
            echo "Available";//Show result if available
        }
    }
?>

Database Connection

  <?php
$connection=mysql_connect("localhost","root","");
$db=mysql_select_db("database",$connection);

// Check connection
if (!$connection) {
    die('Could not connect: ' . mysql_error());
}
 
?>

HTML Form

<form method="post" action="#">
  <input type="text" id="user" name="username" value="" placeholder="Enter your Username">
  <span id="response"></span>
</form>

JQuery Function

<script type="text/javascript">
$(document).ready(function() {
    $('#user').keyup(function() {
        var user = $(this).val();
        $.ajax({
            url: 'check_user.php',
            type: 'POST',
            data: {username:user},
            beforeSend: function(){
                $('#response').text('Wait.Checking Availablity');
            },
            success: function(response){
                $('#response').html(response);
                //alert(response);
              
    if(response == 'Not Available')
    {
  
        $("#user").removeClass("green");
         $("#user").addClass("red");
        msgbox.html(response);
    }
    else
    {
        $("#user").removeClass("red");
        $("#user").addClass("green");
        msgbox.html('<img src="available.png" align="absmiddle">');
    }
 

            }
        });
    });
});
</script>
Please share your comments and feedback.Thanks.

Friday, May 9, 2014

PHP Search using Jquery

In this artcile am going to shows how to get search results using PHP and Jquery



Table.sql

Create a table using the following sql comments.
    
      --
      -- Table structure for table `users`
      --
    
      CREATE TABLE IF NOT EXISTS `users` (
      `userid` int(11) NOT NULL AUTO_INCREMENT,
      `username` varchar(225) NOT NULL,
      PRIMARY KEY (`userid`)
      ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Conn.php

      <?php

$connection=mysql_connect("localhost","root","");
$db=mysql_select_db("database",$connection);

// Check connection
if (!$connection) {
    die('Could not connect: ' . mysql_error());
}

?>

Search.php

  <?php $data='';

if(isset($_POST['search'])) {
    $uname = $_POST['search'];
    $uname = preg_replace("#[^0-9a-z]#i","",$uname);
    $query = "select username from users where username LIKE '%$uname%'";
    $result = mysql_query($query);
    $count = mysql_num_rows($result);
if($count>0)
{
while($row = mysql_fetch_array($result))
    {
        $data = $data."<div>".$row['username']."</div>";
    }  
        echo "<h1>Search results:</h1><br>";
        echo $data;
    }

}
    else
{
?>
<html>
<head>
<title>PHP search using Ajax</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-git2.min.js" ></script>
<script type="text/javascript">
$(function(){
    $('.search_results').keyup(function(){
        var search = $('.search_results').val();
            $.post("search.php",{"search":search},function(data){
                $('.results').html(data);
        });
    });
});
</script>
</head>
<body>
<form action="search.php" method="post">
  <input type="text" name="search" class="search_results" />
  <input type="submit" value="search"/>
</form>
<div class="results"></div>
</body>
</html>
<?php
}
?>
Please share your comments and feedback.Thanks.

Tuesday, May 6, 2014

Timeago using PHP

Time ago function is very important for social websites.In this post i will shows how to add time ago function in website using php.



I have used time() functions to display time ago.

time()
It is used  to return current time


PHP Code

   <?php
function time_stamp($session_time)
{
$time_diff = time() - $session_time ;
$seconds = $time_diff ;
$minutes = round($time_diff / 60 );
$hours = round($time_diff / 3600 );
$days = round($time_diff / 86400 );
$weeks = round($time_diff / 604800 );
$months = round($time_diff / 2419200 );
$years = round($time_diff / 29030400 );

//For Seconds
if($seconds <= 60)
{
    echo "Updated $seconds seconds ago";
}
//For Minutes
else if($minutes <=60)
{
    if($minutes==1)
    {
        echo "Updated one minute ago";
    }
    else
    {
        echo "Updated $minutes minutes ago";
    }
}
//For Hours
else if($hours <=24)
{
    if($hours==1)
    {
        echo "Updated one hour ago";
    }
    else
    {
        echo "Updated $hours hours ago";
    }
}
//For Days
else if($days <= 7)
{
    if($days==1)
    {
        echo " Updated one day ago";
    }
    else
    {
        echo "Updated $days days ago";
    }
}
//For  Weeks
else if($weeks <= 4)
{
    if($weeks==1)
    {
        echo "Updated one week ago";
    }
    else
    {
        echo "Updated $weeks weeks ago";
    }
}
//For  Months
else if($months <=12)
{
    if($months==1)
    {
        echo "Updated one month ago";
    }
    else
    {
        echo "Updated $months months ago";
    }
}
//For Years
else
{
    if($years==1)
    {
        echo "Updated one year ago";
    }
    else
    {
        echo "Updated $years years ago";
    }
}
}
//Session time
$session_time ="1399358058";
echo time_stamp($session_time);
?>
Please share your comments and feedback.Thanks.

Friday, May 2, 2014

Form validation using PHP

This article going to explain how to validate form elements using PHP.
No need external library files or javascript to validate form.

Let's have a look.



Sample Form

<form method="post" action="#">
      Name:
      <input type="text" name="name"/>
      <span style="color:#FF3300"><?php echo $error;?></span> <br>
      Email:
      <input type="text" name="email"/>
      <span style="color:#FF3300"><?php echo $erro;?></span> <br>
      Contact:
      <input type="text" name="contact"/>
      <span style="color:#FF3300"><?php echo $err;?></span> <br>
      <input type="submit" name="submit" value="Submit"/>
    </form>

PHP Validation

      <?php
     //Declare variables value as empty
$name=$email=$contact="";
$error = $erro = $err = "";
if(isset($_POST['submit']))
{
    if(empty($_POST["name"])) {
    $error= "Enter your name";
    echo "<br>";
    }
    if (empty($_POST["email"])) {
     $erro="Email is required";echo "<br>";
   } else {
     $email = $_POST["email"];
     // check if e-mail is valid
     if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
       $erro="Invalid email format"; echo "<br>";
     }
   }
    if(empty($_POST["contact"])) {
        $err="Enter your contact number";
    }  
}
?>
Please share your comments and feedback.Thanks.

Tuesday, April 29, 2014

Password reset using PHP and Mysql

In this article i am going to explain how to reset password using PHP,Mysql.

There are many methods available for password reset.In this i have used php email function to reset the password.I have used both $_POST and $_GET method for this.

If not registered user entered email address it shows error,if email was exists in database shows success message and sent mail with reset link.

The email contains reset link the user.if you click the link it will go to  password reset page.





Functionality files:

1.forgotpassword.php
2.resetpassword.php

In this you will learn the following things.

1.Send mail using PHP
2.UPDATE Query

Form

 <form name="forgotpwdform" action="#" method="post">
          <h3><a href="#" title="Forgot Password">Forgot Password</a></h3>
          <label>Email</label>
          <input type="email" name="Email" required/>
          <p>
            <input type="submit" name="ForgotPassword" value="Submit" id="submit"/>
          </p>
        </form>

Mail function with reset option

      <?php
if(isset($_POST['ForgotPassword'])){

        $email=$_POST['Email'];
        //Query
        $Password=mysql_query("SELECT Password FROM users WHERE Email='$email'");
      
        $NumRows=mysql_num_rows($Password);
       
                     if($NumRows == '0') { 
                        echo 'Sorry..Your Email not found in our database. Please try again';
                        header('Location:forgotpassword.php');
                        exit();
 } else {
               
                $to=$email; //To Mail
                $subject="Password Assistance"; //Subject
                $headers = "From: yourweb@website.in\r\n";
                $headers .= "MIME-Version: 1.0\r\n";
                $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
                $headers .= "X-Priority: 1\n";
                $headers .= "X-MSmail-Priority: High\n";
                $headers .= "X-Mailer: PHP". phpversion() ."\r\n" ;
           
            //Message
            $message = " Hi ,\r\n";
            $message .= "To initiate the password reset process for your $Email Account, click the link below:\r\n";
            $message .= "http://www.yourwebsite.com/resetpassword.php?Email=$email\r\n";
            $message .= "Cheers,\r\n";
            $message .= " Team\n\n";
         
            //Mail Script
            $sentmail=mail($email, $subject, $message,$headers);
        }
                       
    if($sentmail) {
        echo 'Your Password reset link Has Been Sent To Your Email Address.Please check your Inbox!';
        header('Location:forgotpassword.php');
        exit();
 }  else {

         echo 'Error.Please try again!';
         header('Location:forgotpassword.php');
        exit();
         }
    }
?>

Password Reset Form

<form accept-charset="UTF-8"  name="ProfileUpdate"  method="post" action="#" id="reset-form" style="width:590px">
          <h3>Reset Password</h3>
          <div >
            <div>
              <label>New Password</label>
            </div>
            <div>
              <input type="password" name="Password1"  id="Password1" class="user-text" />
            </div>
          </div>
          <div>
            <div>
              <label>Confirm New Password</label>
            </div>
            <div >
              <input type="password" name="Password2" id="Password2" class="user-text1"/>
            </div>
          </div>
          <div>
            <p>
              <input type="submit" name="ResetPassword" value="Submit"  id="submit" />
            </p>
          </div>
        </form>

Reset function in PHP

 <?php
//Database config
$connection=mysql_connect("localhost","root","");
$db=mysql_select_db("campustiger",$connection);

// Check connection
if (!$connection) {
    die('Could not connect: ' . mysql_error());
}

if(isset($_POST['ResetPassword'])) {

     $currentpassword = $_POST['Password']; // get the current password from                                                                   
     $newpassword = $_POST['Password1']; // get the new password from the                                                                       
     $hash = md5($newpassword); // encrypt the current password supplied by the user
                                                          
     $email = $_GET['Email'];
     $result = mysql_query("SELECT Password from users  where Email='$email'");  // query the database for getting password for a the user.

     while($row = mysql_fetch_array($result)) {
         $p=$row['Password'];
     }
    // get the encrypted password from the database for the user
     ?>
      <?php                                    

           $result = mysql_query("UPDATE users set Password='$hash' where Email='$email' ");
          
           if($result) {
                     header('Location:login.php');
         }
         else {
                    echo 'OOPS!.Please try again';
                    header('Location:resetpassword.php');
                    exit();
 }
    }
?>
Please share your comments and feedback.Thanks.

Monday, April 28, 2014

Facebook style comment Using PHP and Jquery

Hi friends.My friends are asked to me how to create facebook style comment .Thats why i have wrote this article.I have used PHP and Javascript to add comment.Let's have a look.

In this you will learn the following things:

1.SESSION
2.Ajax Method(GET)

Functionality Files:
1. index.php


HTML Code

<div class="container">
  <div class="content">
    <div id="commentscontainer">
      <div class="comments clearfix">
        <div class="pull-left lh-fix"> <img src="img/default.gif"> </div>
        <div class="comment-text pull-left"> <span class="color strong"><a href="#">Vinoth</a></span> &nbsp;Hello Friends <span class="info"><abbr class="time" title="2014-04-024T21:50:03+02:00"></abbr></span> </div>
      </div>
      <div class="comments clearfix">
        <div class="pull-left lh-fix"> <img src="img/default.gif"> </div>
        <div class="comment-text pull-left"> <span class="color strong"><a href="#">Code Innovators</a></span> &nbsp;What's up?? <span class="info"><abbr class="time" title="2014-04-024T21:50:03+02:00"></abbr></span> </div>
      </div>
    </div>
    <div class="comments clearfix">
      <div class="pull-left lh-fix"> <img src="img/default.gif"> </div>
      <div class="comment-text pull-left">
        <textarea class="text-holder" placeholder="Write a comment.." id="message"></textarea>
      </div>
    </div>
  </div>
</div>


jQuery Code

<script type="text/javascript">
    $(document).ready(function() {
var msg = '#message';

$('.time').timeago();
$(msg).autosize();

$('#post_comment').click(function() {
$(msg).focus();
});

$(msg).keypress(function(e) {
if(e.which == 13) {
var val = $(msg).val();

$.ajax({
url: 'php/ajax.php',
type: 'GET',
data: 'token=<?php echo $token; ?>&msg='+escape(val),
success: function(data) {
$(msg).val('');
$(msg).css('height','14px');
$('#commentscontainer').append(data);
$('.time').timeago();
}
});
}
});

$('#like_post').click(function() {
var count = parseFloat($('#count').html()) + 1;
if(count > 1) {
$('#if_like').html('You and');
$('#people').html('others');
} else {
$('#if_like').html('You like this.');
$('#likecontent').hide();
}

$('#like_post').hide();
$('#unlike_post').show();
});

$('#unlike_post').click(function() {
var count = parseFloat($('#count').html()) - 1;
if(count < 1) {
$('#likecontent').show();
}
$('#unlike_post').hide();
$('#like_post').show();
$('#if_like').html('');
$('#people').html('people');
});
});
</script>
Please share your comments and feedback.Thanks

Thursday, April 24, 2014

Simple search using PHP and Mysql

In this article i am going to explain how to search values using PHP,Mysql.

In this you will learn the following things:

1.$_POST Method
2.Databse Connection
3.Communication between Database and PHP
4.Fetch results from datbase and display.



Functionality Files:

1.Search.php
2.conn.php


Database Connection

   <?php
          $conn=mysqli_connect("localhost","root","","search") or die('Error connection');
        /*Hostname = "localhost".Replace with your hostname*/
         /*Databse Username="root".Replace with your Username*/
         /*Databse Password="".Replace with your Password*/
         /*Databse Name="search".Replace with your database name*/

    ?>

Search.php

     <?php
  $conn=mysqli_connect("localhost","root","","search") or die('Error connection');
  $search_results = '';
  if(isset($_POST['search']))
  {
    $str = $_POST['search'];
    $str = preg_replace("#[^0-9a-z]#i","",$str);
    $query = "SELECT UserName FROM users WHERE UserName LIKE '%$str%'";
    $result = mysqli_query($conn,$query);
    $count = mysqli_num_rows($result);
    if($count>0)
    while($row = mysqli_fetch_array($result))
      {
        $search_results = $search_results."<div>".$row['UserName']."</div>";
      }
  }

?>
    <form action="#" method="post">
      <input type="text" name="search" />
      <input type="submit" value="search"/>
    </form>
    <?php if(isset($_POST['search'])) { ?>
    <h2>Search Results:</h2>
    <?php echo $search_results; ?>
    <?php } ?>
Please share your comments and feedback.Thanks.

Tuesday, April 22, 2014

File Upload Progress bar using PHP and Jquery

In this article i am going to shows how to upload file with progress bar.

I have used PHP,Jquery to upload a file.

Functionality Files:

1.Index.php
2.Upload.php




HTML Code

    <div style='width:900px;margin:auto'>
      <h1> File Upload Progress bar using PHP and Jquery </h1>
      <form action="upload.php" method="post" enctype="multipart/form-data">
        <input type="file" name="uploadedfile" required>
        <br>
        <input type="submit" name="Upload" id="upload" value="Upload File">
      </form>
      <div class="progress">
        <div class="bar"></div >
        <div class="percent">0%</div >
      </div>
      <div id="status"></div>
    </div>

Jquery Files

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
      <script src="http://malsup.github.com/jquery.form.js"></script>
      <script>
 (function() {
 var bar = $('.bar');
 var percent = $('.percent');
 var status = $('#status');
 $('form').ajaxForm({
   beforeSend: function() {
     status.empty();
     var percentVal = '0%';
     bar.width(percentVal)
     percent.html(percentVal);
   },
   uploadProgress: function(event, position, total, percentComplete) {
     var percentVal = percentComplete + '%';
     bar.width(percentVal)
     percent.html(percentVal);
   },
   complete: function(xhr) {
     bar.width("100%");
     percent.html("100%");
     status.html(xhr.responseText);
   }
 }); 
 })();    
 </script>

PHP Code

      <?php
 if(isset($_POST['submit']))
 {
 $upload_dir = $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']);
 $upload_url = '/';
      $temp_name = $_FILES['uploadedfile']['tmp_name'];
      $file_name = $_FILES['uploadedfile']['name'];
      $file_path = $upload_dir.$upload_url.$file_name;
      if(move_uploaded_file($temp_name, $file_path))
      {
           echo "File uploaded Success !";
      }
}
?>
Please share your comments and feedback.Thanks.!

Saturday, April 19, 2014

Send attachment in mail using php

Lets take a look about how to send attachment in mail using PHP

It is very important to send attachment in mail.



Functionality file:
1.Index.html
2.mail.php


HTML Code

<table cellspacing="0" cellpadding="0" border="0">
      <tbody>
        <tr>
          <td height="20" class="contacttxttitle" style="color:#990000; width:300px; font-family:Arial, Helvetica, sans-serif; font-size:16px;  padding:5px;"  colspan="2"> Enquiry Form </td>
        </tr>
      <form name="contactusform" action="mail.php" method="post" enctype="multipart/form-data">
        <tr>
          <td width="179" height="30" class="contactspl">Name :</td>
          <td width="271" height="30"><input type="text" size="30" id="uname_1" name="uname" required>
          </td>
        </tr>
        <tr>
          <td height="30" class="contactspl">Contact No :</td>
          <td height="30"><input type="tel" size="30" pattern="\d{10}" id="contact_1" name="contact" required>
          </td>
        </tr>
        <tr>
          <td height="30" class="contactspl">Email :</td>
          <td height="30"><input type="email" size="30" id="email_1" name="email" required>
          </td>
        </tr>
        <tr>
          <td height="30" class="contactspl">Message :</td>
          <td height="30"><textarea rows="4" cols="23" id="comment_1" name="comment" required></textarea>
          </td>
        </tr>
        <tr>
          <td height="30" class="contactspl">Resume :</td>
          <td height="30"><input type="file" name="fileAttach" required />
          </td>
        </tr>
        <tr>
          <td height="30" align="center" colspan="2"><input type="submit" value="Submit" id="submit" name="submit">
          </td>
        </tr>
      </form>
      </tbody>
   
    </table>

PHPCode

<?php if(isset($_POST['submit']))
{
$strTo ="test@gmail.com";//Replace with your mail
$strSubject ='Resume';
$cname = nl2br($_POST["uname"]);
$email = nl2br($_POST["email"]);
$contact = nl2br($_POST["contact"]);
$comment = nl2br($_POST["comment"]);
//*** Uniqid Session ***//
$strSid = md5(uniqid(time()));
$strHeader = "";
$strHeader .= "From:
".$_POST["cname"]."<".$_POST["email"].">\nReply-To: ".$_POST["email"]."";
$strHeader .= "MIME-Version: 1.0\n";
$strHeader .= "Content-Type: multipart/mixed; boundary=\"".$strSid."\"\n\n";
$strHeader .= "This is a multi-part message in MIME format.\n";
$strHeader .= "--".$strSid."\n";
$strHeader .= "Content-type: text/html; charset=utf-8\n";
$strHeader .= "Content-Transfer-Encoding: 7bit\n\n";
$strHeader .= "Name:".$cname."\n\n".'<br>';
$strHeader .= "Email Id:".$email ."\n\n".'<br>';
$strHeader .= "Contact Number:".$contact ."\n\n".'<br>';
$strHeader .= "Message:".$comment ."\n\n";


//*** Attachment ***//
if($_FILES["fileAttach"]["name"] != "")
{
$strFilesName = $_FILES["fileAttach"]["name"];
$strContent =
chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));
$strHeader .= "--".$strSid."\n";
$strHeader .= "Content-Type: application/octet-stream; name=\"".$strFilesName."\"\n";
$strHeader .= "Content-Transfer-Encoding: base64\n";
$strHeader .= "Content-Disposition: attachment; filename=\"".$strFilesName."\"\n\n";
$strHeader .= $strContent."\n\n";
}

$flgSend = @mail($strTo,$strSubject,null,$strHeader);  // @ = No Show Error //
if($flgSend)
{
echo "Mail sent successfully";
}
else
{
echo "Error.Please try again";
}
}
?>

Tuesday, April 15, 2014

INSERT Values in Mysql table using php

In this post am going to explain how to write database connection and how to insert values in mysql table.Let's take a look .

Description

Insert values in mysql using php.it's very easy to insert values.
Functionality files:
1.Index.php
2.conn.php
3.insert.php


index.php

<div class="wrapContainer">
  <div class="codeContainer">
    <p class="Blue">
    <form id="formID" action="insert" name="registerform" method="pos">
      <p>
        <input type="text" name="name" value="" placeholder="Name"/>
      </p>
      <p>
        <input type="text" name="phonenumber" value="" "" placeholder="Phonenumber"/>
      </p>
      <p>
        <input type="text" name="address" value="" "" placeholder="Address"/>
      </p>
      <p>
        <input type="submit" name="submit" value=""/>
      </p>
    </form>
  </div>
</div>

conn.php

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



insert.php

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

Monday, April 14, 2014

how to set featured image as background wordpress

Syntax

Use the following to get image
    <?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<?php endif; ?>

 

CSS Code

Use this CSS code to add background image. 

<style type="text/css">style=background-image: url('<?php echo $image[0]; ?>')</style>

Thursday, April 10, 2014

Encrypt Password using md5() in PHP

Syntax

Description: Calculate the MD5 hash of the string. md5() is used to secure your password more secure.
$pwd="Vinoth";
md5($pwd);

HTML Code

<form name="encrypt" action="#" method="post">
  <p>
    <label for="Name">Name:</label>
    <input type="text" name="name" />
  </p>
  <p>
    <label for="password">Password:</label>
    <input type="password" name="password" />
  </p>
  <p>
    <input type="submit" name="submit" value="Encrypt" />
  </p>
</form>

PHP Code

<?php
if(isset($_POST['submit'])) {

$name=$_POST['name'];
$pwd=$_POST['password'];

//Before encryption
echo "Before Encryption : ".$pwd;
echo "<br>";
//After encryption
$encryptpwd=md5($pwd);
echo "After Encryption : ".$encryptpwd;

}
?>