Thursday, 13 December 2012

Which one is the Best Loop Between (For, While, foreach).

That is always open to debate. Using the System.Diagnostics.Stopwatch class I ran some tests. 100,000 iterations in a for loop that did nothing inside took me 0.0003745 seconds. This was the code for the loop:

for (int i = 0; i < 100000; i++) ;
The while loop resulted 0.0003641 seconds, which is pretty much the same as the for loop. Here is the code
I used:

int i=0;
while (i < 100000)
        i++;
 
 The foreach loop has a slightly different purpose. It is meant for itterating through some collection that implements IEnumerable. It's performance is much slower, my test resulted in 0.0009076 seconds with this code:

int[] test = new int[100000];
foreach (int i in test) ;

Thursday, 22 November 2012

How to setup subdomains on localhost (WAMP)


Developing code locally on your computer has some major benefits over using a web server. For one, it’s usually faster as you don’t have to wait for your file changes to upload to the web.
I’ll be using WampServer, a program that lets you run a local web environment (Apache, PHP & MySQL)
You’ll need to download & install WampServer before continuing with this tutorial.
This tutorial assumes WAMP is installed under C:\wamp. You may change this path to reflect your own installation if it differs.

Step 1: Create the folder which will hold your subdomains

For example. Create the following folder:
C:\wamp\www\subdomains
Each folder contained within the subdomains folder will essentially become a subdomain. For example:
example.localhost.com will point to C:\wamp\www\subdomains\example\

Step 2: Make sure httpd-vhosts.conf file is included.


1) Open C:\wamp\bin\apache\Apache2.2.21\conf\httpd.conf (or choose Wampserver > Apache > httpd.conf)
2) Find the lines:

# Virtual hosts
# Include conf/extra/httpd-vhosts.conf

3) Change to:
# Virtual hosts
Include conf/extra/httpd-vhosts.conf

Step 3: Configuring Apache VirtualHosts

1) Enable the alias_module and vhost_alias_module for apache.




Doing this will enable virtualhost aliasing in apache for your subdomains.
2) Open C:\wamp\bin\apache\Apache2.2.21\conf\extra\httpd-vhosts.conf
3) In the httpd-vhosts.conf file, you’ll most likely see some example data.  Replace everything with the following:

NameVirtualHost *:80

<VirtualHost *:80>
    ServerName localhost.com
    ServerAlias www.localhost.com
    DocumentRoot "C:\wamp\www"
    ErrorLog "logs\errors.log"
    <directory "C:\wamp\www">
        Options Indexes FollowSymLinks
        AllowOverride all
        Order Deny,Allow
        Deny from all
        Allow from all
    </directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName localhost.com
    ServerAlias *.localhost.com
    VirtualDocumentRoot C:\wamp\www\subdomains\%1
    ErrorLog "logs\errors.log"
    <directory "C:\wamp\www\subdomains\%1">
        Options Indexes FollowSymLinks
        AllowOverride all
        Order Deny,Allow
        Deny from all
        Allow from all
    </directory>
</VirtualHost>

So what’s going on with the code above? Each <VirtualHost> tag contains a host definition.   The asterisk in <VirtualHost *:80> tells apache that any IP address can be used to access this host definition.  If you wanted to restrict it to just your computer, you could do <VirtualHost 127.0.0.1:80>
ServerName
ServerName localhost.com
The domain.  I use localhost.com. Just remember that whatever you choose to use will essential replace any real domains (EX: using google.com will not let you access the real google.com later)
ServerAlias
ServerAlias *.localhost.com
An alternate domain alias (usually www.localhost.com)
DocumentRoot
DocumentRoot "C:\wamp\www"
The absolute directory to your domain’s root (accessed by going to localhost.com)
ErrorLog Path to your error log.  This is optional.
ErrorLog "logs\errors.log"
VirtualDocumentRoot
VirtualDocumentRoot C:\wamp\www\subdomains\%1
The absolute directory for your subdomain, with a wildcard to define the subdomain’s name.  I use a wildcard %1 to get the name of the subdomain. example.localhost.com will point to C:\wamp\www\subdomains\example
<directory ________>
<directory "C:\wamp\www">
<directory "C:\wamp\www\subdomains\%1">
The directory permission definitions. Defined twice for both localhost.com and it’s virtual subdomains.
4) After making the changes to your httpd-vhosts.conf file, you must restart apache for the changes to take effect. Just click the WAMPSERVER icon in your Notification Area and choose “Restart All Services”.

Step 3: Updating Windows Host File

