Friday, December 14, 2012

Copy an existing MySQL table to a new table

This Command is used to create new table with the structure and data of an existing table.


Existing Table name : users


New Table name : users_Mon

 

CREATE TABLE users_Mon LIKE users; INSERT users_Mon SELECT * FROM users;

Friday, December 07, 2012

Scroll loading content with ajax

Today we learn about some thing in Ajax in jquery.First i said  thanks for the code.And i got this code from google and share with all.Its really helpful for us. How can the content loading from scroll using  ajax method.This is easiest way to learn it.simply few steps to follow. And this is one type of pagination too.

Step 1:
<script type="text/javascript" src="http://www:yoursite.com/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://www:yoursite.com/js/scroll.js"></script>
    <script type="text/javascript">
      // var mtu4 = jQuery.noConflict();
      //  mtu4(function($){                   
            $('#archive1').scrollLoad({               
                    url : 'http://www.yoursite.com/getarchive1_infos.php', //your ajax file to be loaded when scroll breaks ScrollAfterHeight
            getData : function()
                           {
                    // you can post some data along with ajax request  return {offset:rel_data,userName:'Web Developer'};   
                      var rel_data = $("#infinite_scroll").attr("rel");
                      rel_data = parseInt(rel_data);                       
                      rel_data = rel_data+15;
                      $("#infinite_scroll").attr("rel",rel_data);
                      return {offset:rel_data};                           
                },
                start : function() {
                    $('<div class="loading" style="padding:10px 0; margin:0 37.7%;"><p style=" font-size: 14px;font-weight: bold;line-height: 25px;">Loading...</p><img src="http://www.yoursite.com/images/uploading.gif"/></div>').appendTo(this);
                    // you can add your effect before loading data
                },
       ScrollAfterHeight : 95, //this is the height in percentage after which ajax stars
                onload : function( data ) {
                                        $(this).append( data );
                                        $('.loading').remove();
                }, // this event fires on ajax success

                continueWhile : function( resp ) {
                    if( $(this).children('li').length >= 100 ) { // stops when number of 'li' reaches 100
                        return false;
                    }
                    return true;
                }
            });    
                //});    
        </script>       

Step 2:       
Following content html first loading with 15 records in landing page.Once the end of the scroll another 15 records will loading from ajax file (getarchive1_infos.php).

       <div class="chart_table1" id="archive1">
             <div id="infinite_scroll"  class="scroll" rel="0">
           <?php for ($i=1; $i<=15; $i++){    ?>
                   <p>hi this is sample test</p>
          <?php } ?>
           </div>
      </div>

Step 3:                       
This is getarchive1_infos.php ajax file.Another 15 records are loading.  
      <?php
                    $offset = $_REQUEST['offset'];
               for ($i=1; $i<=$offset; $i++){    ?>
                   <p>hi this is sample test from ajax</p>
                    <?php } ?>
         
step 4:
    And this is scroll.js script file.      
    <script type="application/javascript">
        ( function( $ ) {
    $.fn.scrollLoad = function( options ) {
   
        var defaults = {
            url : '',
            data : '',
            ScrollAfterHeight : 90,
            onload : function( data, itsMe ) {
                alert( data );
            },
            start : function( itsMe ){},
            continueWhile : function() {
                return true;
            },
            getData : function( itsMe ) {
                return '';
            }
        };

        for( var eachProperty in defaults ) {
            if( options[ eachProperty ] ) {
                defaults[ eachProperty ] = options[ eachProperty ];
            }
        }

        return this.each( function() {
            this.scrolling = false;
            this.scrollPrev = this.onscroll ? this.onscroll : null;
            $( this ).bind( 'scroll', function ( e ) {
                if( this.scrollPrev ) {
                    this.scrollPrev();
                }
                if( this.scrolling ) return;
                //var totalPixels = $( this ).attr( 'scrollHeight' ) - $( this ).attr( 'clientHeight' );
                if( Math.round( $( this ).attr( 'scrollTop' ) / ( $( this ).attr( 'scrollHeight' ) - $( this ).attr( 'clientHeight' ) ) * 100 ) > defaults.ScrollAfterHeight ) {
                    defaults.start.call( this, this );
                    this.scrolling = true;
                    $this = $( this );
                    $.ajax( { url : defaults.url, data : defaults.getData.call( this, this ), type : 'post', success : function( data ) {
                        $this[ 0 ].scrolling = false;
                        defaults.onload.call( $this[ 0 ], data, $this[ 0 ] );
                        if( !defaults.continueWhile.call( $this[ 0 ], data ) ) {
                            $this.unbind( 'scroll' );
                        }
                    }});
                }
            });
        });
    }
})( jQuery );
</script> 


