Thursday, 22 November 2012

Extract zip images and Upload

<?php

$supload = isset($_POST["supload"]) ? $_POST["supload"] : "";

if($supload != ""){
    $dir = "upload/"; //The folder to store your images
    $fileName = $_FILES['sfile']['name']; //get the file name
    $fileSize = $_FILES['sfile']['size']; //get the size
    $fileError = $_FILES['sfile']['error']; //get the error code
    if($fileSize > 0 || $fileError == 0){ //check if the file is corrupt or error
        //$fname = $dir.$fileName;
        $zip = zip_open($_FILES['sfile']['tmp_name']);
        if(is_resource($zip)){
            do_upload($dir,$_FILES['sfile']['tmp_name']);
        }
    }else{
        echo "error! ".$fileSize." ".$fileError;
    }
}

function do_upload($dir,$path){
    $allowed_type = array("jpeg","jpg","gif","png","bmp","pjpeg");
    $zip = new ZipArchive;
    if ($zip->open($path) === true) {
        for($i = 0; $i < $zip->numFiles; $i++) {
            $filename = $zip->getNameIndex($i);

            //Get file informatin eg: filename, file extension, etc..
            $fileinfo = pathinfo($filename);
            $fname = $dir.$fileinfo['basename'];

            //Only proceed if it has an extension
            if(isset($fileinfo['extension'])){
                //Check if the file extension is an image file
                if(in_array($fileinfo['extension'],$allowed_type)){
                    //Now extract the file
                    if(copy("zip://".$path."#".$filename, $fname)){
                        echo "File ".$filename." uploaded. ";
                        //Create new filename for thumbnail
                        $newfilename = "th_".$fileinfo['basename'];

                        //Second check, To get the real MIME type
                        $imgInfo = getimagesize($fname);
                        echo "File Type: ".$imgInfo['mime']."<br />";
                        if(checkFileType($imgInfo['mime'])){
                            //Now resize the image
                            resize($fname, $dir.$newfilename);
                        }
                    }
                }else{
                    echo $filename." is not an image!<br />";
                }
            }
        }
        $zip->close();
        return true;
    }
}

function checkFileType($file){
    $imgType = array(
            "Gif"=>"image/gif",
            "JPG" => "image/jpg",
            "JPEG" => "image/jpeg",
            "PJPEG" => "image/pjpeg",
            "PNG" => "image/png",
            "BMP" => "image/bmp");
    if(in_array($file,$imgType))
            return true;
    else return false;
}

function resize($img, $newfilename) {
    //Check if GD extension is loaded
    if (!extension_loaded('gd') && !extension_loaded('gd2')) {
        trigger_error("GD is not loaded", E_USER_WARNING);
        return false;
    }
    $w = 100;
    $h = 100;

    //Get Image size info
    $imgInfo = getimagesize($img);
    switch ($imgInfo[2]) {
        case 1: $im = imagecreatefromgif($img); break;
        case 2: $im = imagecreatefromjpeg($img);  break;
        case 3: $im = imagecreatefrompng($img); break;
        default:  trigger_error('Unsupported filetype!', E_USER_WARNING);  break;
    }

    //If image dimension is smaller, do not resize
    if ($imgInfo[0] <= $w && $imgInfo[1] <= $h) {
        $nHeight = $imgInfo[1];
        $nWidth = $imgInfo[0];
    }else{
        //resize it, but keep it proportional
        if ($w/$imgInfo[0] > $h/$imgInfo[1]) {
            $nWidth = $w;
            $nHeight = $imgInfo[1]*($w/$imgInfo[0]);
            }else{
            $nWidth = $imgInfo[0]*($h/$imgInfo[1]);
            $nHeight = $h;
        }
    }
    $nWidth = round($nWidth);
    $nHeight = round($nHeight);

    $newImg = imagecreatetruecolor($nWidth, $nHeight);

    /* Check if this image is PNG or GIF, then set if Transparent*/
    if(($imgInfo[2] == 1) OR ($imgInfo[2]==3)){
        imagealphablending($newImg, false);
        imagesavealpha($newImg,true);
        $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
        imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
    }
    imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);

    //Generate the file, and rename it to $newfilename
    switch ($imgInfo[2]) {
        case 1: imagegif($newImg,$newfilename); break;
        case 2: imagejpeg($newImg,$newfilename);  break;
        case 3: imagepng($newImg,$newfilename); break;
        default:  trigger_error('Failed resize image!', E_USER_WARNING);  break;
    }

    return $newfilename;
}
?>
<form name="fsupload" action="" method="post" enctype="multipart/form-data">
    <div>
    Add Image: <input type="file" name="sfile" id="sfile" />
    <input type="submit" name="supload" value="Upload" />
    </div>
