Friday, 22 March 2013

Improving web performance with Apache and htaccess


Compress content

Compression reduces response times by reducing the size of the HTTP response.
It’s worthwhile to gzip your HTML documents, scripts and stylesheets. In fact, it’s worthwhile to compress any text response including XML and JSON.
Image and PDF files should not be gzipped because they are already compressed. Trying to gzip them not only wastes CPU but can potentially increase file sizes.
To compress your content, Apache 2 comes bundled with the mod_deflate module.
The mod_deflate module provides the DEFLATE output filter that allows output from your server to be compressed before being sent to the client over the network.
Enable gzip compression for text responses:


# BEGIN Compress text files
<ifModule mod_deflate.c>
  AddOutputFilterByType DEFLATE text/html text/xml text/css text/plain
  AddOutputFilterByType DEFLATE image/svg+xml application/xhtml+xml application/xml
  AddOutputFilterByType DEFLATE application/rdf+xml application/rss+xml application/atom+xml
  AddOutputFilterByType DEFLATE text/javascript application/javascript application/x-javascript application/json
  AddOutputFilterByType DEFLATE application/x-font-ttf application/x-font-otf
  AddOutputFilterByType DEFLATE font/truetype font/opentype
</ifModule>
# END Compress text files



Enable browser cache

Web page designs are getting richer and richer over time, which means more scripts, stylesheets and images in the page. A first-time visitor to your page will make several HTTP requests to download all your sites files, but by using the Expires and Cache-Control headers you make those files cacheable. This avoids unnecessary HTTP requests on subsequent page views.
Apache enables those headers thanks to mod_expires and mod_headers modules.
The mod_expires module controls the setting of the Expires HTTP header and the max-age directive of the Cache-Control HTTP header in server responses.
To modify Cache-Control directives other than max-age, you can use the mod_headers module.
The mod_headers module provides directives to control and modify HTTP request and response headers. Headers can be merged, replaced or removed.





# BEGIN Expire headers
<ifModule mod_expires.c>
  ExpiresActive On
  ExpiresDefault "access plus 5 seconds"
  ExpiresByType image/x-icon "access plus 2592000 seconds"
  ExpiresByType image/jpeg "access plus 2592000 seconds"
  ExpiresByType image/png "access plus 2592000 seconds"
  ExpiresByType image/gif "access plus 2592000 seconds"
  ExpiresByType application/x-shockwave-flash "access plus 2592000 seconds"
  ExpiresByType text/css "access plus 604800 seconds"
  ExpiresByType text/javascript "access plus 216000 seconds"
  ExpiresByType application/javascript "access plus 216000 seconds"
  ExpiresByType application/x-javascript "access plus 216000 seconds"
  ExpiresByType text/html "access plus 600 seconds"
  ExpiresByType application/xhtml+xml "access plus 600 seconds"
</ifModule>
# END Expire headers








# BEGIN Cache-Control Headers
<ifModule mod_headers.c>
  <filesMatch "\.(ico|jpe?g|png|gif|swf)$">
    Header set Cache-Control "public"
  </filesMatch>
  <filesMatch "\.(css)$">
    Header set Cache-Control "public"
  </filesMatch>
  <filesMatch "\.(js)$">
    Header set Cache-Control "private"
  </filesMatch>
  <filesMatch "\.(x?html?|php)$">
    Header set Cache-Control "private, must-revalidate"
  </filesMatch>
</ifModule>
# END Cache-Control Headers


Disable HTTP ETag header

ETags were added to provide a mechanism for validating entities that is more flexible than the last-modified date.
The problem with ETags is that they typically are constructed using attributes that make them unique to a specific server hosting a site.
ETags won’t match when a browser gets the original component from one server and later tries to validate that component on a different server.
In Apache, this is done by simply adding the FileETag directive to your configuration file:


# BEGIN Turn ETags Off
FileETag None
# END Turn ETags Off

Tuesday, 5 February 2013

Back button. Page expired problem

On IE when user hits back button they get the classic IE "webpage has expired" message.

I have found that setting the following in my php.ini has solved this.
 
'session.cache_limiter=private'

or

You can try this. working for all browser

ini_set("session.cache_limiter", "must-revalidate");

This might help you out...

Tuesday, 29 January 2013

Cache problem when downloading file with same name


If you want to be 100% sure that files you update frequently, always show changes made to them right away... use cache busting. You may even have a member site that you allow members to change their files on. If so they may not see updated changes right away unless you cache bust some files. If you are not able to use PHP to cache bust, you can do the same thing using Javascript.

