Thursday, 20 March 2014

Using MEMCACHE for caching PHP Website for increasing Website Speed

In the case of  Large dynamic websites, it may become slower for some pages where it has to fetch large data from the database. So Solution in PHP is using the PHP cache methods.
Their are many cache tools available for php sites. Some of them are:-


  • APC 
  • Xcache
  • Memcache
  • E Accelerator .etc.
In this Post I will explain how to use memcache & its basic functions. I know that their are many vast tutorials explaining this but am just trying to figure out basic functions for new programmers.
Try to install memcache in your windows or linux or Mac by any methods. Iam not covering the installation process here.So I hope that your memcache is installed in your system & you are ready for the magic.


Many common processes utilized in web application development (for example generating large amounts of HTML or fetching data via complex SQL queries) are processor and disk intensive. Serializing and caching the generated data to disk solves the first of those problems, but you still get a small performance hit each time you read the data to disk, plus you have to write routines to automatically purge old cached data. 
Memcached solves this problem for you by letting you write frequently accessed data directly to RAM, where it can be fetched almost instantaneously; plus you can tell memcached how long to store the cached data and it will automatically purge stale data without any further intervention from you, the programmer. 
Many web sites & applications such as Facebook, LiveJournal, Flickr, Slashdot, WikiPedia/MediaWiki, SourceForge, Digg and Twitter use memcached to enhance their performance. 

What is Memcached? 
Memcached (Memory Cache Daemon) was developed by the team at LiveJournal to improve performance of their social blogging site by minimizing the impact of the bottleneck caused by reading data directly from the database. Memcached is a server that caches Name Value Pairs in memory. The “Name”, or key, is limited to 250 characters, and the “Value” is limited to 1MB in size. Values can consist of data, HTML 
Fragments, or binary objects; almost any type of data that can be serialized and fits in memcached can be stored.

Drawbacks/Limitations to Memcached 
• Memcached is not a persistent data storage mechanism. The data cannot be 
queried SQL-style or dumped to disk; the only way to access the information in Memcached is retrieve the data from the server via the correct key (or “Name”) for the information stored. There is no fail-over/high availability support; if a memcached server goes down or the service is restarted, the data is gone. 
• In many cases there is much less RAM available than disk space, so the amount of 
memory you can dedicate to memcached is more than likely fairly limited. 
• Things like resource variables (file handles, etc.) and internal PHP classes cannot 
be stored using memcached, because they cannot be serialized.


Initializing memcache