Finally we learn about this , how can scroll the content loading from ajax.
cheers friends!!! :)
   

Saturday, November 17, 2012

Force file download in php

Now we learning about download in php. Following contents are how can we simply download the file in php . Now this sample code for how to download .mp3 file. And we give some mime types for other files.

   $filepath  = "/path/to/testfile.mp3";
$filename = "testfile.mp3";
$mime     = 'audio/mpeg';
$data       = file_get_contents($filepath);

if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
{
header('Content-Type: "'.$mime.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: public');
header("Content-Length: ".strlen($data));
}
else
{
header('Content-Type: "'.$mime.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: ".strlen($data));
}
exit($data);

Other mime types used in download:

$mimes = array( 'hqx' => 'application/mac-binhex40',
'cpt' => 'application/mac-compactpro',
'csv' => array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel'),
'bin' => 'application/macbinary',
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'exe' => 'application/octet-stream',
'class' => 'application/octet-stream',
'psd' => 'application/x-photoshop',
'so' => 'application/octet-stream',
'sea' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => array('application/pdf', 'application/x-download'),
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => array('application/excel', 'application/vnd.ms-excel', 'application/msexcel'),
'ppt' => array('application/powerpoint', 'application/vnd.ms-powerpoint'),
'wbxml' => 'application/wbxml',
'wmlc' => 'application/wmlc',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'dvi' => 'application/x-dvi',
'gtar' => 'application/x-gtar',
'gz' => 'application/x-gzip',
'php' => 'application/x-httpd-php',
'php4' => 'application/x-httpd-php',
'php3' => 'application/x-httpd-php',
'phtml' => 'application/x-httpd-php',
'phps' => 'application/x-httpd-php-source',
'js' => 'application/x-javascript',
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'tar' => 'application/x-tar',
'tgz' => 'application/x-tar',
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'zip' =>  array('application/x-zip', 'application/zip', 'application/x-zip-compressed'),
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp3' => array('audio/mpeg', 'audio/mpg'),
'aif' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'ra' => 'audio/x-realaudio',
'rv' => 'video/vnd.rn-realvideo',
'wav' => 'audio/x-wav',
'bmp' => 'image/bmp',
'gif' => 'image/gif',
'jpeg' => array('image/jpeg', 'image/pjpeg'),
'jpg' => array('image/jpeg', 'image/pjpeg'),
'jpe' => array('image/jpeg', 'image/pjpeg'),
'png' => array('image/png',  'image/x-png'),
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'css' => 'text/css',
'html' => 'text/html',
'htm' => 'text/html',
'shtml' => 'text/html',
'txt' => 'text/plain',
'text' => 'text/plain',
'log' => array('text/plain', 'text/x-log'),
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'xml' => 'text/xml',
'xsl' => 'text/xml',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'avi' => 'video/x-msvideo',
'movie' => 'video/x-sgi-movie',
'doc' => 'application/msword',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'word' => array('application/msword', 'application/octet-stream'),
'xl' => 'application/excel',
'eml' => 'message/rfc822'
);


Friday, November 16, 2012

simple multiple upload in php

Multiple upload files in php  is very simply. Read the following steps and you can learn some jquery options in the multiple upload.

Step 1:


<form id="filename" action="" method="post" enctype="multipart/form-data">

<p style="background:#3F3F3F;color:#FFF"><span id="spanButtonPlaceHolder"></span>&nbsp;
<span class="add_field"><img src="/images/plus.gif" /></span>
<span class="remove_field"><img src="/images/minus.gif" /></span>
<span style="font-weight:bold; color:#03DE3B; line-height:24px; margin-left:10px;"> (You can upload more than one track at a time.) </span>
<div class="input_holder">
<input class="upload_btn" type="file" name="uploaded_files[]" id="input_clone"/>
<input class="upload_btn" type="file" name="uploaded_files[]"/>
</div>
</p>
<div id="light" class="white_content2"><p>Please wait the tracks are uploading...</p><img class="uploadprocess" width="128" src="/images/uploading.gif"></div>
<div id="fade1" class="black_overlay"></div>
<div id="underlay"></div>
<input type="submit" name="upload" value="Upload" class="validate clsappSbut orngbtn">

<div class="btnclear">
<a class="bck_btn" href="http://backurl"><img src="/images/back.jpg"></a>
<a class="nxt_btn" href="http://nexturl">Next</a>
</div>


</form>



Step 2:
This script is very important for multiple upload.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
/*If you have any jquery conflicts , use above two lines instead of  $(function(){ */
//var jq=jQuery.noConflict();
//jq(function($){

$(function(){

/*If you click the plus button the clone is genrated*/

 $('.add_field').click(function(){
   var input = $('#input_clone');
   var clone = input.clone(true);
   clone.removeAttr ('id');
   clone.val('');
   clone.appendTo('.input_holder');
  });

/*If you click the minus button the clone is removed*/
  $('.remove_field').click(function(){
   if($('.input_holder input:last-child').attr('id') != 'input_clone'){
    $('.input_holder input:last-child').remove();
   }
  });

/*If you click next button wioth out any files it throws error.*/

 $(".nxt_btn").click(function(event){
var fcount = $("#uploadedFilesList").attr("rel");
fcount = parseInt(fcount);
var rurl= $(this).attr("href");

if(fcount==0)
{
alert('Please upload files.');
return false;
}else{
return true;
}
  });

/* upload sumbitting time */

  $("#filename").submit(function(){
   var cnt=0;
   var ecnt=0;
   var big_v=0;
   var fcount = $("#uploadedFilesList").attr("rel");
   fcount = parseInt(fcount);
/*To check each file like forloop in jquery*/
     $("input[name='uploaded_files[]']").each(function(i, file){
     var c_file = $(this);
     var fileName = c_file.val();  
     var flength = $("input[name='uploaded_files[]']").length;
     flength = parseInt(flength);
     var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
     var ext=ext.toLowerCase();
     var id_v = $(this).attr("id");

      if(ext!="mp3" && ext.length>0)
      {    
        /*If the selected value is not .mp3 file , to empty the selected value*/
if ($.browser.msie) {
c_file.replaceWith(c_file.clone());
}else{
c_file.val("");
}
 cnt++;
      }
   
      if(ext=="mp3")
      {
          ecnt++;
       }
   
     });

 
   if(cnt>0)
   {
     alert("Please upload Mp3 files only");
     return false;
   }
 
   if(ecnt==0)
   {
    alert("Please upload Mp3 files");
    return false;
   }
 
    if(cnt==0 && ecnt>0 )
   {
       if(ecnt>0)
     {
/*This is for showing upload the progress gif image with lightbox effect.we not navigate any other page while the uploading is finish*/
$("#light").show();
$("#fade1").show();
return true;
     }
 
   }
     return false;
   });

});
</script>



Step 3:
Css content to displayed like the light-box and some effects.
<style type="text/css">
.input_holder input{
display:block;
}

.clsAppForm span img {
    vertical-align: middle;
}
.white_content2
{
display: none;
background-color: black;
border: 10px solid #272727;
height:auto;
left: 25%;
padding: 18px 9px;
position: fixed;
top: 25%;
width: 534px;
z-index: 1002;
}

.white_content2 .uploadprocess { width:128px; display:block; margin:0 auto;}
.white_content2 p{color:#FFFFFF; text-align:center; font-weight:bold; padding:0 0 10px;}

.black_overlay{
display: none;
position: fixed;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: black;
z-index:1001;
-moz-opacity: 0.8;
opacity:.80;
filter: alpha(opacity=80);
}
.upload_btn { background: #9B9B9B; border: 1px solid #9B9B9B; width:500px;}
.btnclear { clear:both; overflow:hidden;}
.bck_btn { float:left;}
.nxt_btn { float:left; width:69px; height:24px; background:url(/images/continue.jpg) no-repeat 0 0; text-align:center; line-height:24px; display:inline-block; margin:0 0 0 10px;}
input.orngbtn {background:#f8a513; border:none; font-weight:bold; padding:5px 10px;}
</style>

Step 4:
This is the final output in the post values.

if(isset($_FILES['uploaded_files']))
{
    if($_FILES['uploaded_files']!='')
{
//For each file get the $key so you can check them by their key value
foreach($_FILES['uploaded_files']['name'] as $key => $value)
{
//If the file was uploaded successful and there is no error
if(is_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key]) && $_FILES['uploaded_files']['error'][$key] == 0)
{

//Create an unique name for the file using the current timestamp, an random number and the filename
$filename = $_FILES['uploaded_files']['name'][$key];
   $filename = time().$filename;
$uploadPath="uploadedpath/".$filename;
$fsize = $_FILES['uploaded_files']['size'][$key];
$fsize=($fsize)/1048576;
  $size = round($fsize);
if($size<30){
//Check if the file was moved
if(move_uploaded_file($_FILES['uploaded_files']['tmp_name'][$key], $uploadPath))
{
// echo 'The file ' . $_FILES['uploaded_files']['name'][$key].' was uploaded successful <br/>';
}
}

}
}

}
}

Finally you done the multiple upload with simple jquery learning. Implement the code and share your thoughts.Cheers friends!!!







Monday, November 05, 2012

Get number of rows in joomla


Simple to Count the number of rows in joomla.
getNumRows() function used to count the rows.

Example:

$db =& JFactory::getDBO();
$query  = "SELECT * from #__table";
$db->setQuery($query);
$db->query();
$count=$db->getNumRows();

Friday, November 02, 2012

Mysql composite unique key

First We have created Table:

CREATE TABLE IF NOT EXISTS `userlist` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `Listname` varchar(50) NOT NULL,
  `Listval1` varchar(50) NOT NULL,
  `Listval2` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


Next Execute this query:

ALTER TABLE `userlist` ADD UNIQUE KEY (Listname,Listval1);

Insert Rows:

 INSERT INTO `tiketsoft`.`userlist` (`id`, `Listname`, `Listval1`, `Listval2`) VALUES (NULL, 'country', 'India', 'IN');

same record insert again its display below message

#1062 - Duplicate entry 'country-India' for key 'Listname'

Same time execute below query run successfully:

INSERT INTO `tiketsoft`.`userlist` (`id`, `Listname`, `Listval1`, `Listval2`) VALUES (NULL, 'country', 'China', 'Ch');


Thursday, November 01, 2012

PHP Display floating number with 2 leading zeros


<?php
 $no = "2.8" ;

$no1 =  sprintf("%01.2f",$no);

echo $no1;
echo "<br/>";

?>

output : 2.80

// suppose input is 0.4 => output 0.40

Wednesday, October 31, 2012

Delete duplicate rows in mysql and php

How to delete duplicate records in table?
For example :
user_new table - total rows - 45000
duplicate rows - 5150

I have used below this code.It works fine.cheers!!!

<?php 
ini_set("max_execution_time","18800");
$con = mysql_connect("localhost","root","root");
mysql_select_db("testdb",$con);

$query = "SELECT email,count(email),group_concat(user_id) as uid FROM `user_new` group by email having count(email) > 1  ";

$result = mysql_query($query);
$total_rows = mysql_num_rows($result);
$del_ids = array();

if($total_rows>0)
{
  while($row=mysql_fetch_object($result))
  {
    $uid = $row->uid;
$aUid = explode(",",$uid);
array_shift($aUid);
 $rids = array_merge($del_ids,$aUid);
 $del_ids =  $rids;
   }
 //   print_r($del_ids);
   $Sdel_ids = implode(",",$del_ids);
   $del_query = "DELETE FROM user_new where user_id in ($Sdel_ids) ";
   echo $del_query;
   mysql_query($del_query);
}

?>

Tuesday, October 23, 2012

Image re-size exactly in php

Simply two steps to re-size the image as your given dimensions.

Step 1:
 // *** Include the class
include("resize_class.php");
// *** 1) Initialise / load image
$resizeObj = new resize('images/cars/large/original.jpg');
// *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
$resizeObj -> resizeImage(230 , 108, 'exact');
// *** 3) Save image
$resizeObj -> saveImage('images/cars/small/resizeimage.jpg', 100);

Step 2:
Save this content as resize_class.php.


Class resize
{
// *** Class variables
    private $image;
   private $width;
   private $height;
    private $imageResized;

function __construct($fileName)
{
    // *** Open up the file
    $this->image = $this->openImage($fileName);

   // *** Get width and height
   $this->width  = imagesx($this->image);
   $this->height = imagesy($this->image);
}

private function openImage($file)
{
// *** Get extension
$extension = strtolower(strrchr($file, '.'));

switch($extension)
{
case '.jpg':
case '.jpeg':
$img = @imagecreatefromjpeg($file);
break;
case '.gif':
$img = @imagecreatefromgif($file);
break;
case '.png':
$img = @imagecreatefrompng($file);
break;
default:
$img = false;
break;
}
return $img;
}

public function resizeImage($newWidth, $newHeight, $option="auto")
{
// *** Get optimal width and height - based on $option
$optionArray = $this->getDimensions($newWidth, $newHeight, $option);

$optimalWidth  = $optionArray['optimalWidth'];
$optimalHeight = $optionArray['optimalHeight'];


// *** Resample - create image canvas of x, y size
$this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);
imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height);


// *** if option is 'crop', then crop too
if ($option == 'crop') {
$this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);
}
}

private function getDimensions($newWidth, $newHeight, $option)
{

  switch ($option)
{
case 'exact':
$optimalWidth = $newWidth;
$optimalHeight= $newHeight;
break;
case 'portrait':
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight= $newHeight;
break;
case 'landscape':
$optimalWidth = $newWidth;
$optimalHeight= $this->getSizeByFixedWidth($newWidth);
break;
case 'auto':
$optionArray = $this->getSizeByAuto($newWidth, $newHeight);
$optimalWidth = $optionArray['optimalWidth'];
$optimalHeight = $optionArray['optimalHeight'];
break;
case 'crop':
$optionArray = $this->getOptimalCrop($newWidth, $newHeight);
$optimalWidth = $optionArray['optimalWidth'];
$optimalHeight = $optionArray['optimalHeight'];
break;
}
return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}

private function getSizeByFixedHeight($newHeight)
{
$ratio = $this->width / $this->height;
$newWidth = $newHeight * $ratio;
return $newWidth;
}

private function getSizeByFixedWidth($newWidth)
{
$ratio = $this->height / $this->width;
$newHeight = $newWidth * $ratio;
return $newHeight;
}

private function getSizeByAuto($newWidth, $newHeight)
{
if ($this->height < $this->width)
// *** Image to be resized is wider (landscape)
{
$optimalWidth = $newWidth;
$optimalHeight= $this->getSizeByFixedWidth($newWidth);
}
elseif ($this->height > $this->width)
// *** Image to be resized is taller (portrait)
{
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight= $newHeight;
}
else
// *** Image to be resizerd is a square
{
if ($newHeight < $newWidth) {
$optimalWidth = $newWidth;
$optimalHeight= $this->getSizeByFixedWidth($newWidth);
} else if ($newHeight > $newWidth) {
$optimalWidth = $this->getSizeByFixedHeight($newHeight);
$optimalHeight= $newHeight;
} else {
// *** Sqaure being resized to a square
$optimalWidth = $newWidth;
$optimalHeight= $newHeight;
}
}

return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}
     
         private function getOptimalCrop($newWidth, $newHeight)
{

$heightRatio = $this->height / $newHeight;
$widthRatio  = $this->width /  $newWidth;

if ($heightRatio < $widthRatio) {
$optimalRatio = $heightRatio;
} else {
$optimalRatio = $widthRatio;
}

$optimalHeight = $this->height / $optimalRatio;
$optimalWidth  = $this->width  / $optimalRatio;

return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
}


      private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight)
{
// *** Find center - this will be used for the crop
$cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
$cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 );