In order for you to access your localhost.com or example.localhost.com, you must first point these domains to your local IP address.  Windows unfortunately does not allow you to use a wildcard in the hosts file.  You will have to input each new subdomain into your hosts file for it to work in your browser.
1) Open C:\Windows\System32\drivers\etc\hosts using Notepad
2) Add a the following line to the bottom of your hosts file.

127.0.0.1       example.localhost.com

You have to do this for each domain & subdomain you wish to use. For example:
127.0.0.1       localhost.com
127.0.0.1       www.localhost.com
127.0.0.1       example.localhost.com
127.0.0.1       example2.localhost.com
127.0.0.1       mysubdomain.localhost.com

Test! Check if your subdomains work.

Open your browser and go to your local subdomain: example.localhost.com
Apache should now be serving files for that subdomain from C:\wamp\www\subdomains\example

Additionally: Custom Domain Definitions

If you ever wanted to create a custom domain definition that pointed to a folder outside of your “subdomains” folder, you can do that! Just open your httpd-vhosts.conf file (See step 2.2), and paste the following directly after NameVirtualHost *:80 and before the first instance of <VirtualHost *:80>.
This custom definition MUST be before your wildcard VirtualHost definition to work.

<VirtualHost *:80>
    ServerName mycustomlocaldomain.com
    ServerAlias www.mycustomlocaldomain.com
    DocumentRoot "C:\Documents\mycustomlocaldomain.com"
    ErrorLog "logs\errors.log"
    <directory "C:\Documents\mycustomlocaldomain.com">
        Options Indexes FollowSymLinks
        AllowOverride all
        Order Deny,Allow
        Deny from all
        Allow from all
    </directory>
</VirtualHost>
And how the httpd-vhosts.conf should finally look with this custom definition:
NameVirtualHost *:80

<VirtualHost *:80>
    ServerName mycustomlocaldomain.com
    ServerAlias www.mycustomlocaldomain.com
    DocumentRoot "C:\Documents\mycustomlocaldomain.com"
    ErrorLog "logs\errors.log"
    <directory "C:\Documents\mycustomlocaldomain.com">
        Options Indexes FollowSymLinks
        AllowOverride all
        Order Deny,Allow
        Deny from all
        Allow from all
    </directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName localhost.com
    ServerAlias www.localhost.com
    DocumentRoot "C:\wamp\www"
    ErrorLog "logs\errors.log"
    <directory "C:\wamp\www">
        Options Indexes FollowSymLinks
        AllowOverride all
        Order Deny,Allow
        Deny from all
        Allow from all
    </directory>
</VirtualHost>

<VirtualHost *:80>
    ServerName localhost.com
    ServerAlias *.localhost.com
    VirtualDocumentRoot C:\wamp\www\subdomains\%1
    ErrorLog "logs\errors.log"
    <directory "C:\wamp\www\subdomains\%1">
        Options Indexes FollowSymLinks
        AllowOverride all
        Order Deny,Allow
        Deny from all
        Allow from all
    </directory>
</VirtualHost>

Friday, 2 November 2012

Read Excle file ( .xlsx ) Using PHP

Read Excle file ( .xlsx ) Using PHP


<?php
// SimpleXLSX php class v0.4
// MS Excel 2007 workbooks reader
// Example:
   $xlsx = new SimpleXLSX('pizza hut-sample-ori.xlsx');
   echo '<pre>';print_r( $xlsx->rows() );
// Example 2:
//   $xlsx = new SimpleXLSX('book.xlsx');
//   print_r( $xlsx->rowsEx() );
// Example 3:
//   $xlsx = new SimpleXLSX('book.xlsx');
//   print_r( $xlsx->rows(2) ); // second worksheet
//
// 0.4 sheets(), sheetsCount(), unixstamp( $excelDateTime ), getWorksheetName() by SPYRO KiD - http://www.spyrozone.net
// 0.3 - fixed empty cells (Gonzo patch)

class SimpleXLSX {
 // Don't remove this string! Created by Sergey Schuchkin from http://www.sibvison.ru - professional php developers team 2010-2011
 private $sheets;
 private $hyperlinks;
 private $package;
 private $sharedstrings;
 // scheme
 const SCHEMA_OFFICEDOCUMENT  =  'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument';
 const SCHEMA_RELATIONSHIP  =  'http://schemas.openxmlformats.org/package/2006/relationships';
 const SCHEMA_SHAREDSTRINGS =  'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings';
 const SCHEMA_WORKSHEETRELATION =  'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet';