</form>

Thursday, 1 November 2012

Add google language translate bar to your site

Put this script in your head part 

<script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en',includedLanguages: 'en,de,es,fr,it,pt,ar,ja,ko,zh',  layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>



put this div where  you want to show language dropdown

<div id="google_translate_element"  class="languate-dropdown"></div>


 last...for hinding google translator bar from the top of your page
put this code in you css

.goog-te-banner-frame.skiptranslate {display: none !important;}
body { top: 0px !important; }


woiiiiiiiiiiiillaa....done...

Tuesday, 23 October 2012

cron it manually

<?php


$con = mysql_connect('localhost','root','');
if(!$con)
{
die("Error in database connection");
}
$sdb=mysql_select_db('mysite',$con);
if(!$sdb)
{
die("Erroe in database selection");
}
$select=mysql_query("select * from task order by id desc limit 1");
while($row=mysql_fetch_array($select)){$last_date=strtotime($row['last_run']);}



echo strtotime(date("d-m-y"))."</br>";
$today=date("d");
echo "todays date : ".date("d")."<br>";
$expiry = "23";
$date=strtotime(date('d-m-y'));
$d=date('d-m-y');
echo "last date".$last_date;

if($today==$expiry && $date!=$last_date){ echo "Code is executed";
$insert="insert into task (last_run,status)values('".$d."','1')";
$result=mysql_query($insert);



}
else{echo "this code will be executed after sometime and the last run is :".$last_date;}


?>

Saturday, 11 August 2012

GENERATE PASSWORDS

<?php
function generatePassword ($length = 7)
  {

    // start with a blank password
    $password = "";

  
    $possible = "234678951abcdefghijklmnopqrstuvqxyz";

    // we refer to the length of $possible a few times, so let's grab it now
    $maxlength = strlen($possible);
 
    // check for length overflow and truncate if necessary
    if ($length > $maxlength) {
      $length = $maxlength;
    }
   
    // set up a counter for how many characters are in the password so far
    $i = 0;
   
    // add random characters to $password until $length is reached
    while ($i < $length) {

      // pick a random character from the possible ones
      $char = substr($possible, mt_rand(0, $maxlength-1), 1);
       
      // have we already used this character in $password?
      if (!strstr($password, $char)) {
        // no, so it's OK to add it onto the end of whatever we've already got...
        $password .= $char;
        // ... and increase the counter by one
        $i++;
      }

    }

    // done!
    return $password;

  }
 
$pwd=generatePassword();
if(isset($_REQUEST['submit']))
{
   
    $gen=$_REQUEST['gen'];
    for($i=0;$i<$gen;$i++)
    {
        echo $pwd=generatePassword()."<br>";
    }
}


?>
<form name="form" method="get" action="">

<input type="text" name="gen" value="" >
<input type="submit" name="submit">
</form>

Thursday, 9 August 2012

Date convertion from Y-m-d to d-m-Y

Use strtotime() and date():
$originalDate = "2010-03-21";
$newDate = date("d-m-Y", strtotime($originalDate));

Friday, 29 June 2012

Use Of Append Javascript