Browser Cache

Browser caching is used to speed up internet browsing by storing files so people do not re-download files they have already downloaded. If you make a change to a file and somebody has the old version cached for that file name, they will not see your new changes in that file.

A user on the internet has a browser in which they use to surf the web. Under normal browser settings while surfing their browser will cache (store) the files from your web site as they browse. Meaning that if they go to your homepage and they see 5 pictures or a flash file, those files get cached so the next time they come to your homepage those elements do not have to re-download to display. They are served up from the user's browser cache if they are detected there.

Cache Busting Files

Cache Busting a file is when we add a random string or number to the end of a URL that we have defined on our pages or in our code. You should not Cache Bust every single page and file on your web site, just the ones you are going to make frequent changes on and you would like for people to always see the most recent design or version of a file.

On any file of your site that you always want the newest version of an image or any file to show, you can append a random number to the end of the URL... this way it has to download new to the user's browser cache... always showing newest file.Examples of Cache Busting Popular File Types Using PHP

Simply put a question mark [ ? ] and then a random number or string on the end of your URLs to those files

Cache Bust an image file

myPicture.jpg?<?php echo rand(); ?>
Cache Bust a Style Sheet

myStyle.css?<?php echo rand(); ?>
Cache Bust an SWF file

myFlash.swf?<?php echo rand(); ?>
Cache Bust an MP3 file

mySong.mp3?<?php echo rand(); ?>
Cache Bust a Style Sheet

myWholePage.html?<?php echo rand(); ?>

Thursday, 22 November 2012

Extract zip images and Upload

<?php

$supload = isset($_POST["supload"]) ? $_POST["supload"] : "";

if($supload != ""){
    $dir = "upload/"; //The folder to store your images
    $fileName = $_FILES['sfile']['name']; //get the file name
    $fileSize = $_FILES['sfile']['size']; //get the size
    $fileError = $_FILES['sfile']['error']; //get the error code
    if($fileSize > 0 || $fileError == 0){ //check if the file is corrupt or error
        //$fname = $dir.$fileName;
        $zip = zip_open($_FILES['sfile']['tmp_name']);
        if(is_resource($zip)){
            do_upload($dir,$_FILES['sfile']['tmp_name']);
        }
    }else{
        echo "error! ".$fileSize." ".$fileError;
    }
}

function do_upload($dir,$path){
    $allowed_type = array("jpeg","jpg","gif","png","bmp","pjpeg");
    $zip = new ZipArchive;
    if ($zip->open($path) === true) {
        for($i = 0; $i < $zip->numFiles; $i++) {
            $filename = $zip->getNameIndex($i);

            //Get file informatin eg: filename, file extension, etc..
            $fileinfo = pathinfo($filename);
            $fname = $dir.$fileinfo['basename'];

            //Only proceed if it has an extension
            if(isset($fileinfo['extension'])){
                //Check if the file extension is an image file
                if(in_array($fileinfo['extension'],$allowed_type)){
                    //Now extract the file
                    if(copy("zip://".$path."#".$filename, $fname)){
                        echo "File ".$filename." uploaded. ";
                        //Create new filename for thumbnail
                        $newfilename = "th_".$fileinfo['basename'];

                        //Second check, To get the real MIME type
                        $imgInfo = getimagesize($fname);
                        echo "File Type: ".$imgInfo['mime']."<br />";
                        if(checkFileType($imgInfo['mime'])){
                            //Now resize the image
                            resize($fname, $dir.$newfilename);
                        }
                    }
                }else{
                    echo $filename." is not an image!<br />";
                }
            }
        }
        $zip->close();
        return true;
    }
}

function checkFileType($file){
    $imgType = array(
            "Gif"=>"image/gif",
            "JPG" => "image/jpg",
            "JPEG" => "image/jpeg",
            "PJPEG" => "image/pjpeg",
            "PNG" => "image/png",
            "BMP" => "image/bmp");
    if(in_array($file,$imgType))
            return true;
    else return false;
}

