Friday, 28 June 2013

Extracting data from Excel file using PHP

When we are doing large projects,their may arise situation like we have to import data to our database from Excel sheets. This is a basic requirement which is asked by all clients.
So here iam explaining how to extract data from an excel sheet simply using php.
If you need to do large data migration from an excel sheet to your MySQL database, the most conventional way is to convert the .xls or .xlsx files to simple CSV(comma seperated file) and read it using PHP file read function. However we can also read a .xls file without converting it to a csv file. We can even navigate through the various worksheets in a single file.

You can get source library from this link Dowload here

I will explain it with an example...

Iam converting the below excel sheet to php format :-


First we need to include the main class file in our PHP page and initialise an object for it as follows:

include 'reader.php';
$excel = new Spreadsheet_Excel_Reader();

Now we are loading the excel file using the above created object as:
$excel->read('sample.xls');

Now we navigate through the rows and columns of the first worksheet in the excel file and display it as a simple HTML table in the browser:

$x=1;
    while($x<=$excel->sheets[0]['numRows']) {
      echo "\t<tr>\n";
      $y=1;
      while($y<=$excel->sheets[0]['numCols']) {
        $cell = isset($excel->sheets[0]['cells'][$x][$y]) ? $excel->sheets[0]['cells'][$x][$y] : '';
        echo "\t\t<td>$cell</td>\n"; 
        $y++;
      } 
      echo "\t</tr>\n";
      $x++;
    }

In the above sheet[0] is used to read cells from the first work sheet, you can change it according to your needs. Now in sheets[0]['cells'], ['cells'] is a 2D array storing the data as shown in the above screen shot. After executing the entire source code, this is the output that is generated:

so code will be:-

1) download library file from the source i provided earlier..
2)the sample file would be like this:-

<html>
  <head>
    <style type="text/css">
    table {
    border-collapse: collapse;
    }        
    td {
    border: 1px solid black;
    padding: 0 0.5em;
    }        
    </style>
  </head>
  <body>
<?php
include 'reader.php';
    $excel = new Spreadsheet_Excel_Reader();
?>
Sheet 1:<br/><br/>
    <table>
    <?php
    $excel->read('record.xls');  
    $x=1;
    while($x<=$excel->sheets[0]['numRows']) {
      echo "\t<tr>\n";
      $y=1;
      while($y<=$excel->sheets[0]['numCols']) {
        $cell = isset($excel->sheets[0]['cells'][$x][$y]) ? $excel->sheets[0]['cells'][$x][$y] : '';
        echo "\t\t<td>$cell</td>\n";  
        $y++;
      }  
      echo "\t</tr>\n";
      $x++;
    }
    ?>    
    </table><br/>

    ?>    
    </table>


  </body>
</html>

Resolving "headers already send" warning in PHP

When I was learning PHP their were few things that had stumped me, I would usually take it hours to solve them if not days.
Today I am going to write about one such annoying problem that almost always comes in the way of PHP developers at least once.

Warning: Cannot modify header information – headers already sent by (output started at C:wampwwwaktesterror.php:2) in C:wampwwwaktesterror.php on line 4

Warning: session_start() [function.session-start]: Cannot send session cookie – headers already sent by (output started at C:wampwwwaktesterror.php:2) in C:wampwwwaktesterror.php on line 3

This is “header already sent” warning message, that we get whenever we try to redirect a user to some other page or location, when we try to set a cookie or if we try to start a session. Once we get this warning we know that page won’t redirect, session won’t start or cookie’s sent to user, So we can’t even ignore them.

Before we see the solutions to resolve this warning let’s see the source code of the error.php file that I used to generate this error.


<?php

session_start();
header("location:file.php");
?>

Please notice an empty line before “<?php”, this is the cause of errors in his page.


Why This Occurs??

This is requirement of the http protocol that header related information must be sent by the server before it can sent the content. When we try to send a header information after we have already sent some output to client, PHP responds by giving this warning.

The most common reasons are :-


  • An output is sent, either by normal HTML tags, blank lines in a file, or from PHP file itself(in my case this is the reason).
  • We read a file using include()/require() function, and that file may have empty spaces or he lines at the end, that will be sent as output.
  • Important thing to note is that output is sent before header information that you wanted to sent, and hence the warning.


How To Resolve??

This is really simple, just make sure their is no output sent before your call to header function. This might be a correct advice but this still does not help much.

What really needed is that we need to know where is the exact problem, that we can resolve.

Basically we have to make sure that no output is sent before call to any header related functions.

Some guideline that might help


  • Always start “<?php” at the first line and first column, in you php file.
  • Keep all you your session related function like session_start() at the start of file, just after “<?php”
  • If all you are writing is a php file then do not use “?>”, this can prevent empty space or lines from being included in the other files.
  •  use ob_start(); at begining of php file. This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.