 function __construct( $filename ) {
 $this->_unzip( $filename );
 $this->_parse();
 }
 function sheets() {
 return $this->sheets;
 }
 function sheetsCount() {
 return count($this->sheets);
 }
 function worksheet( $worksheet_id ) {
 if ( isset( $this->sheets[ $worksheet_id ] ) ) {
 $ws = $this->sheets[ $worksheet_id ];

 if (isset($ws->hyperlinks)) {
 $this->hyperlinks = array();
 foreach( $ws->hyperlinks->hyperlink as $hyperlink ) {
 $this->hyperlinks[ (string) $hyperlink['ref'] ] = (string) $hyperlink['display'];
 }
 }

 return $ws;
 } else
 throw new Exception('Worksheet '.$worksheet_id.' not found.');
 }
 function dimension( $worksheet_id = 1 ) {
 $ws = $this->worksheet($worksheet_id);
 $ref = (string) $ws->dimension['ref'];
 $d = explode(':', $ref);
 $index = $this->_columnIndex( $d[1] );      
 return array( $index[0]+1, $index[1]+1);
 }
 // sheets numeration: 1,2,3....
 function rows( $worksheet_id = 1 ) {

 $ws = $this->worksheet( $worksheet_id);

 $rows = array();
 $curR = 0;

 foreach ($ws->sheetData->row as $row) {

 foreach ($row->c as $c) {
 list($curC,) = $this->_columnIndex((string) $c['r']);
 $rows[ $curR ][ $curC ] = $this->value($c);
 }

 $curR++;
 }
 return $rows;
 }
 function rowsEx( $worksheet_id = 1 ) {
 $rows = array();
 $curR = 0;
 if (($ws = $this->worksheet( $worksheet_id)) === false)
 return false;
 foreach ($ws->sheetData->row as $row) {

 foreach ($row->c as $c) {
 list($curC,) = $this->_columnIndex((string) $c['r']);
 $rows[ $curR ][ $curC ] = array(
 'name' => (string) $c['r'],
 'value' => $this->value($c),
 'href' => $this->href( $c ),
 );
 }
 $curR++;
 }
 return $rows;

 }
 // thx Gonzo
 function _columnIndex( $cell = 'A1' ) {

 if (preg_match("/([A-Z]+)(\d+)/", $cell, $matches)) {

 $col = $matches[1];
 $row = $matches[2];

 $colLen = strlen($col);
 $index = 0;

 for ($i = $colLen-1; $i >= 0; $i--)
 $index += (ord($col{$i}) - 64) * pow(26, $colLen-$i-1);

 return array($index-1, $row-1);
 } else
 throw new Exception("Invalid cell index.");
 }
 function value( $cell ) {
 // Determine data type
 $dataType = (string)$cell["t"];
 switch ($dataType) {
 case "s":
 // Value is a shared string
 if ((string)$cell->v != '') {
 $value = $this->sharedstrings[intval($cell->v)];
 } else {
 $value = '';
 }

 break;

 case "b":
 // Value is boolean
 $value = (string)$cell->v;
 if ($value == '0') {
 $value = false;
 } else if ($value == '1') {
 $value = true;
 } else {
 $value = (bool)$cell->v;
 }

 break;

 case "inlineStr":
 // Value is rich text inline
 $value = $this->_parseRichText($cell->is);

 break;

 case "e":
 // Value is an error message
 if ((string)$cell->v != '') {
 $value = (string)$cell->v;
 } else {
 $value = '';
 }

 break;

 default:
 // Value is a string
 $value = (string)$cell->v;

 // Check for numeric values
 if (is_numeric($value) && $dataType != 's') {
 if ($value == (int)$value) $value = (int)$value;
 elseif ($value == (float)$value) $value = (float)$value;
 elseif ($value == (double)$value) $value = (double)$value;
 }
 }
 return $value;
 }
 function href( $cell ) {
 return isset( $this->hyperlinks[ (string) $cell['r'] ] ) ? $this->hyperlinks[ (string) $cell['r'] ] : '';
 }
 function _unzip( $filename ) {
 // Clear current file
 $this->datasec = array();

 // Package information
 $this->package = array(
 'filename' => $filename,
 'mtime' => filemtime( $filename ),
 'size' => filesize( $filename ),
 'comment' => '',
 'entries' => array()
 );
 // Read file
 $oF = fopen($filename, 'rb');
 $vZ = fread($oF, $this->package['size']);
 fclose($oF);
 // Cut end of central directory
 $aE = explode("\x50\x4b\x05\x06", $vZ);

 // Normal way
 $aP = unpack('x16/v1CL', $aE[1]);
 $this->package['comment'] = substr($aE[1], 18, $aP['CL']);

 // Translates end of line from other operating systems
 $this->package['comment'] = strtr($this->package['comment'], array("\r\n" => "\n", "\r" => "\n"));

 // Cut the entries from the central directory
 $aE = explode("\x50\x4b\x01\x02", $vZ);
 // Explode to each part
 $aE = explode("\x50\x4b\x03\x04", $aE[0]);
 // Shift out spanning signature or empty entry
 array_shift($aE);

 // Loop through the entries
 foreach ($aE as $vZ) {
 $aI = array();
 $aI['E']  = 0;
 $aI['EM'] = '';
 // Retrieving local file header information
//            $aP = unpack('v1VN/v1GPF/v1CM/v1FT/v1FD/V1CRC/V1CS/V1UCS/v1FNL', $vZ);
 $aP = unpack('v1VN/v1GPF/v1CM/v1FT/v1FD/V1CRC/V1CS/V1UCS/v1FNL/v1EFL', $vZ);
 // Check if data is encrypted
//            $bE = ($aP['GPF'] && 0x0001) ? TRUE : FALSE;
 $bE = false;
 $nF = $aP['FNL'];
 $mF = $aP['EFL'];

 // Special case : value block after the compressed data
 if ($aP['GPF'] & 0x0008) {
 $aP1 = unpack('V1CRC/V1CS/V1UCS', substr($vZ, -12));

 $aP['CRC'] = $aP1['CRC'];
 $aP['CS']  = $aP1['CS'];
 $aP['UCS'] = $aP1['UCS'];

 $vZ = substr($vZ, 0, -12);
 }

 // Getting stored filename
 $aI['N'] = substr($vZ, 26, $nF);
 if (substr($aI['N'], -1) == '/') {
 // is a directory entry - will be skipped
 continue;
 }

 // Truncate full filename in path and filename
 $aI['P'] = dirname($aI['N']);
 $aI['P'] = $aI['P'] == '.' ? '' : $aI['P'];
 $aI['N'] = basename($aI['N']);

 $vZ = substr($vZ, 26 + $nF + $mF);

 if (strlen($vZ) != $aP['CS']) {
 $aI['E']  = 1;
 $aI['EM'] = 'Compressed size is not equal with the value in header information.';
 } else {
 if ($bE) {
 $aI['E']  = 5;
 $aI['EM'] = 'File is encrypted, which is not supported from this class.';
 } else {
 switch($aP['CM']) {
 case 0: // Stored
 // Here is nothing to do, the file ist flat.
 break;
 case 8: // Deflated
 $vZ = gzinflate($vZ);
 break;
 case 12: // BZIP2
 if (! extension_loaded('bz2')) {
 if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
 @dl('php_bz2.dll');
 } else {
 @dl('bz2.so');
 }
 }
 if (extension_loaded('bz2')) {
 $vZ = bzdecompress($vZ);
 } else {
 $aI['E']  = 7;
 $aI['EM'] = "PHP BZIP2 extension not available.";
 }
 break;
 default:
 $aI['E']  = 6;
 $aI['EM'] = "De-/Compression method {$aP['CM']} is not supported.";
 }
 if (! $aI['E']) {
 if ($vZ === FALSE) {
 $aI['E']  = 2;
 $aI['EM'] = 'Decompression of data failed.';
 } else {
 if (strlen($vZ) != $aP['UCS']) {
 $aI['E']  = 3;
 $aI['EM'] = 'Uncompressed size is not equal with the value in header information.';
 } else {
 if (crc32($vZ) != $aP['CRC']) {
 $aI['E']  = 4;
 $aI['EM'] = 'CRC32 checksum is not equal with the value in header information.';
 }
 }
 }
 }
 }
 }

 $aI['D'] = $vZ;

 // DOS to UNIX timestamp
 $aI['T'] = mktime(($aP['FT']  & 0xf800) >> 11,
 ($aP['FT']  & 0x07e0) >>  5,
 ($aP['FT']  & 0x001f) <<  1,
 ($aP['FD']  & 0x01e0) >>  5,
 ($aP['FD']  & 0x001f),
 (($aP['FD'] & 0xfe00) >>  9) + 1980);

 //$this->Entries[] = &new SimpleUnzipEntry($aI);
 $this->package['entries'][] = array(
 'data' => $aI['D'],
 'error' => $aI['E'],
 'error_msg' => $aI['EM'],
 'name' => $aI['N'],
 'path' => $aI['P'],
 'time' => $aI['T']
 );

 } // end for each entries
 }
 function getPackage() {
 return $this->package;
 }
 function getEntryData( $name ) {
 $dir = dirname( $name );
 $name = basename( $name );
 foreach( $this->package['entries'] as $entry)
 if ( $entry['path'] == $dir && $entry['name'] == $name)
 return $entry['data'];
 }
 function unixstamp( $excelDateTime ) {
 $d = floor( $excelDateTime ); // seconds since 1900
 $t = $excelDateTime - $d;
 return ($d > 0) ? ( $d - 25569 ) * 86400 + $t * 86400 : $t * 86400;
 }
 function _parse() {
 // Document data holders
 $this->sharedstrings = array();
 $this->sheets = array();

 // Read relations and search for officeDocument

 $relations = simplexml_load_string( $this->getEntryData("_rels/.rels") );
 foreach ($relations->Relationship as $rel) {
 if ($rel["Type"] == SimpleXLSX::SCHEMA_OFFICEDOCUMENT) {
 // Found office document! Read relations for workbook...
 $workbookRelations = simplexml_load_string($this->getEntryData( dirname($rel["Target"]) . "/_rels/" . basename($rel["Target"]) . ".rels") );
 $workbookRelations->registerXPathNamespace("rel", SimpleXLSX::SCHEMA_RELATIONSHIP);

 // Read shared strings
 $sharedStringsPath = $workbookRelations->xpath("rel:Relationship[@Type='" . SimpleXLSX::SCHEMA_SHAREDSTRINGS . "']");
 $sharedStringsPath = (string)$sharedStringsPath[0]['Target'];            
 $xmlStrings = simplexml_load_string($this->getEntryData( dirname($rel["Target"]) . "/" . $sharedStringsPath) ); 
 if (isset($xmlStrings) && isset($xmlStrings->si)) {
 foreach ($xmlStrings->si as $val) {
 if (isset($val->t)) {
 $this->sharedstrings[] = (string)$val->t;
 } elseif (isset($val->r)) {
 $this->sharedstrings[] = $this->_parseRichText($val);
 }
 }
 }

 // Loop relations for workbook and extract sheets...
 foreach ($workbookRelations->Relationship as $workbookRelation) {
 if ($workbookRelation["Type"] == SimpleXLSX::SCHEMA_WORKSHEETRELATION) {
 $this->sheets[ str_replace( 'rId', '', (string) $workbookRelation["Id"]) ] =
 simplexml_load_string( $this->getEntryData( dirname($rel["Target"]) . "/" . dirname($workbookRelation["Target"]) . "/" . basename($workbookRelation["Target"])) );
 }
 }

 break;
 }
 }

 // Sort sheets
 ksort($this->sheets);
 }
 private function _parseRichText($is = null) {
 $value = array();

 if (isset($is->t)) {
 $value[] = (string)$is->t;
 } else {
 foreach ($is->r as $run) {
 $value[] = (string)$run->t;
 }
 }

 return implode(' ', $value);
 }
 function getWorksheetName($dimId = 0){
 $worksheetName = array();
 $xmlWorkBook = simplexml_load_string( $this->getEntryData("xl/workbook.xml") );
 if($dimId==0){
 foreach ($xmlWorkBook->sheets->sheet as $sheetName) {
 $worksheetName[] = $sheetName['name'];
 }
 }else{
 $worksheetName[] = $xmlWorkBook->sheets->sheet[$dimId-1]->attributes()->name;
 }
 return $worksheetName;
 }
}
?>