$crop = $this->imageResized;
//imagedestroy($this->imageResized);

// *** Now crop from center to exact requested size
$this->imageResized = imagecreatetruecolor($newWidth , $newHeight);
imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight);
}

public function saveImage($savePath, $imageQuality="100")
{
// *** Get extension
        $extension = strrchr($savePath, '.');
        $extension = strtolower($extension);

switch($extension)
{
case '.jpg':
case '.jpeg':
if (imagetypes() & IMG_JPG) {
imagejpeg($this->imageResized, $savePath, $imageQuality);
}
break;

case '.gif':
if (imagetypes() & IMG_GIF) {
imagegif($this->imageResized, $savePath);
}
break;

case '.png':
// *** Scale quality from 0-100 to 0-9
$scaleQuality = round(($imageQuality/100) * 9);

// *** Invert quality setting as 0 is best, not 9
$invertScaleQuality = 9 - $scaleQuality;

if (imagetypes() & IMG_PNG) {
imagepng($this->imageResized, $savePath, $invertScaleQuality);
}
break;

// ... etc

default:
// *** No extension - No save.
break;
}

imagedestroy($this->imageResized);
}
}

Friday, October 19, 2012

Remove special characters from file name

       If you use special characters filename

            $f_name = "filename"; // given filename

            $f_name = trim($f_name,".");  // trim the first or last character "."

            $afilename=explode(".",$f_name);  // explode filename using separator  "."

            $f_ext = end($afilename);  // end keyword used to return the array end of value

            $f_name = reset($afilename); //  reset keyword used to return the array start of value

            $filename = $f_name.".".$f_ext;

            $str    = $filename;

            $sp_chr = array("[,]","[']","[=]","[;]");

            $str = preg_replace($sp_chr,"-",$str);   // using preg replace to replace the . , = ;

            $str = preg_replace("/&/","and",$str);  // replace & to and





           // below steps are replace the . or * or ? or / <  > change to -.

            $str = str_replace(".","-",$str); 
            $str = str_replace(":","-",$str);
            $str = str_replace("*","-",$str);
            $str = str_replace("/","-",$str);
            $str = str_replace("<","-",$str);
            $str = str_replace(">","-",$str);
            $str = str_replace("\"","-",$str);

            $filename = $str;