If you have any doubts or you did not understand something leave a comment below, I will try to help you as time permits.

Thursday, 13 June 2013

Instant Search Implementation in a PHP site

Hope that everyone knows the word Instant search. If not then you would have certainly noticed the coming of suggestion keywords when you start typing something in google. In simple that process is called Instant search. You can also implement the same function in your website. here iam explaining how to make instant search function by fetching keywords directly from database. here iam using a jquery library, which i found to be very simple in merging with our code. below is the code.. Just copy & paste code..

Make sure that you have connected a databse and have a sample table `cms_instant` and with fields id, title.etc... So that you can customize above code in your other projects.

<?php
ob_start();
include("autoload.php");
$db   = new MySql();
$db->connect();
$in=new Instant();
$intdet=$in->getal();// fetching keyword from database
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>Instant search </title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css" />
  <script>// keywords for instant search
  $(function() {
    var availableTags = [
   <?php for($i=0;$i<count($intdet);$i++){    ?>
    <?php echo '"';  ?>
<?php echo $intdet[$i]['name']; ?>
 <?php echo '"';  ?>
  <?php echo ',';  ?>
    <?php } ?>
    ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  });
  </script>
</head>
<body>
<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags" />
</div>
</body>
</html>

Wednesday, 29 May 2013

Sending Mails with attachment in Php

In php, their may arise situations where you have to send mails with attachments. So here Iam explaining how  sending mail through php library called Phpmailer.

Download phpmailer lib file from here.

Now place the below code:-

-
$msg="Thank you for your interest in our products. Your order details is attached with this mail.";


require_once 'class.phpmailer.php';

//$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch

$admin="name";
$emailfrom=$adminemail;
$email_to=$receivermail;

$email =new PHPMailer(true);
$email->From      = $adminemail;
$email->FromName  = 'name';
$email->Subject   = 'your subject';
$email->Body      = $msg;
$email->AddAddress($orderdet[0]['email'] );

$file_to_attach = 'attachment.pdf';

$email->AddAttachment($file_to_attach, 'attachment.pdf' );

 $email->Send();


You can add any number of attachments by using code
$mail->AddAttachment('filepath');

Upload it on your server & check..................

Monday, 6 May 2013

Reading barcodes in Php


What is a bar code reader (scanner)???
Bar code reader is a hardware pluggable into computer that sends decoded bar code strings into computer. The trick is to know how to catch that received string. With PHP (and any other web programming language) the string will be placed into focused input HTML element in browser. Thus to catch received bar code string, following must be done:

just before reading the bar code, proper input element, such as INPUT TEXT FIELD must be focused (mouse cursor is inside of the input field).
once focused, start reading the code
when the code is recognized (bar code reader usually shortly beeps), it is send to the focused input field. By default, most of bar code readers will append extra special character to decoded bar code string called CRLF (ENTER). For example, if decoded bar code is "12345AB", then computer will receive "12345AB<ENTER>". Appended character <ENTER> (or <CRLF>) emulates pressing the key ENTER causing instant submission of the HTML form:


<form action="getbarcode.php" method="post">

    <input type="text" name="documentID" onmouseover="this.focus();">

</form>

The receiving form getbarcode.php is like:-



<?php
if(isset($_POST['documentID'])){

$barcode= htmlentities( $code ); 
}

?>

Here In $barcode variable, you will get the barcode value...


When choosing bar code reader, one should consider what types of bar codes will be read with it. Some bar codes allow only numbers, others will not have checksum, some bar codes are difficult to print with inkjet printers, some barcode readers have narrow reading pane and cannot read for example barcodes with length over 10 cm. Most of barcode readers support common barcodes, such as EAN8, EAN13, CODE 39, Interleaved 2/5, Code 128 etc.



Thursday, 11 April 2013

Watermarking an image with your logo using PHP


When You are developing a photo oriented websites,You have to make sure that each photos upload in your site must not be copied. Or atleast it should be copyrighted to You. may be there are many softwares available for removing water marks, But it will certainly prevent normal users from copying photos from your site.
  So here Iam explaining how to watermark an image using your own Logo.


<?php
// Load the stamp and the photo to apply the watermark to
$stamp = imagecreatefrompng('entekalyanamlogo.png');
$im = imagecreatefromjpeg('photo.jpg');

// Set the margins for the stamp and get the height/width of the stamp image
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);

// Copy the stamp image onto our photo using the margin offsets and the photo 
// width to calculate positioning of the stamp. 
imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));

// Output and free memory
header('Content-type: image/png');
imagepng($im);

?>


Watermarking an Image With Text using PHP