Wednesday, 31 October 2012

Read Excel File or Sheet (.xls) with PHP


Read Excel File or Sheet (.xls) with PHP

Hi,

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. Click here to download the entire source code. I have used couple of external class files to achieve this.

Lets have a look at the spreadsheet I am using as example:

Code and Explanation:

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:


Best of luck. Download excel_reader.zip

Tuesday, 18 September 2012

How to Find and Replace Data in MySQL

How to Find and Replace Data in MySQL :

Replace .JPG(Capital Letter) to .jpg(Small Letter)

Syntax :

update [table_name] set [field_name] = replace([field_name],'[string_to_find]','[string_to_replace]');

Example :

update products_bk set product_first_image = replace(product_first_image,'.JPG','.jpg');

Friday, 27 July 2012

htaccess Redirect

How to redirect webpages

The .htaccess file is a small text document that generally sits in the same location as your index.php or index.htm pages. It gives you the ability to interact with Apache on an individual domain-to-domain and directory-to-directory basis.
You can place the htaccess file anywhere where you'd like to control the flow of visitors. So for instance you can protect directories and redirect the traffic visiting those pages. This page will show you how to use the .htaccess file to redirect your visitors in different ways. Note that this is a powerful system file, if the syntax is incorrect in anyway, it could render your site unusable. Always take a backup.