Thursday, October 18, 2012

Ogone payment integration in php

Ogone payment simply done in two steps.

 Step 1:        
 $PSPID = 'YOURPSPID'; //'OGONETEST';
 $Price = "100"; // PAYPAL
 $passphrase = 'YOURSECRETKEY';
 $unique_id = RAND(890000,895689596);
 $pm = "CREDIT CARD";
$accept_url="http://yourreturnurl.com"; //Like IPN
$cancelurl="http://yourcancelurl.com";

//If you add any parameters in  Ogone_sha1 order by Alphabet order.
 $Ogone_sha1 =  
                        "ACCEPTURL=".$accept_url.$passphrase.
                        "AMOUNT=".$credit.$passphrase.
                         "BGCOLOR=#010000".$passphrase.
                         "CANCELURL=".$cancelurl.$passphrase.
                         "CURRENCY=EUR".$passphrase.
                         "LANGUAGE=en_us".$passphrase.
                         "ORDERID=".$unique_id.$passphrase.
                         "PM=".$pm.$passphrase.
                         "PSPID=".$PSPID.$passphrase.
                         "TITLE=Payment via Ogone".$passphrase;
//Creating the signature
   $Ogone_sha1 = sha1($Ogone_sha1);

// For test use the url in action https://secure.ogone.com/ncol/test/orderstandard.asp

 $form1 = '<form name="directpayment1" id="directpayment" action="https://secure.ogone.com/ncol/prod/orderstandard.asp" method="post" >
      <input name="PSPID" type="hidden" value="'.$PSPID.'" />
      <input name="AMOUNT" type="hidden" value="'.$credit.'" />
      <input name="ACCEPTURL" type="hidden" value="'.$accept_url.'" />
      <input name="CANCELURL" type="hidden" value="'.$cancelurl.'" />
      <input name="ORDERID" type="hidden" value="'.$unique_id.'" />
      <input name="CURRENCY" type="hidden" value="EUR" />
      <input name="LANGUAGE" type="hidden" value="en_us" />
      <input name="PM"  type="hidden" value="'.$pm.'">
      <input name="TITLE"  type="hidden" value="Payment via Ogone">
      <input name="BGCOLOR"  type="hidden" value="#010000">
      <input name="SHASIGN" type="hidden" value="'.$Ogone_sha1.'" />    
      </form><script>document.getElementById("directpayment").submit()</script>';   
      echo $form1;