When You are developing a photo oriented websites,You have to make sure that each photos upload in your site must not be copied. Or atleast it should be copyrighted to You. may be there are many softwares available for removing water marks, But it will certainly prevent normal users from copying photos from your site.
  So here Iam explaining how to watermark an image using your company name or some other texts..


<?php
// Load the stamp and the photo to apply the watermark to
$im = imagecreatefromjpeg('photo.jpg');

// First we create our stamp image 
$stamp = imagecreatetruecolor(100, 70);
imagefilledrectangle($stamp, 0, 0, 99, 69, 0x0000FF);
imagefilledrectangle($stamp, 9, 9, 90, 60, 0xFFFFFF);
$im = imagecreatefromjpeg('photo.jpg');
imagestring($stamp, 5, 5, 20, 'companyname', 0x0000FF);//Here you can set needed text in place of company name
// first 5 is the font weight
//second 5 is X cordinate
//20 is the Y cordinate
imagestring($stamp, 3, 20, 40, '(c) 2013', 0x0000FF);

// Set the margins for the stamp and get the height/width of the stamp image
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);

// Merge the stamp onto our photo with an opacity of 50%
imagecopymerge($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp), 50);

// Save the image to file and free memory
imagepng($im, 'photo_stamp.png');
imagedestroy($im);

?>




You can also apply water mark by following function also:-



<?php
function watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile) { 
   list($width, $height) = getimagesize($SourceFile);
   $image_p = imagecreatetruecolor($width, $height);
   $image = imagecreatefromjpeg($SourceFile);
   imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height); 
   $black = imagecolorallocate($image_p, 0, 0, 0);
   $font = 'arial.ttf';
   $font_size = 10; 
   imagettftext($image_p, $font_size, 0, 10, 20, $black, $font, $WaterMarkText);
   if ($DestinationFile<>'') {
      imagejpeg ($image_p, $DestinationFile, 100); 
   } else {
      header('Content-Type: image/jpeg');
      imagejpeg($image_p, null, 100);
   };
   imagedestroy($image); 
   imagedestroy($image_p); 
};
?>
<?php
$SourceFile = 'photo.jpg';
$DestinationFile = 'image1-watermark.jpg'; 
$WaterMarkText = 'Copyright mycompany.com';
watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile);
?>

Friday, 22 March 2013

Developing a Word press site With Your own Theme

In this post Iam trying to explain how to bulid a wordpress site with your own theme.

For this first step is create your own theme outside wordpress with css, js,images etc and index.php like what you do in the usual php sites.

After that for Preparing it as a wordpress template you have to customize like this...


Put the below code on top of index.php file.


<?php
/**

 * @package packagename
 *
   Template Name: theme name
 *
 * @file           index.php
 * @author         Author name

 */
?>

For an advanced theme development you have to seperate headers, footers and sidebars... and call them in the theme altogether.

name the header file as header.php and include in Theme folder.
name footer file as footer.php and include in Theme folder
name sidebar file as sidebar.php and include in Theme folder.

In header.php

for including style sheets code like this:-

<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" />

If javascript is placed inside a js folder. Then call like this:-

<script src="<?php echo get_template_directory_uri(); ?>/js/jquery-1.7.2.min.js" type="text/javascript"></script>



Now in index.php  you have to call like this:-

<?php get_header(); ?>// for header
------------------------------------// content
------------------------------------------
--------------------------------------------
<?php get_sidebar(); ?>// sidebar

<?php get_footer(); ?>// calling footer

for eg:-

index.php looks like this:-

<?php
/**

 * @package Twenty_Eleven
 *
   Template Name: theme1
 *
 * @file           litto.php
 * @author         Manu

 */



?>
<?php get_header(); ?>

<div class="mid-box">
<div class="grid-left">
<h2>Tour Packages</h2>



<
</div><!--grid-left-->
<?php get_sidebar(); ?>


</div><!--mid-box-->




<?php get_footer(); ?>



Now your folder conatins


  • index.php
  • header.php
  • footer.php
  • sidebar.php
  • style.css
  • js folder// inside it js files
  • images folder
After this zip the folder. make sure that it cannot exceed the limit of max size of uploading.


After that upload zip file through Appearance>themes>addthemes>upload

If you are working in the local server just copy the unzipped folder in to the themes folder located inside the wp-content folder.

Now Inorder to get a first look at the design u created.. Just create a page in admin panel and select the theme as new uploaded theme. When you visit the user side you can see your theme there. But may be it's not complete, so we can make it dynamic by adding page listing code.


To list all the pages under a parent code like this:-

<?php
$page_id=29;
 query_posts(array('showposts' => 20, 'post_parent' => $page_id, 'post_type' => 'page')); 


?>
<?php while (have_posts()) { //loop datas

the_post(); 


?>

<?php the_title(); ?>//title

<?php the_content(); ?>//content

<a href="single.php?<?php the_id();  ?>//getting id's

   </a>
<?php } ?>



