Tuesday, 18 September 2012

Cropping an Image with PHP and the GD Library

Learn how to use the PHP GD library in your PHP program to generate dynamic images. Learn how to create and manipulate the GIF, PNG and JPG images.



<?php
# Note: Install GD laibreries 
$filename = '194_card.jpg';//orignal file 
$filename1 = '1.png';//save file name whoes you save 

list($current_width, $current_height) = getimagesize($filename);
$left = 0; //crop left margin
$top = 0;//crop right margin
$crop_width = 1056; 
$crop_height = 400;
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
imagejpeg($canvas, $filename1, 100);
?>

Sunday, 16 September 2012

Saving An Image Retrieved Via cURL


How can save images without use of browser with the help of Curl.
Some time we need save url image help of code without open browser
This function save image without open link.
$url="http://google.com/imagename.jpg";                                                                          
$ch = curl_init($url);
$fp = fopen(‘folderpath/card1.jpg', 'wb');// folder path where you save image
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

Note : One of the main reasons to use cURL to save or display a remote image is that some servers/hosts have allow_url_fopen turned off. This means functions like fopen can’t open files held on external servers.
I hope you have enjoyed this tutorial

Saturday, 18 August 2012

How can import excel file data in mysql with the help of php.


How can import excel file data in mysql with the help of php.

To import excel data into php-mysql records first create a table with required fields. Make database connection. Open excel file and read columns one by one and store in variables.

First Method******************* import excel data to php code****************/
$handle = fopen("Book1.csv", "r");
while (($data = fgetcsv($handle)) !== FALSE) {
$num = count($data);
$row;
echo "INSERT into importing(text,number)values('$data[0]','$data[1]')";
echo "<br>";
}
/************************************************************************/
 /***Second Method************ import excel data to php code and mysql***************/
$handle = fopen("Book1.csv", "r");
$fields=array('category','datatype','date','value');
$table='test';
$sql_query = "INSERT INTO $table(". implode(',',$fields) .") VALUES(";
while (($data = fgetcsv($handle)) !== FALSE) {
    foreach($data as $key=>$value) {
            $data[$key] = "'" . addslashes($value) . "'";
        }
           $rows[] = implode(",",$data);
  }
$sql_query .= implode("),(", $rows);
 $sql_query .= ")";
  echo $sql_query;

/****************************************************************************/
 /***Third Method*********** import excel data to php code and mysql****************/
require_once 'Excel/reader.php'; // http://code.google.com/p/php-excel-reader/downloads/list
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('CP1251');
$data->read('Book1.xls');
for ($x = 2; $x<=count($data->sheets[0]["cells"]); $x++) {
    $name = $data->sheets[0]["cells"][$x][1];
    $extension = $data->sheets[0]["cells"][$x][2];
    $email = $data->sheets[0]["cells"][$x][3];
    $sql = "INSERT INTO mytable (name,extension,email) VALUES ('$name',$extension,'$email')";
    echo $sql."\n";
    echo "<br>";
 }

/*****************************************************************************/

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);
}

}