Redirect to another page

To redirect one page to another page:
Redirect /old-index.html http://www.mynewwebsite.com/foldername/new-index.html
 
 

Redirect to another website

To redirect an entire website from one url to another:
Redirect 301 / http://www.mynewwebsite.com
 
 

Redirect index to subdirectory

To redirect a page to a subdirectory:
Redirect /index.html http://www.mynewwebsite.com/foldername
 
 
 

Redirect filepaths

To redirect a filepath to another filepath:
Redirect /foldername/filename.html http://www.mynewwebsite.com/foldername2/filename.html
 
 
 

To change file extention

If you've changed your pages from .html to .php:
RedirectMatch 301 (.*)\.html$ http://www.example.com$1.php
 
 
 

Specifying folder default page

To change the default webpage loaded by the server:
DirectoryIndex index.php
 
 

Redirect www to non-www

To redirect http://www.mysite.com to http://mysite.com:
RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.mynewwebsite\.com$ [NC]

RewriteRule ^(.*)$ http://mynewwebsite.com/$1 [L,R=301]
 
 
 

Redirect non-www to www

To redirect http://mysite.com to http://www.mysite.com:
RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\.mynewwebsite\.com$ [NC]

RewriteRule ^(.*)$ http://www.mynewwebsite.com/$1 [L,R=301]
 
 