Step 2:

If the ogone payment is done it calls the accept url.

$pay_status= $_REQUEST['STATUS'];
//Status 9 is success for PAYPAL and 5 is authorized for CREDIT CARD
$pay_id=$_REQUEST['PAYID'];
//Like Transaction id
$pay_types=$_REQUEST['BRAND'];
$pay_ipaddress=$_REQUEST['IP'];
$paytype =$_REQUEST['PM'];
$amount=$_REQUEST['AMOUNT'];
$invoiceNumber = $_REQUEST['ORDERID'];

Just all the values are get from request like PAYID , ORDERID , STATUS values. Thats all. simply ogone payment is implemented.
Cheers!!!!

Create thumbnails for mp4 using ffmpeg

First of all note this point. If you use this code in your local server use ffmpeg for windows exe file.otherwise use linux server user use linux version.

//In your ffmpeg.exe file path
$ffmpeg_path = 'ffmpeg';

//In your video file
$video_path = 'video_old.mp4';

// Image destination path
$image = "video_old".time().'.jpg';

// default time to get the image
$second = 1;

// get the duration and a random place within that
$comd = "$ffmpeg_path -i $video_path -deinterlace -an -ss $second -t 00:00:01 -r 1 -y -vcodec mjpeg -f mjpeg $image 2>&1";