function resize($img, $newfilename) {
    //Check if GD extension is loaded
    if (!extension_loaded('gd') && !extension_loaded('gd2')) {
        trigger_error("GD is not loaded", E_USER_WARNING);
        return false;
    }
    $w = 100;
    $h = 100;

    //Get Image size info
    $imgInfo = getimagesize($img);
    switch ($imgInfo[2]) {
        case 1: $im = imagecreatefromgif($img); break;
        case 2: $im = imagecreatefromjpeg($img);  break;
        case 3: $im = imagecreatefrompng($img); break;
        default:  trigger_error('Unsupported filetype!', E_USER_WARNING);  break;
    }

    //If image dimension is smaller, do not resize
    if ($imgInfo[0] <= $w && $imgInfo[1] <= $h) {
        $nHeight = $imgInfo[1];
        $nWidth = $imgInfo[0];
    }else{
        //resize it, but keep it proportional
        if ($w/$imgInfo[0] > $h/$imgInfo[1]) {
            $nWidth = $w;
            $nHeight = $imgInfo[1]*($w/$imgInfo[0]);
            }else{
            $nWidth = $imgInfo[0]*($h/$imgInfo[1]);
            $nHeight = $h;
        }
    }
    $nWidth = round($nWidth);
    $nHeight = round($nHeight);

    $newImg = imagecreatetruecolor($nWidth, $nHeight);

    /* Check if this image is PNG or GIF, then set if Transparent*/
    if(($imgInfo[2] == 1) OR ($imgInfo[2]==3)){
        imagealphablending($newImg, false);
        imagesavealpha($newImg,true);
        $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
        imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
    }
    imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);

    //Generate the file, and rename it to $newfilename
    switch ($imgInfo[2]) {
        case 1: imagegif($newImg,$newfilename); break;
        case 2: imagejpeg($newImg,$newfilename);  break;
        case 3: imagepng($newImg,$newfilename); break;
        default:  trigger_error('Failed resize image!', E_USER_WARNING);  break;
    }

    return $newfilename;
}
?>
<form name="fsupload" action="" method="post" enctype="multipart/form-data">
    <div>
    Add Image: <input type="file" name="sfile" id="sfile" />
    <input type="submit" name="supload" value="Upload" />
    </div>
</form>

Thursday, 1 November 2012

Add google language translate bar to your site

Put this script in your head part 

<script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en',includedLanguages: 'en,de,es,fr,it,pt,ar,ja,ko,zh',  layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>



put this div where  you want to show language dropdown

<div id="google_translate_element"  class="languate-dropdown"></div>


 last...for hinding google translator bar from the top of your page
put this code in you css

.goog-te-banner-frame.skiptranslate {display: none !important;}
body { top: 0px !important; }


woiiiiiiiiiiiillaa....done...

Tuesday, 23 October 2012

cron it manually

<?php


$con = mysql_connect('localhost','root','');
if(!$con)
{
die("Error in database connection");
}
$sdb=mysql_select_db('mysite',$con);
if(!$sdb)
{
die("Erroe in database selection");
}
$select=mysql_query("select * from task order by id desc limit 1");
while($row=mysql_fetch_array($select)){$last_date=strtotime($row['last_run']);}



echo strtotime(date("d-m-y"))."</br>";
$today=date("d");
echo "todays date : ".date("d")."<br>";
$expiry = "23";
$date=strtotime(date('d-m-y'));
$d=date('d-m-y');
echo "last date".$last_date;

if($today==$expiry && $date!=$last_date){ echo "Code is executed";
$insert="insert into task (last_run,status)values('".$d."','1')";
$result=mysql_query($insert);



}
else{echo "this code will be executed after sometime and the last run is :".$last_date;}


?>

Saturday, 11 August 2012

GENERATE PASSWORDS

<?php
function generatePassword ($length = 7)
  {

    // start with a blank password
    $password = "";

  
    $possible = "234678951abcdefghijklmnopqrstuvqxyz";

    // we refer to the length of $possible a few times, so let's grab it now
    $maxlength = strlen($possible);
 
    // check for length overflow and truncate if necessary
    if ($length > $maxlength) {
      $length = $maxlength;
    }
   
    // set up a counter for how many characters are in the password so far
    $i = 0;
   
    // add random characters to $password until $length is reached
    while ($i < $length) {

      // pick a random character from the possible ones
      $char = substr($possible, mt_rand(0, $maxlength-1), 1);
       
      // have we already used this character in $password?
      if (!strstr($password, $char)) {
        // no, so it's OK to add it onto the end of whatever we've already got...
        $password .= $char;
        // ... and increase the counter by one
        $i++;
      }

    }

    // done!
    return $password;

  }
 
$pwd=generatePassword();
if(isset($_REQUEST['submit']))
{
   
    $gen=$_REQUEST['gen'];
    for($i=0;$i<$gen;$i++)
    {
        echo $pwd=generatePassword()."<br>";
    }
}


?>
<form name="form" method="get" action="">

<input type="text" name="gen" value="" >
<input type="submit" name="submit">
</form>