Give 307 'Site Under Maintenance' Header on all webpage requests

To return a 307 Site Under Maintenance header to those visiting the site. Create a temporary file called 307.php and inside it place the message to give to your visitors and upload it to your public root directory.
Next create a totally separate .htaccess file called .htaccess.307 with the following text:
RewriteEngine On

RewriteBase /

# Before using this htaccess, you have to change this digits to match your

# own IP address: This will keep you with access to the site. as long as

# your IP doesn't change: http://whatismyip.com



RewriteCond %{REMOTE_ADDR} !^123\.123\.123\.123$



# The last 2 lines take the site offline. the basically say if: page request is

# NOT 307.php, show 307.php but only once. Stops it from looping endlessly.

RewriteCond %{REQUEST_URI} !^/307\.php$



# The browser gets this bit, so you need the full website address.

RewriteRule ^(.*)$ http://www.yoursite.com/307.php [R=307,L]
The above includes comments for your convenience. To get the redirect up and running, rename your existing .htaccess file to live.htaccess then rename this one to .htaccess

Alternative Redirect 1: Meta Refresh

It's also possible to redirect traffic when visiting a page with the following line inside the head tag.
To do an immediate redirect:
<meta http-equiv="refresh" content="0; url=http://www.new-website.com" />
To redirect after 5 seconds:
<meta http-equiv="refresh" content="5; url=http://www.new-website.com" />
 
 

Alternative Redirect 2: PHP Header Redirect

You're able to redirect traffic by putting the following line at the very top of a php document (nothing can be above it).
          <?php
            header ('HTTP/1.1 301 Moved Permanently');
            header( "http://www.new-website.com" );
          ?>
 

Thursday, 19 July 2012

 Get all dates between two dates using php code


<?

$strDateFrom = '2009-01-05';
$strDateTo = '2009-01-10';
    // takes two dates formatted as YYYY-MM-DD and creates an
    // inclusive array of the dates between the from and to dates.

    // could test validity of dates here but I'm already doing
    // that in the main script

    $aryRange=array();

    $iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2),     substr($strDateFrom,8,2),substr($strDateFrom,0,4));
    $iDateTo=mktime(1,0,0,substr($strDateTo,5,2),     substr($strDateTo,8,2),substr($strDateTo,0,4));

    if ($iDateTo>=$iDateFrom)
    {
        array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry
        while ($iDateFrom<$iDateTo)
        {
            $iDateFrom+=86400; // add 24 hours
            array_push($aryRange,date('Y-m-d',$iDateFrom));
        }
    }
    echo '<pre>';
    print_r($aryRange);


?>

Friday, 13 July 2012



Set unsetattribute using javascript




Username :
Password :


