Monday, 30 July 2012

In cake php Upload file/image without refresh page with the help of ajax and validate extension.


Upload file without refreshing page in cakephp
1.controller/controlername_controller.php
class DoctorsController extends AppController {
var $name = 'Doctors';
public $uses = array('Doctor');
function changeprofilephoto() {
$doctor_id = “14”; //
$path = "../../app/webroot/profilepic/";//set path
$valid_formats = array(".jpg", ".png", ".gif", ".bmp", ".jpeg");//
if($this->data)
{
$this->Doctor->set( $this->data );
$name = $this->data["Doctor"]['profile_pic']['name'];
$size = $this->data["Doctor"]['profile_pic']['size'];
if(strlen($name))
{
$fileExt = substr(strrchr($name, '.'), 0);
if(in_array($fileExt,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = strtotime(date('Y-m-d H:i:s')).$fileExt;
$tmp = $this->data["Doctor"]['profile_pic']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$this->Doctor->set($this->data);
$this->Doctor->id=$doctor_id;
$this->Doctor->saveField('uploadfoldername',$actual_image_name);
echo "<img src='/profilepic/".$actual_image_name."' class='preview'>";
$this->Session->write('suc','1');
$this->redirect($_SERVER['HTTP_REFERER']);
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
} else
echo "Please select image..!";
exit;
}
}
} 



  1. views/changeprofilephoto.ctp


<?php
echo $this->Html->script('jquery.min.js');
echo $this->Html->script('jquery.form.js');
?>

<script type="text/javascript" >
$(document).ready(function() {
$('#profile_pic').live('change', function(){
$("#preview").html('');
$("#preview").html('<img src="../img/loader.gif" alt="Uploading...."/>');//download loding image
$("#Doctor").ajaxForm({
target: '#preview'
}).submit();
});
});
</script>
<style>
.preview
{
width:200px;
border:solid 1px #dedede;
padding:10px;
}
#preview
{
color:#cc0000;
font-size:12px
}
</style>
<div class="layout-popup f-left">
<?php
echo $this->Form->create('Doctor',array('id'=>'Doctor', 'controller'=>'Doctors','action'=>'changeprofilephoto', 'type'=>'file'));
?>

<!-- <form id="Doctors" name='Doctors' method="post" enctype="multipart/form-data" action='/Doctors/changeprofilephoto'> -->

<!-- start id-form -->
<table class="frm-tbl" id="id-form" >
<tr>
<td colspan="2" class="align-t-r" >
<div class="f-left popup-title">Change doctor profile image</div>
</td>
</tr>
<tr>
<td>Upload your image</td>
<td align="left" >
<!-- <input type="file" name="[Doctors][photoimg]" id="profile_pic" /> -->
<?php echo $form->file('profile_pic', array('id'=>'profile_pic', "label" => false, "div"=>false, 'class'=>'styled-input-big'))?>
</td>
</tr>
<tr>
<td colspan="2">
<div id='preview'>
</div>
</td>
</tr>
</table>
<?php
echo $this->Form->end();
?>
</div>

Sunday, 29 July 2012

How to create paging and shorting in cake php


1. Controller/controllername.php
class ControllerNameController extends AppController {

var $name = 'ControllerName';
public $uses = array('TablesName');


function inbox() {
$this->paginate = array(
'conditions' => array('TablesName.receiver_delete'=>'0', 'AND'=>array('TablesName.user_to'=>$parameters ['id'])),'limit' => 10,'order' => array('TablesName.sent_date'=>'desc'
)
);
$data = $this->paginate('TablesName');
$this->set('messages', $data);
}


  1. views/elements/paging.ctp
    <?php
echo "<div align='left' class='l1'>".
$this->Paginator->counter(array('format' => 'Showing %page% to %pages% of %count% entries' )).
"</div><div align='right' class='r1'>".
$this->Paginator->first('First', null, null, array('class' => 'disabled'))."&nbsp;&nbsp;&nbsp;".
$this->Paginator->prev('« Prev', null, null, array('class' => 'disabled'))."&nbsp;&nbsp;".
$this->Paginator->numbers()."&nbsp;&nbsp;".
$this->Paginator->next('Next »', null, null, array('class' => 'disabled'))."&nbsp;&nbsp;".
$this->Paginator->last('Last', null, null, array('class' => 'disabled'))."".
"</div>";
?>

  1. views/paging vies file

<table width="100%" style="border: 1px solid #ccc;" border='0'>
<?php
if (!empty($messages)) {
echo "<tr>";
echo "<td colspan=\"5\" align=\"right\">". $this->element('paging')."</td>";
echo "</tr>";
echo "<tr style=\"background-color: #55699F;\">";
echo "<td><font color=white>S.No</font></td>";
echo "<td><font color=white>".$this->Paginator->sort('From', 'user_from')."</font></td>";
echo "<td><font color=white>".$this->Paginator->sort('Title', 'subject')."</font></td>";
echo "<td><font color=white>".$this->Paginator->sort('Date & Time', 'sent_date')."</font></td>";
echo "<td><font color=white>Action</font></td>";
echo "<tr>";
foreach ($messages as $message) {?>
<tr class="<?php echo ($message['Message']['status']=='Un-read')? 'unread':'read'?>">
<td><?php echo $message['Message']['id'] ?></td>
<td onclick="read('<?php echo base64_encode($message['Message']['id'])?>/inbox')" style="width: 200px"><?php echo $message['user_from']['email']?></td>
<td onclick="read('<?php echo base64_encode($message['Message']['id'])?>/inbox')" style="width: 500px"><?php echo $message['Message']['subject']?></td>
<td onclick="read('<?php echo base64_encode($message['Message']['id'])?>/inbox')" style="width: 130px"><?php echo $message['Message']['sent_date']?></td>
<td style="width: 40px"><a onclick="return confirm('Do you really want to delete this message?');" href="delete/<?php echo base64_encode($message['Message']['id']);?>/inbox">Delete</a></td>
</tr>
<?php
}
echo "<tr>";
echo "<td style=\"height:20px\"></td>";
echo "</tr>";
echo "<tr>";
echo "<td colspan=\"5\" align=\"right\">". $this->element('paging')."</td>";
echo "</tr>";
} else {?>
<tr >
<td colspan="5">Ther are no messages in inbox.</td>
</tr>
<?php
}
?>
</table>

Monday, 23 July 2012

Upload file/image without refresh page with the help of ajax and validate extension.

file upload with progress bar
jquery upload file with progress bar


Step 1.
<html>
<head>
<title>Image upload without refresh page</title>
</head>
<script type="text/javascript" src="scripts/jquery.min.js"></script>//search this file on google
<script type="text/javascript" src="scripts/jquery.form.js"></script> //search this file on google
<script type="text/javascript" >
$(document).ready(function() {
$('#photoimg').live('change', function(){
$("#preview").html('');
$("#preview").html('<img src="loader.gif" alt="Uploading...."/>'); //download load loading image 
$("#imageform").ajaxForm({
target: '#preview'
}).submit();
});
});
</script>
<style>
body
{
font-family:arial;
}
.preview
{
width:200px;
border:solid 1px #dedede;
padding:10px;
}
#preview
{
color:#cc0000;
font-size:12px
}
</style>
<body>
<div style="width:600px">
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload your image <input type="file" name="photoimg" id="photoimg" />
<br>
<input type="text" id='tt' name='tt'>
</form>
<div id='preview'>
</div>
</div>
</body>
</html>

Step 2. 

<?php
$path = "img/"; // set image upload path

$valid_formats = array(".jpg", ".png", ".gif", ".bmp"); // set formate
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
//echo $name = $_POST['tt'];//use to image description. and you can do also save in database.
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
$fileExt = substr(strrchr($name, '.'), 0);
if(in_array($fileExt,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext; // create image unique name
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
// you can fire query for insert image discription or more fields whoes you create in form.
echo "<img src='img/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>


Thursday, 12 July 2012

A simple code to export data to excel using PHP and cake php

While generating a report in your project, you might have to download the data into excel file using PHP. In most scenario, you have to display the report in a page and create a link to download the report in the excel file. Well in that scenario, i think i can help you with a simplified code of PHP and cakephp.


Core Php

<?php
    $filename ="excelreport.xls";
    $contents = "Name\t Email \t Mobile \t \n";
$contents.= "Jafar Khan\t jafarkhanphp@gmail.com \t 9451293997 \t \n";
$contents.= "Jafar Khan\t jafarkhanphp@gmail.com \t 9451293997 \t \n";
$contents.= "Jafar Khan\t jafarkhanphp@gmail.com \t 9451293997 \t \n";
    header('Content-type: application/ms-excel'); /// you can set csv format
    header('Content-Disposition: attachment; filename='.$filename);
    echo $contents;
    ?>

Cake php Code 
Past this code on controller
controlpanel_controller.php

class ControlpanelController extends AppController {
var $name="Controlpanel";
var $layout=false;

function file_export()
{
              $this->autoRender=false;
ini_set('max_execution_time', 1600); //increase max_execution_time to 10 min if data set is very large
$results = $this->ModelName->find('all', array());// set the query function
 foreach($results as $result)
{
$header_row.= $result['Doctor']['fname']."\t". $result['Doctor']['lname'] ."\t ".$result['User']['email']." \t \n";

}
$filename = "export_".date("Y.m.d").".xls";
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename="'.$filename.'"');
echo($header_row);
}

}



Monday, 18 June 2012

Mail Function with Attachments in php

Mail Function with Attachments in php
<?php
function mailWithAttachments($fileName, $filepath, $mailto, $fromMail, $fromName, $replyTo, $subject, $message) {
    $file = $filepath.$fileName;
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));
    $uid = md5(uniqid(time()));//for unique number generate
    $name = basename($file);
    $header = "From: ".$from_name." <".$fromMail.">\r\n";
    $header .= "Reply-To: ".$replyTo."\r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
    $header .= "This is a multi-part message.\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $header .= $message."\r\n\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-Type: application/octet-stream; name=\"".$fileName."\"\r\n"; // you can also use different content types here
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"".$fileName."\"\r\n\r\n";
    $header .= $content."\r\n\r\n";
    $header .= "--".$uid."--";
    if (mail($mailto, $subject, "", $header)) {
        echo "mail send ... OK"; // 
    } else {
        echo "mail send ... ERROR!";
    }
}
?>

How can use this function.

$my_file = "demo.zip";
$my_path = $_SERVER['DOCUMENT_ROOT']."/your_path_here/";
$my_name = "jafar khan";
$my_mail = "jafarkhanphp@gmail.com";
$my_replyto = "jafarkhanphp@gmail.com";
$my_subject = "Mail with attachment.";
$my_message = "Hallo this is testing";
mail_attachment($my_file, $my_path, "jafar_14jan@yahoo.com", $my_mail, $my_name, $my_replyto, $my_subject, $my_message); 

Wednesday, 23 May 2012

Custom Right Click menu on web


Some time clients requirement that when I right click then open delete option and particular div delete

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
.vmenu {
border:1px solid #aaa;
position:absolute;
background:#fff;
display:none;
font-size:0.75em;
}
.vmenu .first_li span {
width:100px;
display:block;
padding:5px 10px;
cursor:pointer
}
.vmenu .inner_li {
display:none;
margin-left:120px;
position:absolute;
border:1px solid #aaa;
border-left:1px solid #ccc;
margin-top:-28px;
background:#fff;
}
.vmenu .sep_li {
border-top: 1px ridge #aaa;
margin:5px 0
}
.vmenu .fill_title {
font-size:11px;
font-weight:bold;
/height:15px;
/overflow:hidden;
word-wrap:break
}
;
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
$('.toolTip').bind('contextmenu',function(e){
var $cmenu = $(this).next();
$('<div class="overlay"></div>').css({left : '0px', top : '0px',position: 'absolute', width:                                                   '100%', height: '100%', zIndex: '100' }).click(function() {
$(this).remove();
$cmenu.hide();
}).bind('contextmenu' , function(){return false;}).appendTo(document.body);
$(this).next().css({ left: e.pageX, top: e.pageY, zIndex: '101' }).show();

return false;
});

$('.vmenu .first_li').live('click',function() {
if( $(this).children().size() == 1 ) {
//alert('Delete Event');
console.log(this.id);
var aa = this.id;
var ttt=$('#tt'+aa).text();
alert(ttt);
$('.vmenu').hide();
$('.overlay').hide();
}
});

/*$('.vmenu .inner_li span').live('click',function() {
alert($(this).text());
$('.vmenu').hide();
$('.overlay').hide();
});*/

$(".first_li , .sec_li, .inner_li span").hover(function () {
$(this).css({backgroundColor : '#E0EDFE' , cursor : 'pointer'});
if ( $(this).children().size() >0 )
$(this).find('.inner_li').show();
$(this).css({cursor : 'default'});
}, 
function () {
$(this).css('background-color' , '#fff' );
$(this).find('.inner_li').hide();
});


});
////////////////////////////////
</script>
</head>

<body>
<div class="toolTip" style="width:200px; height:50px; border:1px solid #F00">
          <div id="tt12">jafar</div>
        </div>
<div class="vmenu">
          <div class="first_li" id="12"><span>Delete</span></div>
        </div>
<br />
<div  class="toolTip" style="width:200px; height:50px; border:1px solid #F00">
          <div id="tt13">jafar1</div>
        </div>
<div class="vmenu">
          <div class="first_li" id="13"><span>Delete</span></div>
        </div>
<br />
<div  class="toolTip" style="width:200px; height:50px; border:1px solid #F00">
          <div>jafar khan</div>
          <div id="tt14" style="display:none">other Data</div>
        </div>
</div>
<div class="vmenu">
          <div class="first_li" id="14"><span>Delete</span></div>
        </div>
</div>
</body>
</html>