To list a single page, code like this:-

<?php
$page_id=$_GET['page_id'];// getting page id
?>

<?php  $page_data =get_page($page_id) ;//retreiving page data
?>


<?php 
echo $page_data->post_title;// getting title

?>
<?php 
echo $page_data->post_content;// getting content

?>


You can create as many theme files in that folder u have to just change the header and change the theme name as i explained before in this post...

And select that particular theme for particular pages.

for developing a contact form just download contactform 7 , which is the most frequently used contact form in wordpress.
Download it from Here
 http://wordpress.org/extend/plugins/contact-form-7/



  • Upload the entire contact-form-7 folder to the /wp-content/plugins/ directory.
  • Activate the plugin through the 'Plugins' menu in WordPress.
  • You will find 'Contact' menu in your WordPress admin panel.


After that add fields, or customize fields as required.

For adding captcha to ensure free spamming,

http://wordpress.org/extend/plugins/really-simple-captcha/

This is the mainly used captcha with contact form-7



  • Upload the entire really-simple-captcha folder to the /wp-content/plugins/ directory.
  • Activate the plugin through the 'Plugins' menu in WordPress.
  • FYI: There is no "control panel" for this plugin.

After that while adding fields in contact form add field named captcha.. and it will gave you a code to be placed in contact form.. do it...

Now in the user side place below code where you want to call the contact form like:-

<?php echo do_shortcode( '[contact-form-7 id="96" title="Contact form 1"]' ); ?>

For adding simple galleries to your website download http://wordpress.org/plugins/simple-gallery-odihost/
Upload the Easy Gallery plugin to your blog, Activate it.

How to add gallery to post or page:

Click the "Add New" link
Fill the gallery name, type of gallery and images
Copy the shortcode and paste it into your page or post.
like <?php echo do_shortcode( '[easygallery id=1]' ); ?>
.

Thus, you have created a small wordpress site of your own :-)



Sample Wordpress Site :-)

Wordpress is the most used Content mangement system by the web developers. It is very easy to develop a small website with the wordpress site , even if you don't know much about php coding.
The wordpress offers default themes for you and also you can develop wordpress site with your own theme. So Iam explaining here how to develop your wordpress site With your own Theme...

First you want to download wordpress code from the wordpress.org. Download the latest version.
Now unzip the file and copy it to the localhost server. If you are using linux machine make sure that You have given it enough permissions.

Now create a database of any name. Then go into the root directory of site, Here you came to see wp-config-sample.php. Change it's name to wp-config.php.

In that file Rename details as per your requirement :-)


define('DB_NAME', 'wordpress');

/** MySQL database username */
define('DB_USER', 'root');

/** MySQL database password */
define('DB_PASSWORD', 'root');

/** MySQL hostname */
define('DB_HOST', 'localhost');

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');

Now It's the time to intsall wordpress. In the browser navigate to http://localhost/wordpress.
For installing type http://localhost/wordpress/wp-admin/install.php
 and give corresponding username and password.

After installing you can access admin panel by http://localhost/wordpress/wp-admin/

and user side by http://localhost/wordpress/

Now you can see your user side with default theme from the wordpress.

Installing New Wordpress Themes

You can set new themes in wordpress by navigating in admin> Appearances>Themes>Add theme
You can download and add themes by searching new themes based on criteria and downloading zip file and installing it.

Adding Pages

You can add new pages by clicking on pages link in the menu and click on add page.

Here You can give title,content .etc... and while saving make sure that you have selected your desired theme for the page.Also for adding subpages for a page just select the parent page while saving. After doing this all click on the publish button, Your page will be saved. When You navigate to the userside you will able to see the added page.

Adding category's

For people looking to buil small blogs they have to create posts rather than pages. So Inorder to differentiate between posts you have to categorize posts.

In this adding category section add any name you wish as category, in the slug field give any recognizable name for it, If u have any description for category add in this field. After that click on the add new category button. Your category has been created.


Adding Posts

Just fill in fields title, content and select the category you like the post be under and click on publish your post will be published

Viewing Comments

If you are buliding your blogs with wordpress, may be users will comment under your post regarding their views about the post. You can mange this comments in the comment section in wordpress admin panel. You can delete unappropriate comments made to your posts





Above I have explained to bulid a wordpress basic site with default template. This may be useful for people Who are trying to bulid a blog or site with 2 or more pages without any difficult customizations or so on. 










Wednesday, 6 March 2013

Setting Default Browser in Linux


In the command line, type
 sudo update-alternatives --config x-www-browser
A list of installed browsers will be displayed with a different number next to each browser. Type the number corresponding to the browser of your choice and press enter.

Again type 
sudo update-alternatives --config x-www-browser
to see whether the change have been done......