<script>
function setattribute(action)
{
    var obju = document.getElementById('username');
    var objub = document.getElementById('uButton');
   
    var objp = document.getElementById('password');
    var objpb = document.getElementById('pButton');
   
    if(action=='Set Disable'){
        obju.setAttribute('disabled','disabled'); // you can set any attribute of any tags
        objub.setAttribute('onClick','setattribute("unSet Disable");');
        objub.setAttribute('value','click to Enable');
    }else if('unSet Disable'){
        obju.removeAttribute('disabled','disabled'); // you can set any attribute of any tags
        objub.setAttribute('onClick','setattribute("Set Disable");');
        objub.setAttribute('value','click to Disable');
    }
    if(action=='Set Style'){
        objp.setAttribute('style','background-color:#FF0000;'); // you can set any attribute of any tags
        objpb.setAttribute('onClick','setattribute("unSet Style");');
        objpb.setAttribute('value','click to unSet Style');
    }
    else if('unSet Style'){
        objp.removeAttribute('style','background-color:#FF0000;'); // you can set any attribute of any tags
        objpb.setAttribute('onClick','setattribute("Set Style");');
        objpb.setAttribute('value','click to Set Style');
    }
}
</script>
<form name="FormName" id="FormName">
Username : <input type="text" name="username" id="username"><br>

Password : <input type="password" name="password" id="password" ><br>

<input type="button" href="javascript:void(0);" onClick="setattribute('Set Disable');" value="click to Disable" id="uButton">

<input type="button" href="javascript:void(0);" onClick="setattribute('Set Style');" value="click to Set Style" id="pButton">
</form>

Thursday, 28 June 2012

Delete Duplicate Entry from Table Using ( Two Condition )


SELECT * FROM chat;
+----+----------+
| id | name     |
+----+----------+
| 1  | rajneesh |
| 2  | rajneesh |
| 3  | gautam   |
| 4  | rajneesh |
| 5  | gautam   |
| 6  | gautam   |
+----+----------+
 
DELETE A1 FROM chat A1, chat A2 WHERE A1.id > A2.id AND A1.name = A2.name

if you want to keep the row with the lowest id value OR

DELETE A1 FROM chat A1, chat A2 WHERE A1.id < A2.id AND A1.name = A2.name

if you want to keep the row with the highest id value.

Form Submits automatically after 5 seconds


Code:

<!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>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<SCRIPT LANGUAGE="JavaScript"><!--
setTimeout('document.test.submit()',5000);
//--></SCRIPT>

</head>

<body>
<form name="test" id="form1" method="post" action="http://www.php.net/search.php">
  <p>
    <input name="pattern" type="text" id="pattern" />
    <input name="show" type="hidden" id="show" value="quickref" />
  </p>
  <p><input type="submit" name="next" value="Next" />
&nbsp;  </p>
</form>
</body>
</html>

Tuesday, 26 June 2012


<?php
 
    $bithdayDate = '1987-01-24';
    $date = new DateTime($bithdayDate);
    $now = new DateTime();
    $interval = $now->diff($date);
    echo $interval->y;

?>

Wednesday, 20 June 2012

how to select only one particular field from model in zend framework

public function ParticularCol($whr,$group)

{

$select = $this->_db->select()

->from(array('tablename'), array('Col1','Col2')) // Required Change

->where($whr)

->group($group);//echo $select;die;

$result = $this->getAdapter()->fetchAll($select);

return $result;

}


Zend Framework SQL Joins Examples

You may have custom of using advanced queries. It often requires writing complex queries if you are working on enterprise, large scale web application(s).
The use of joins can never be ignored.
Zend Framework developers have done tremendous job by providing simple method for implementing joins.
Lets look some examples of different type of joins.
Before discussing joins lets consider we have two tables, “authors” and “books”.
These are associated with author_id.

1. Inner Join
The simplest query will be
$select = $this->_db->select()
                ->from('books',array('col1','col2'…..))
                ->joinInner('authors','books.id=authors.bks_id',array('col1','col3'…))
                ->where('where condition here')
                ->order('column name ASC/DESC');

2. Left Join
$select = $this->_db->select()
                ->from('books',array('col1','col2'…..))
                ->joinLeft('authors','books.id=authors.bks_id',array('col1','col3'…))
                ->where('where condition here')
                ->group('group by column name here')
                ->order('column name ASC/DESC');

3. Right Join
$select = $this->_db->select()
                ->from('books',array('col1','col2'…..))
                ->joinRight('authors','books.id=authors.bks_id',array('col1','col3'…))
                ->where('where condition here')
                ->group('group by column name here')
                ->order('column name ASC/DESC');