shell_exec($comd);


Note: not need to given path is ffmpeg.exe.only given ffmpeg.

Thursday, October 04, 2012

PayPal Recurring Payments


When you use PayPal Subscriptions and Recurring Payments, your customers can purchase automatically recurring subscriptions from your website, or even using a link in an email!
Subscriptions and Recurring Payments is a low-cost way for you to accept credit card and bank account payments for content site subscriptions, newsletter fees, club dues, or recurring donations, and can be fully integrated with your website in a few easy steps. Subscriptions and Recurring Payments is only available for Business or Premier accounts.


What are the benefits?

Save time and money with PayPal's hassle-free Subscriptions and Recurring Payments:
  • Easy to implement - flexible and automatic billing frees you from sending invoices
  • No up-front costs - you'll have the same low fee schedule used when you receive other PayPal payments
  • Sell with ease - PayPal maintains detailed transaction records on our website
  • Improve buyer experience - with customizable buttons and secure payments, happy customers become repeat customers

How to implement:

This is simple. You just need to add three  hidden fields listed below.

<input type="hidden" name="src" value="1">
<input type="hidden" name="sra" value="1"> 
<input type="hidden" name="srt" value="1">

src

Recurring payments. Subscription payments recur unless subscribers cancel their subscriptions before the end of the current billing cycle or you limit the number of times that payments recur with the value that you specify for srt.
Allowable values are:
  • 0 – subscription payments do not recur
  • 1 – subscription payments recur