<html>
<head>
 <title>
 </title> 
 <!--Standard jQuery -->
 <script type="text/javascript" src="jquery.js" charset="utf-8"></script>
 <script type="text/javascript">
  $(document).ready(function()
  {
   $('#boxClear').click(function(){
    $('#firstFilterSearch').val('');

   });

   $('#firstFilterSearch').keyup(function()
   {
    var searchArea = $('#firstList');
    searchFirstList($(this).val(), searchArea);
   });

   $('#firstList').dblclick(function() {
    assignList();
   });

   $('#secondList').dblclick(function() {
    unassignList();
   });

   $('#to2').click(function()
   {
    assignList();
   });

   $('#to1').click(function()
   {
    unassignList();
   });
  });
   
  // Function for Filtering
  function searchFirstList(inputVal, searchArea)
  {
   var allCells = $(searchArea).find('option');
   if(allCells.length > 0)
   {
    var found = false;
    allCells.each(function(index, option)
    {
     var regExp = new RegExp(inputVal, 'i');
     if(regExp.test($(option).text()))
     {
      $(option).show();
     }
     else
     {
      $(option).hide();
     }
    });
   }
  }

  // function: UnAssignment
  function assignList()
  {
   $('#firstList :selected').each(function(i, selected){
    // append to second list box
    $('#secondList').append('<option value="'+selected.value+'">'+ selected.text+'</option>');
    // remove from first list box
    $("#firstList option[value='"+ selected.value +"']").remove();
   });
  }
  // function: UnAssignment
  function unassignList()
  {
   $('#secondList :selected').each(function(i, selected){
    // append to first list box
    $('#firstList').append('<option value="'+selected.value+'">'+ selected.text+'</option>');
    // remove from second list box
    $("#secondList option[value='"+ selected.value +"']").remove();
   });
  }
 </script>


</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%"> 
 <tr>  
  <td width="100%">
   <form id="frm_format" method="" action="">
   <table cellpadding="0" id="tbl_format"cellspacing="0" border="0" width="100%" class="standard_table_v4"> 
    <thead>
    </thead>
    <tbody>
     <tr>
      <td>
      <td align="center">
       Filter: <input id="firstFilterSearch" type="text">
         <input type="button" id="boxClear" name="boxClear" value="Cancel"><br>
       <select id="firstList" multiple="multiple" style="height:420px;width: 250px;" > 
        <option value="1">PHP</option>
        <option value="2">.Net</option>
        <option value="3">Copy</option>
        <option value="4">Paste</option>
        <option value="5">Pea</option>
        <option value="6">Pamp</option>
        <option value="7">ladaku</option>
        <option value="8">Zebra</option>
       </select>
      </td>
      <td align="center">
       <input id="to2" type="button" name="to2"  title='assign' value=">" /><br/><br/>
       <input id="to1" type="button" name="to1" title='unassign' value="<">
      </td>
      <td>
       <select id="secondList" multiple="multiple" style="height:420px;width: 250px;" >
       </select>
      </td>
     </tr>
    </tbody>
   </table>
   </form>
   
  </td>
 </tr>
</table>
</body>
</html>

Friday, 22 June 2012

Ajax Autocomplete – Jquery PHP Mysql


Before Start

The aim is to design an auto complete script for text box in ajax using Jquery, PHP, Mysql. I have searched for the script, and i have found a simple autocomplete plugin here http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/ and you can find the documentation here http://docs.jquery.com/Plugins/Autocomplete.
You can download the source and see the Demos. But there is no demo fetching data from mysql. Then i have done some small trick in the php file to get data from mysql. This will be very useful in search suggestions, City, State fill up in some registrations.

HTML – Understanding the Layout

Here i have taken course names for example. I have a text box named and ided course. Thats all you need to know in the html layout.
<input type="text" name="course" id="course" />

JS – Include autocomplete plugin and activate

Download the autocomplete source from http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/ and get the jquery core, autocomplete javascript file and css file. Include them inside the head tag. After that write some code to activate the text box with autocomplete.
<script type="text/javascript" src="jquery.js"></script>
<script type='text/javascript' src='jquery.autocomplete.js'></script>
<link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
 
<script type="text/javascript">
$().ready(function() {
    $("#course").autocomplete("get_course_list.php", {
        width: 260,
        matchContains: true,
        selectFirst: false
    });
});
</script>

To know the autocomplete plugin options go to here http://docs.jquery.com/Plugins/Autocomplete/autocomplete and see the Options tab.

PHP – Get data from DB

Get the query word and search within the database and return the list. (get_course_list.php file mentioned in the above javascript)
<?php
require_once "config.php";
$q = strtolower($_GET["q"]);
if (!$q) return;
 
$sql = "select DISTINCT course_name as course_name from course where course_name LIKE '%$q%'";
$rsd = mysql_query($sql);
while($rs = mysql_fetch_array($rsd)) {
    $cname = $rs['course_name'];
    echo "$cname\n";
}
?>

Download

Download Source