PHP provides both procedural and object-oriented interfaces to memcached. My 
examples will use the object-oriented interface. If you're interested in using the 
procedural interface, consult the PHP manual (http://www.php.net/memcache). 
We'll assume that our memcached instance is listening on localhost on port 12345. 
 $cache = new Memcache(); 
$cache->connect('localhost', 12345);

Before you start storing data, you'll want to make sure that you actually were able to 
connect to the memcached instance. 
 if ($cache->getServerStatus() == 0) die('Could not connect to 
 memcached!'); 

In memcache you have the power to add more than one server, so we can add server by:-

$cache->addServer('mem1.domain.com'1121133);$cache->addServer('mem2.domain.com'1121167);

Or Adding servers using an array

$servers = array(
    array(
'mem1.domain.com'1121133),
    array(
'mem2.domain.com'1121167)
);
$cache->addServers($servers);

But in this case if we didn't check before adding The same server may appear multiple times in the server pool, because no duplication checks are made. This is not advisable; instead, use the weight option to increase the selection weighting of this server.

So we can code something Like this :-
$server=$cache->getServerList();


foreach ($servers as $server) 
       if($server['host'] == $host and $server['port'] == $port) //checking whether server already added
               //already exist
//code here 
                } 
But Since we are talking about only one server our previous connect method is enough.


Flush all cache data

You may also at some point want to flush the cache without restarting the service: 
 $cache->flush();


Storing Data 
The next step is to actually store some data in the memcached instance. Each bit of data you store will be identified by a unique "key." You'll need to be sure that you don't use the same key to store two different bits of data; if you do, the second bit will overwrite the first, as you might expect. 
 $mydata = array( 
'user_id' => 1234,
 'fullname' => 'John Doe',
 'phone' => '(123) 234-3456' 
); 
$cache->set('my-memcached-key', $mydata, MEMCACHED_COMPRESSED, 
 1500); 
$cache->set('uncompressed-data', 'Just a string ...', null, 0); 
Now you've stored the contents of $mydata in the cache! 
The third and fourth options in the set() method specify whether or not to compress the cached data using zlib (use null for no compression) and how long in milliseconds to keep the cached data (use 0 for no expiration) respectively. Remember that setting no expiration date doesn't mean that the data will be cached forever ... if memcached runs out of memory it will start to remove old data, even data with no expiration date. 

Retreiving and Replacing Data

Retrieving cached data is very straightforward; you do need to remember to let 
memcached know if the data you are fetching was compressed. 
 echo $cache->get('my-memcached-key', MEMCACHED_COMPRESSED); 
echo $cache->get('uncompressed-data'); 
If you want to replace cached data, you've got two options. First, you can use the 
Memcache::replace() function, which will return false and not store your data if the 
cache key does not exist, or you can use Memcache::set(), which will replace the data if 
it exists, and store the value if it does not exist. 
 $cache->replace('uncompressed-data', 'New Value', null, 1500); 
or $cache->set('uncompressed-data', 'New Value', null, 1500); 

But In my opinion using set is more secure than using replace.

Deleting data

Deleting data is also straightforward ... 
 $cache->delete('my-memcached-key');


Incrementing and Decrementing Numeric Values 
Memcached also provides the Memcache::increment() and Memcache::decrement() 
methods for increasing or decresing the value of cached numeric values by a certain 
value. These funtions will NOT create the value if it does not exist, though. 
 $cache->set('connection-count', 1, null, 60000); $cache->increment('connection-count', 1); 
$cache->decrement('connection-count', 1); 

To append data to a variable

For adding data to a already existing cache method,we can use append method.
For eg: if we set variable name like:-

$cache->set('varname',$data);
$cache->append('varname',$moredate);


Sample Usage of memcache

$cache=new Memcache();
$cache->connect('localhost',1235);
$ip=$cache->get('data');
if(!$ip){
if($cache->getResultCode()==Memcached:RES_NOTFOUND){
$data_db=getdata();// fetch data from db
$cache->set('data',$data_db);

}
}else{
$ip=$cache->get('data');
echo $ip;

}


Wednesday, 19 March 2014

Using PDO in MYSQL PHP project

PDO stands for PHP data Objects.PDO is a PHP extension to formalise PHP's database connections by creating a uniform interface. This allows developers to create code which is portable across many databases and platforms.
PDO supports many of the popular databases as seen on the list below.

  • DBLIB: FreeTDS / Microsoft SQL Server / Sybase
  • Firebird (http://firebird.sourceforge.net/): Firebird/Interbase 6
  • IBM (IBM DB2)
  • INFORMIX - IBM Informix Dynamic Server
  • MYSQL (http://www.mysql.com/): MySQL 3.x/4.0
  • OCI (http://www.oracle.com): Oracle Call Interface
  • ODBC: ODBC v3 (IBM DB2 and unixODBC)
  • PGSQL (http://www.postgresql.org/): PostgreSQL
  • SQLITE (http://sqlite.org/): SQLite 3.x
In this Tutorial I will explain about PDO and its usage in MYSQL.

1. Connection with database

<?php
/*** mysql hostname ***/$hostname 'localhost';

$dbname
= 'mytable';/*** mysql username ***/$username 'username';
/*** mysql password ***/$password 'password';

try {
    
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname"$username$password);
    
/*** echo a message saying we have connected ***/
    
echo 'Connected to database';
    }
catch(
PDOException $e)
    {
    echo 
$e->getMessage();
    }
?>


2. For Closing database connection
Just set the connection variable to null

 $dbh null;


3. For Executing Query statements like INSERT,UPDATE,DELETE

<?php  
//Insert query  
$query="INSERT INTO tablename(fieldname, fieldname) VALUES ('value1', 'value2')";
//Update query
$query="UPDATE tablename set fieldname='value' where condition";
//Delete query
$query="DELETE FROM table where condition;

 $dbh->exec($query);

    
/*** echo the number of affected rows ***/
?>


4. Executing query statements like SELECT

/*** The SQL SELECT statement ***/
    
$sql "SELECT * FROM animals";
    foreach (
$dbh->query($sql) as $row)
        {
        print 
$row['value1'] .' - '$row['value2'] . '<br />';
        }



FETCH Modes


  • FETCH ASSOC



To fetch an associative array from our results the constant PDO::FETCH_ASSOC is used and returns the column names as indexes or keys of the resulting array

$sql "SELECT * FROM tablename";

    
/*** fetch into an PDOStatement object ***/
    
$stmt $dbh->query($sql);

    
/*** echo number of columns ***/
    
$result $stmt->fetch(PDO::FETCH_ASSOC);

    
/*** loop over the object directly ***/
    
foreach($result as $key=>$val)
    {
    echo 
$key.' - '.$val.'<br />';
    }



  • FETCH NUM



Like PDO::FETCH_ASSOC, the PDO::FETCH_NUM produces a numerical index of the result set rather than the field names.


/*** The SQL SELECT statement ***/
    
$sql "SELECT * FROM tablename";

    
/*** fetch into an PDOStatement object ***/
    
$stmt $dbh->query($sql);

    
/*** echo number of columns ***/
    
$result $stmt->fetch(PDO::FETCH_NUM);

    
/*** loop over the object directly ***/
    
foreach($result as $key=>$val)
    {
    echo 
$key.' - '.$val.'<br />';
    }



  • FETCH BOTH



There may be times you need to fetch both numerical and associative indexes. PDO::FETCH_BOTH produces a numerical and associative index of the result set so you can use either, or both.


/*** The SQL SELECT statement ***/
    
$sql "SELECT * FROM tablename";

    
/*** fetch into an PDOStatement object ***/
    
$stmt $dbh->query($sql);

    
/*** echo number of columns ***/
    
$result $stmt->fetch(PDO::FETCH_BOTH);

    
/*** loop over the object directly ***/
    
foreach($result as $key=>$val)
    {
    echo 
$key.' - '.$val.'<br />';
    }


5. For getting last insert Id


    $dbh->exec("INSERT INTO tablename(fieldname,fieldname) VALUES ('value1', 'value2')");

    
/*** display the id of the last INSERT ***/
    
echo $dbh->lastInsertId();


I have covered only basic things about PDO. Hope that this post is helpful to some people...

Speed Up your Website by Enabling Browser cache

When you create a website,the main success factor of that website would be its speed. But however we tried to increase a website speed it takes some default time to load a page. Here am trying to explain about 
Browser caching.
Before moving to the tricks,I will explain what is browser caching?? and what is the significance of it??
When a web browser displays your webpage it has to load several things like your logo, your CSS file, and other resources.

What browser caching does is "remember" the resources that the browser has already loaded. This means that when a visitor goes to another page on your website it does not have to go get your logo or CSS file again, because it already has it "remembered". The end result of this is that your pages load much faster.

If you have tested your webpage for speed and found out that you need to use browser caching, here is how you do it.

To acheive this you have to write something in your htaccess file.
Open your htaccess files and add lines below:-

</IfModule>

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType text/css "access plus 1 year"
ExpiresByType text/js "access plus 1 year"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>

Here You can set its expire period too.
Change the period you want after access plus . For eg: access plus 1 month, access plus 1 week, access plus 1 year are vaild statements.

Save your htaccess file and refresh the page. 


Monday, 17 March 2014

Generating Picture Thumbnails in Virtual domains

During my Previous project, I got a situation where I have to generate thumbnail images in a virtual subdomain. Many thumbnail function we use will fail to work when it is used in virtual subdomains.
I didn't want to confuse you with my techie language. Let me explain with an eg:-
Consider a project of blogger, Where users can create their own user urls. Like litto.blogger.com, kevin.blogger.com. etc. Actually these subdomain urls are not created anywhere whereas it is redirected to a particular code or folder via htaccess. and it will continue executing from their. but the url remains the same. This is known as virtual url & virtual subdomain.
So when we want to display images in these domains we have to give absolute urls. Like Normally in php websites we give image url like ../upload/imagename.png. But Here we have to give url like http://sitename.com/upload/imagename.png.

So When we use normal thumbnail script for this images it will show error & will not generate. So In thsi situation what we can do is:-
1) During page reloading download the image to domain s local folder as thumbnails and show this images.

So here I tried it and I suceeded in it.
If you want it you can also gave it a try.


First step :- 1)Function to resize image & download it to local server
Name it as resize_image.php & include it in your server

<?php
/**
 * easy image resize function
 * @param  $file - file name to resize
 * @param  $width - new image width
 * @param  $height - new image height
 * @param  $proportional - keep image proportional, default is no
 * @param  $output - name of the new file (include path if needed)
 * @param  $delete_original - if true the original image will be deleted
 * @param  $use_linux_commands - if set to true will use "rm" to delete the image, if false will use PHP unlink
 * @param  $quality - enter 1-100 (100 is best quality) default is 100
 * @return boolean|resource
 */
  function smart_resize_image($file,
                              $width              = 0,
                              $height             = 0,
                              $proportional       = false,
                              $output             = 'file',
                              $delete_original    = true,
                              $use_linux_commands = false,
                                $quality = 100
           ) {
     
    if ( $height <= 0 && $width <= 0 ) return false;

    # Setting defaults and meta
    $info                         = getimagesize($file);
    $image                        = '';
    $final_width                  = 0;
    $final_height                 = 0;
    list($width_old, $height_old) = $info;
    $cropHeight = $cropWidth = 0;

    # Calculating proportionality
    if ($proportional) {
      if      ($width  == 0)  $factor = $height/$height_old;
      elseif  ($height == 0)  $factor = $width/$width_old;
      else                    $factor = min( $width / $width_old, $height / $height_old );

      $final_width  = round( $width_old * $factor );
      $final_height = round( $height_old * $factor );
    }
    else {
      $final_width = ( $width <= 0 ) ? $width_old : $width;
      $final_height = ( $height <= 0 ) ? $height_old : $height;
      $widthX = $width_old / $width;
      $heightX = $height_old / $height;
     
      $x = min($widthX, $heightX);
      $cropWidth = ($width_old - $width * $x) / 2;
      $cropHeight = ($height_old - $height * $x) / 2;
    }

    # Loading image to memory according to type
    switch ( $info[2] ) {
      case IMAGETYPE_JPEG:  $image = imagecreatefromjpeg($file);  break;
      case IMAGETYPE_GIF:   $image = imagecreatefromgif($file);   break;
      case IMAGETYPE_PNG:   $image = imagecreatefrompng($file);   break;
      default: return false;
    }
   
   
    # This is the resizing/resampling/transparency-preserving magic
    $image_resized = imagecreatetruecolor( $final_width, $final_height );
    if ( ($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG) ) {
      $transparency = imagecolortransparent($image);
      $palletsize = imagecolorstotal($image);

      if ($transparency >= 0 && $transparency < $palletsize) {
        $transparent_color  = imagecolorsforindex($image, $transparency);
        $transparency       = imagecolorallocate($image_resized, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
        imagefill($image_resized, 0, 0, $transparency);
        imagecolortransparent($image_resized, $transparency);
      }
      elseif ($info[2] == IMAGETYPE_PNG) {
        imagealphablending($image_resized, false);
        $color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
        imagefill($image_resized, 0, 0, $color);
        imagesavealpha($image_resized, true);
      }
    }
    imagecopyresampled($image_resized, $image, 0, 0, $cropWidth, $cropHeight, $final_width, $final_height, $width_old - 2 * $cropWidth, $height_old - 2 * $cropHeight);
   
   
    # Taking care of original, if needed
    if ( $delete_original ) {
      if ( $use_linux_commands ) exec('rm '.$file);
      else @unlink($file);
    }

    # Preparing a method of providing result
    switch ( strtolower($output) ) {
      case 'browser':
        $mime = image_type_to_mime_type($info[2]);
        header("Content-type: $mime");
        $output = NULL;
      break;
      case 'file':
        $output = $file;
      break;
      case 'return':
        return $image_resized;
      break;
      default:
      break;
    }
   
    # Writing image according to type to the output destination and image quality
    switch ( $info[2] ) {
      case IMAGETYPE_GIF:   imagegif($image_resized, $output);    break;
      case IMAGETYPE_JPEG:  imagejpeg($image_resized, $output, $quality);   break;
      case IMAGETYPE_PNG:
        $quality = 9 - (int)((0.9*$quality)/10.0);
        imagepng($image_resized, $output, $quality);
        break;
      default: return false;
    }

    return true;
  }
?>


Step 2: Include it in your file:-

<?php include("resize_image.php");          ?>


Step 3: Loop the images in file


<?php
      while($rows=mysql_fetch_array($sql_p))
      {
$loc=$rows['photo_loc'];
$filenameIn  = "http://yoursite.com/upload/".$loc; // Give the images actual url
$filenameOut = __DIR__ . '/images/' .$loc; // Give here where image to be downloaded  your virtual domain folder
$out="http://yoursite.com/user/template/adv001/images/".$loc;// Full path of image in virtual domain
//$contentOrFalseOnFailure   = file_get_contents($filenameIn);
//$byteCountOrFalseOnFailure = file_put_contents($filenameOut, $contentOrFalseOnFailure);
$file = $filenameIn ;

//indicate the path and name for the new resized file
$resizedFile = $filenameOut;

//call the function
smart_resize_image($file , 150 , 150 , false , $resizedFile , false , false ,100 );
      ?>
                      <li>  <img src="http://<?php echo $server_name; ?>/user/template/adv001/images/<?php echo $rows['photo_loc'];?>" alt="" width="150px" height="150px">  </li>
              
<?php } ?>

Wednesday, 5 March 2014

Uploading Multiple Files Via Ajax - Dropzone - A simple Plugin

In the case of web developers, their araise many situations where your clients asked you to make multiple files to upload & also that via Ajax. So their are many plugins available for it. But When Iam working on my previous project, I got a nice plugin to do it. It's name is Dropzone.

You Just need to download file from this site  http://www.dropzonejs.com/

I will explain step by step how to use it:-

 Your html file uploading form will look like this :-

            <div id="dropzone">
                                <form action="upload.php" class="dropzone">
                                    <div class="fallback">
                                        <input name="file" type="file" multiple="" />
                                    </div>
                                </form>
                            </div>

<script src="assets/js/dropzone.min.js"></script> 

Please download dropzone.min.js from its site , I have given its link earlier.

Now include this code below the page:-

<script type="text/javascript">
            jQuery(function($){
           
            try {
              $(".dropzone").dropzone({
                paramName: "file", // The name that will be used to transfer the file
                maxFilesize: 0.5, // MB
             
                addRemoveLinks : true,
                dictDefaultMessage :
                '<span class="bigger-150 bolder"><i class="icon-caret-right red"></i> Drop files</span> to upload \
                <span class="smaller-80 grey">(or click)</span> <br /> \
                <i class="upload-icon icon-cloud-upload blue icon-3x"></i>'
            ,
                dictResponseError: 'Error while uploading file!',
               
                //change the previewTemplate to use Bootstrap progress bars
                previewTemplate: "<div class=\"dz-preview dz-file-preview\">\n  <div class=\"dz-details\">\n    <div class=\"dz-filename\"><span data-dz-name></span></div>\n    <div class=\"dz-size\" data-dz-size></div>\n    <img data-dz-thumbnail />\n  </div>\n  <div class=\"progress progress-small progress-success progress-striped active\"><span class=\"bar\" data-dz-uploadprogress></span></div>\n  <div class=\"dz-success-mark\"><span></span></div>\n  <div class=\"dz-error-mark\"><span></span></div>\n  <div class=\"dz-error-message\"><span data-dz-errormessage></span></div>\n</div>"
              });
            } catch(e) {
              alert('Dropzone.js does not support older browsers!');
            }
           
            });
        </script>


This drop zone will work only in latest browsers. So Please make sure that You use updated browsers.

Then Next thing is that we have to create upload.php file, Which is given as the action for the file uploading form.


<?php

$ds          = DIRECTORY_SEPARATOR;  //1

$storeFolder = '../upload';   //2


if (!empty($_FILES)) {
$ext='';
  $photonam=$_FILES['file']['name'];
  $phot=explode('.',$photonam);
  $photoname=$phot[0];
$string=$photonam;
  $parts  = explode(".",$string);
       $ext   = strtolower($parts[count($parts)-1]);
       $savename="gal".substr(md5(rand(1111,9999)),0,8).".".$ext;
    
    $tempFile = $_FILES['file']['tmp_name'];          //3            
     
    $targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;  //4
    
    $targetFile =  $targetPath. $savename;  //5

    move_uploaded_file($tempFile,$targetFile); //6
}

?>

Now all files will be uploaded in your target folder.

Unzipping Files in Core PHP

In this Post Iam explaining about how to handle zip files in php. In many projects their araise situation where you want to upload zip file for eg: For a blogger like website you want to add large number of themes dynamically. Without this unzip function it will be practically difficult to upload folder containing themes.
In Php there is a library for handling this zip files. The name of  that Library is ZipArchive.
In Latest versions of PHP you didn't want to install anything for it,it comes default with PHP package.
So I will explain step by step How to acheive this:-

1) We want to have an html form for uploading zip files.so my html code goes here:-
<html>
<body>
<form class="form-horizontal" name="addproduct" method="post" enctype="multipart/form-data" action="addtemplate.php">
<div class="control-group">
                   
                                <div class="span5">    <label class="control-label" for="form-field-1">Template(Zip File)</label>

                                    <div class="controls">

                                        <input type="file" id="id-input-file-2" name="txtzipFile"/>
                                           
                                    </div></div>
                                </div>

        <div class="form-actions">
                                    <button class="btn btn-info" type="submit" name="submit">
                                        <i class="icon-ok bigger-110"></i>
                                        Submit
                                    </button></div>


</body>
</html>


Above is a form to upload a file. Its action is set to addtemplate.php. & File name is txtZipFile


2) In the action, we are going to do this :- upload the zip file to a location then From that location we will unzip our file and store it in another Location.
So here we go:-

<?php

if(isset($_POST['submit'])){


$name="somename";//demo name to be given to unzip folder

 $absDirNamezip =   dirname(dirname(__FILE__)).'/user/template'; //setting path to upload file

    $rnd=rand(100,999);
     $rnd=$rnd."_";
    $fileName = $rnd.trim($_FILES['files']['name']);//setting file name

$tmpname=$_FILES['files']['tmp_name'][$i];
$target=  $absDirNamezip.'/'.$fileName;
move_uploaded_file($tmpname,$target);//uploading file
$templateloc =$fileName;
            mkdir($absDirNamezip.'/'.$name);//making directory of demo name
            chmod($absDirNamezip.'/'.$name,0777);//giving permissions

        $file = $absDirNamezip.'/'.$templateloc;
  $fileloc=$absDirNamezip.'/'.$name;

// get the absolute path to $file
$path = pathinfo(realpath($file), PATHINFO_DIRNAME);

$zip = new ZipArchive;
$res = $zip->open($file);//opening zip file
if ($res === TRUE) {
  $zip->extractTo($fileloc);//extracting zip file
  $zip->close();
  echo 'Success';

} else {
  echo 'Failed!';

}
unlink($file);//deleting the zipped file uploaded 
}

?>
Now you have unzipped file in the folder you created.Just check it :-)
Have a Great day :-)