The default is 0.

srt
Optional
Recurring times. Number of times that subscription payments recur. Specify an integer with a minimum value of 1 and a maximum value of 52. Valid only if you specify src="1".

sra

Reattempt on failure. If a recurring payment fails, PayPal attempts to collect the payment two more times before canceling the subscription.
Allowable values are:
  • 0 – do not reattempt failed recurring payments
  • 1 – reattempt failed recurring payments before canceling
The default is 1.






Tuesday, September 18, 2012

Open url in new tab using javascript

Javascipt :


<script type="text/javascript">
function click_o(url){
alert(url);
window.open(url, '_blank');
window.focus();
}
</script>


Html Content:


<a href="javascript:void(0);" onclick="click_o('http://www.jquery.com')">jquery</a>

Monday, September 17, 2012

Some interesting facts about PHP.


1) It is possible to use PHP in almost every operating system. PHP can be used in all major operating systems including Linux, Microsoft Windows, Mac OS X, and RISC OS.

2) PHP uses procedural programming or object oriented programming and also a mixture of them.

3) PHP is installed on over 20 million websites and 1 million web servers.

4) 75% of Web 2.0 sites are built in PHP.

5) There are about 5 million PHP developers worldwide.

6) The latest release of PHP till now is 5.3.0. It was released on Jun 30, 2009. PHP 6 is under development alongside PHP 5. Major changes include the removal of register_globals, magic quotes, and safe mode. The reason for the removals was that register_globals had given way to security holes, and magic quotes had an unpredictable nature, and was best avoided.