4. Full Join
$select = $this->_db->select()
                ->from('books',array('col1','col2'…..))
                ->joinFull('authors','books.id=authors.bks_id',array('col1','col3'…))
                ->where('where condition here')
                ->group('group by column name here')
                ->order('column name ASC/DESC');

5. Cross Join
$select = $this->_db->select()
                ->from('books',array('col1','col2'…..))
                ->joinFull('authors','books.id=authors.bks_id',array('col1','col3'…))
                ->where('where condition here')
                ->group('group by column name here')
                ->order('column name ASC/DESC');

Once you write these queries, you can fetch a single row or multiple rows as

$result = $this->getAdapter()->fetchRow($select);
$result = $this->getAdapter()->fetchAll($select);

The first statement fetch only one row, while the second statement fetch the entire dataset.

Monday, 18 June 2012

Delete duplicate entries/rows/values in mysql table in one query

How can you delete or remove duplicate entries from a mysql table, without having to use PHP logic etc ?

The query would be

CREATE TABLE MyNewTable AS SELECT * FROM MyOldTable WHERE 1 GROUP BY [COLUMN TO remove duplicates BY];
 
This would create a new table with name MyNewTable which will have unique values for the column specified in the query. Now we do not require the MyOldTable, hence can be removed, followed by a query that will rename the new table to the old table..

DROP TABLE MyOldTable;
RENAME TABLE MyNewTable TO MyOldTable;

Difference between InnoDB and MyISAM in MySQL

MyISAM and InnoDB are two most commonly used storage engines of MySQL database. However, MyISAM is the default storage engine chosen by MySQL database, when creating a new table. The major differences between these two storage engines are :
  • InnoDB supports transactions which is not supported by tables which use MyISAM storage engine.
  • InnoDB has row-level locking, relational integrity i.e. supports foreign keys, which is not possible in MyISAM.
  • InnoDB ‘s performance for high volume data cannot be beaten by any other storage engines available.
Tables created in MyISAM are known to have higher speed compared to tables in InnoDB. But since InnoDB supports volume, transactions, integrity it’s always a better option which you are dealing with a larger database. It is worth mentioning that a single database can have tables of different storage engines.

File structure

MyISAM stores each table on disk with three files whose names begin with same as table name. These files have different extensions to differentiate their purpose. A .frm files stores the table format, and a .MYD (MYData) file stores the data of the table. If the table has indexes then these are stored in the .MYI (MYIndex) files.
On the other hand, InnoDB tables and their indexes are stored in the tablespace, which consists of several files. That is why InnoDB tables can be very large and can store large volume of data. The InnoDB storage engine maintains its own buffer pool for caching data and indexes in main memory.

Check the engines being used for existing tables

So these are the main differences between these two engines. You can specify in the query that which engine is to be used while creating the table.
CREATE TABLE test name varchar(30) ENGINE = InnoDB;
Since MyISAM is the default engine assigned when creating a table, so you need not to specify it, if you are planning to use MyISAM. This rule holds good, if you have not changed anything in the configuration. To check the engines of already existing tables, use the following query. It will list all the existing tables which are present in the current database, with their engines specified.
show table status;
If you want to view the status of a particular table, then use the following query,
show table status where Name = ‘tablename’;

Thursday, 7 June 2012

Sending Email with attachment in Zend Framework

Note : You must remember add ( <form enctype="multipart/form-data" > ) in form tag.

<?php
require_once 'Zend/Mail.php' ; // include on header on Controller where you want use

$message='Report of last months log files Please keep in mind Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry"s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.' ;
//echo $message;die;

$subject = 'Subject of Email';

$config = array('auth' => 'login',
                'username' => 'Email Id', // To Be Required rajneeshgautam@hotmail.com
                'password' => 'xxxxxxx'); // To Be Required xxxxxxx

// SMTP must be change according to Mail Server

$transport = new Zend_Mail_Transport_Smtp('smtp.live.com', $config);

$mail = new Zend_Mail();
$mail->setType(Zend_Mime::MULTIPART_RELATED);
$mail->setBodyText($message);
$mail->setBodyHtml($message);
$mail->setFrom('rajneeshgautam@hotmail.com');
$mail->addTo('rajneeshgautam24@gmail.com');
$mail->setSubject($subject);
$fileContents = file_get_contents($_FILES['resume']['tmp_name']); // To Be Required Attachement File name
$at=$mail->createAttachment($fileContents);
$at->filename = $_FILES['resume']['name']; // To Be Required Attachement File name
$mail->send($transport);
$this->_redirect("index/index/msg/suc");
?>