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