7)  Some of the biggest online brands, such as Facebook, ProProfs, Digg, Friendster, Flickr, Technorati, and Yahoo! are powered by PHP.

Friday, September 14, 2012

What Every Developer Must Know About PHP 5.4 ?


Some of the key new features include traits, a shortened array syntax, a built-in webserver for testing purposes, use of $this in closures, class member access on instantiation, <?= is always available, and more!
PHP 5.4.0 significantly improves performance, memory footprint and fixes over 100 bugs. Notable deprecated/removed features include register_globals, magic_quotes (about time) and safe_mode. Also worth mentioning is the fact that multibyte support is enabled by default and default_charset has been changed from ISO-8859-1 to UTF-8.

1. Trait Support
As of PHP 5.4.0, PHP implements a method of code reuse called Traits.
Traits is a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.
A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.
.
2. Improvements to Arrays
PHP 5.4 includes two significant improvements to arrays – support for short array syntax and dereferencing of arrays from function and method calls. Both these changes make the code easier to read and manage.
No more temporary variables when dealing with arrays!
Let’s imagine that we want to retrieve the middle name of Alan Mathison Turing:

echo explode(' ', 'Alan Mathison Turing')[1]; // Mathison
Sweet; but it wasn’t always this easy. Before 5.4, we had to do:

$tmp = explode(' ', 'Alan Mathison Turing');
echo $tmp[1]; // Mathison
Now, what if we want to get the last name (last element in array):

echo end(explode(' ', 'Alan Mathison Turing')); // Turing
This works fine, however, it will throw a E_STRICT (Strict Standards: Only variables should be passed by reference) error, since it became part of E_ALL in error_reporting.
Here’s a slightly more advanced example:


function foobar()
{
    return ['foo' => ['bar' => 'Hello']];
}
echo foobar()['foo']['bar']; // Hello

 3. $this Support in Closures
You can now refer to the object instance from anonymous functions (also known as closures) by using $this.
Anonymous or unnamed functions are called closures. These functions are very useful as the value of callback parameters. Prior to PHP 5.4, referring to object instances from closures required lengthy workarounds. With support for $this, you can call on any object property in any anonymous function, eliminating the need for hacks.

4. Built-in Web Server
Since the focus of PHP 5.4 is to streamline the development process, it includes a built-in web server in CLI mode on port 8000 to facilitate faster development and testing, thereby eliminating the need to set up an Apache HTTPD server. This server can be called on by using a simple command:
Open the command prompt (Windows + R, type in cmd, hit Enter); you should see something like this, depending on your Windows version.
Change your current directory to the PHP installation by following the example below:
Here comes the most important part – running the web-server. Copy…
… and paste it in the command prompt (right mouse button, click Paste to paste). Hit Enter. If all goes well, you should see something similar to what’s shown below. Do not close the command prompt; if you do, you will exit the web-server as well.

 5. < ?= Support is Always Available
Regardless of the php.ini setting, short_open_tag, <?= (open PHP tag and echo) will always be available. This means that you can now safely use:
<?=$title?>…in your templates instead of…<?php echo $title ?>