Wednesday, 23 July 2014

jQuery validation for file type extension

jQuery validation for file type extension

<script type="text/javascript">
  $(function(){
    $('input#submit').click(function(){
      var file = $('input[type="file"]').val();
      var exts = ['doc','docx','rtf','odt'];
      // first check if file field has any value
      if ( file ) {
        // split file name at dot
        var get_ext = file.split('.');
        // reverse name to check extension
        get_ext = get_ext.reverse();
        // check file type is valid as given in 'exts' array
        if ( $.inArray ( get_ext[0].toLowerCase(), exts ) > -1 ){
          alert( 'Allowed extension!' );
        } else {
          alert( 'Invalid file!' );
        }
      }
    });
  });
</script>

Monday, 21 July 2014

Read xls or xlsx file using PHP

PHP XLSXReader Sample

<?php 
date_default_timezone_set('UTC');
require('XLSXReader.php');
$xlsx = new XLSXReader('Companies.xlsx');
$sheetNames = $xlsx->getSheetNames();

?>
<?php 
foreach($sheetNames as $sheetName) {
$sheet = $xlsx->getSheet($sheetName);
?>
<h3><?php echo escape($sheetName);?></h3>
<?php 
array2Table($sheet->getData());
}

?>
<?php 
$data = array_map(function($row) {
$converted = XLSXReader::toUnixTimeStamp($row[0]);
return array($row[0], $converted, date('c', $converted), $row[1]);
}, $xlsx->getSheetData('Dates'));
array_unshift($data, array('Excel Date', 'Unix Timestamp', 'Formatted Date', 'Data'));
array2Table($data);

function array2Table($data) {
echo '<table>';
foreach($data as $row) {
echo "<tr>";
foreach($row as $cell) {
echo "<td>" . escape($cell) . "</td>";
}
echo "</tr>";
}
echo '</table>';
}

function debug($data) {
echo '<pre>';
print_r($data);
echo '</pre>';
}

function escape($string) {
return htmlspecialchars($string, ENT_QUOTES);
}?>



<?php



class XLSXReader {
protected $sheets = array();
protected $sharedstrings = array();
protected $sheetInfo;
protected $zip;
public $config = array(
'removeTrailingRows' => true
);
// XML schemas
const SCHEMA_OFFICEDOCUMENT  =  'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument';
const SCHEMA_RELATIONSHIP  =  'http://schemas.openxmlformats.org/package/2006/relationships';
const SCHEMA_OFFICEDOCUMENT_RELATIONSHIP = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
const SCHEMA_SHAREDSTRINGS =  'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings';
const SCHEMA_WORKSHEETRELATION =  'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet';

public function __construct($filePath, $config = array()) {
$this->config = array_merge($this->config, $config);
$this->zip = new ZipArchive();
$status = $this->zip->open($filePath);
if($status === true) {
$this->parse();
} else {
throw new Exception("Failed to open $filePath with zip error code: $status");
}
}

// get a file from the zip
protected function getEntryData($name) {
$data = $this->zip->getFromName($name);
if($data === false) {
throw new Exception("File $name does not exist in the Excel file");
} else {
return $data;
}
}

// extract the shared string and the list of sheets
protected function parse() {
$sheets = array();
$relationshipsXML = simplexml_load_string($this->getEntryData("_rels/.rels"));
foreach($relationshipsXML->Relationship as $rel) {
if($rel['Type'] == self::SCHEMA_OFFICEDOCUMENT) {
$workbookDir = dirname($rel['Target']) . '/';
$workbookXML = simplexml_load_string($this->getEntryData($rel['Target']));
foreach($workbookXML->sheets->sheet as $sheet) {
$r = $sheet->attributes('r', true);
$sheets[(string)$r->id] = array(
'sheetId' => (int)$sheet['sheetId'],
'name' => (string)$sheet['name']
);
}
$workbookRelationsXML = simplexml_load_string($this->getEntryData($workbookDir . '_rels/' . basename($rel['Target']) . '.rels'));
foreach($workbookRelationsXML->Relationship as $wrel) {
switch($wrel['Type']) {
case self::SCHEMA_WORKSHEETRELATION:
$sheets[(string)$wrel['Id']]['path'] = $workbookDir . (string)$wrel['Target'];
break;
case self::SCHEMA_SHAREDSTRINGS:
$sharedStringsXML = simplexml_load_string($this->getEntryData($workbookDir . (string)$wrel['Target']));
foreach($sharedStringsXML->si as $val) {
if(isset($val->t)) {
$this->sharedStrings[] = (string)$val->t;
} elseif(isset($val->r)) {
$this->sharedStrings[] = XLSXWorksheet::parseRichText($val);
}
}
break;
}
}
}
}
$this->sheetInfo = array();
foreach($sheets as $rid=>$info) {
$this->sheetInfo[$info['name']] = array(
'sheetId' => $info['sheetId'],
'rid' => $rid,
'path' => $info['path']
);
}
}

// returns an array of sheet names, indexed by sheetId
public function getSheetNames() {
$res = array();
foreach($this->sheetInfo as $sheetName=>$info) {
$res[$info['sheetId']] = $sheetName;
}
return $res;
}

public function getSheetCount() {
return count($this->sheetInfo);
}

// instantiates a sheet object (if needed) and returns an array of its data
public function getSheetData($sheetNameOrId) {
$sheet = $this->getSheet($sheetNameOrId);
return $sheet->getData();
}

// instantiates a sheet object (if needed) and returns the sheet object
public function getSheet($sheet) {
if(is_numeric($sheet)) {
$sheet = $this->getSheetNameById($sheet);
} elseif(!is_string($sheet)) {
throw new Exception("Sheet must be a string or a sheet Id");
}
if(!array_key_exists($sheet, $this->sheets)) {
$this->sheets[$sheet] = new XLSXWorksheet($this->getSheetXML($sheet), $sheet, $this);

}
return $this->sheets[$sheet];
}

public function getSheetNameById($sheetId) {
foreach($this->sheetInfo as $sheetName=>$sheetInfo) {
if($sheetInfo['sheetId'] === $sheetId) {
return $sheetName;
}
}
throw new Exception("Sheet ID $sheetId does not exist in the Excel file");
}

protected function getSheetXML($name) {
return simplexml_load_string($this->getEntryData($this->sheetInfo[$name]['path']));
}

// converts an Excel date field (a number) to a unix timestamp (granularity: seconds)
public static function toUnixTimeStamp($excelDateTime) {
if(!is_numeric($excelDateTime)) {
return $excelDateTime;
}
$d = floor($excelDateTime); // seconds since 1900
$t = $excelDateTime - $d;
return ($d > 0) ? ( $d - 25569 ) * 86400 + $t * 86400 : $t * 86400;
}

}

class XLSXWorksheet {

protected $workbook;
public $sheetName;
protected $data;
public $colCount;
public $rowCount;
protected $config;

public function __construct($xml, $sheetName, XLSXReader $workbook) {
$this->config = $workbook->config;
$this->sheetName = $sheetName;
$this->workbook = $workbook;
$this->parse($xml);
}

// returns an array of the data from the sheet
public function getData() {
return $this->data;
}

protected function parse($xml) {
$this->parseDimensions($xml->dimension);
$this->parseData($xml->sheetData);
}

protected function parseDimensions($dimensions) {
$range = (string) $dimensions['ref'];
$cells = explode(':', $range);
$maxValues = $this->getColumnIndex($cells[1]);
$this->colCount = $maxValues[0] + 1;
$this->rowCount = $maxValues[1] + 1;
}

protected function parseData($sheetData) {
$rows = array();
$curR = 0;
$lastDataRow = -1;
foreach ($sheetData->row as $row) {
$rowNum = (int)$row['r'];
if($rowNum != ($curR + 1)) {
$missingRows = $rowNum - ($curR + 1);
for($i=0; $i < $missingRows; $i++) {
$rows[$curR] = array_pad(array(),$this->colCount,null);
$curR++;
}
}
$curC = 0;
$rowData = array();
foreach ($row->c as $c) {
list($cellIndex,) = $this->getColumnIndex((string) $c['r']);
if($cellIndex !== $curC) {
$missingCols = $cellIndex - $curC;
for($i=0;$i<$missingCols;$i++) {
$rowData[$curC] = null;
$curC++;
}
}
$val = $this->parseCellValue($c);
if(!is_null($val)) {
$lastDataRow = $curR;
}
$rowData[$curC] = $val;
$curC++;
}
$rows[$curR] = array_pad($rowData, $this->colCount, null);
$curR++;
}
if($this->config['removeTrailingRows']) {
$this->data = array_slice($rows, 0, $lastDataRow + 1);
$this->rowCount = count($this->data);
} else {
$this->data = $rows;
}
}

protected function getColumnIndex($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);
}
throw new Exception("Invalid cell index");
}
protected function parseCellValue($cell) {
// $cell['t'] is the cell type
switch ((string)$cell["t"]) {
case "s": // Value is a shared string
if ((string)$cell->v != '') {
$value = $this->workbook->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 = self::parseRichText($cell->is);
break;
case "e": // Value is an error message
if ((string)$cell->v != '') {
$value = (string)$cell->v;
} else {
$value = '';
}
break;
default:
if(!isset($cell->v)) {
return null;
}
$value = (string)$cell->v;

// Check for numeric values
if (is_numeric($value)) {
if ($value == (int)$value) $value = (int)$value;
elseif ($value == (float)$value) $value = (float)$value;
elseif ($value == (double)$value) $value = (double)$value;
}
}
return $value;
}

// returns the text content from a rich text or inline string field
    public static 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);
    }
}


Wednesday, 16 July 2014

Redirect HTTP to HTTPS using mod_rewrite

Redirect http to https htaccess


<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /

RewriteCond %{HTTPS} !=on
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
RewriteCond $1 !^children/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

</IfModule>

Sunday, 13 July 2014

Connect to BSNL Broadband using Router

Configure Beetel 110TC1 ADSL2+ Router for BSNL


Open http://192.168.1.1 in your browser. Use the following username password to login

username : admin
password : admin or password

You should be greeted with the Beetel 110TC1 configuration page.
Click on Interface Setup
For Virtual Circuit, you can choose either the default PVC0 or PVC2. If you choose PVC0, then you need to set VPI = 0 and VCI = 35 (This is specific to BNSL).
 If you choose PVC2, the default values are 0 and 35.


NB :- For me  Virtual Circuit:  Status PV0 is Deactivated with VPI = 1 and VCI = 32
  
PVC2 status Activated with VPI = 0 and VCI = 35
Servicename : BSNL
Username:uname
Password: password
Encapsulation:  PPPoE LLC
Bridge Interface: Deactivated
Get IP Address: Dynamic


Under the ‘PPPoA/PPPoE’ section enter the user name/password combination provided by BSNL. For me the username as first two characters of my first name follower by my telephone number along with the STD Code. That is ni80xxxxxxxx. The password is ‘password’.
Save your changes.
The next step is to set the DNS entries, navigate to the sub-tab ‘LAN’ under ‘Interface Setup’.
Under DHCP, change the DNS Relay to ‘Use ZAuto Discovered DNS Server Only’. 

Tuesday, 22 April 2014

jQuery: Difference between parent(), parents() and closest()

HTML

<xmp>
<html lang="en">
  <head>
     <script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
  </head>
  <body>
     <div>
        
            <a href="https://www.blogger.com/blogger.g?blogID=5288802523561781990#" id="anchorTag">Click here</a>
         


      </div>
</body>
</html>

jQuery
   $('#anchorTag').parent();      //This would return p, immediate parent of a#anchorTag.
parents(selector) : This returns the multiple ancestors. Its not restricted to only one level of parent/ancestors of the element. This is the main difference between the parent and parents method.
In the above HTML Snippet. If i do
   $('#anchorTag').parents();        //This would return all the ancestors (p, div, body, html)

   //On passing selector it will filter down the matched parent elements by selector

   $('#anchorTag').parents('div');   //This would give me only div
closest(selector) : It works like parents(), except that it returns only one parent/ancestor. This is ideal for the situation i mentioned earlier. If i want to check for existence of element in the ancestry tree, then i would prefer to use the closest rather than parents as it only target the selector rather than filtering it from all the ancestor elements. Here is example
$('#anchorTag').closest();           //This would give me empty object as we have not mentioned the selector
$('#anchorTag').closest('div');      //This would give me the div.
Hope this post has helped in terms of using the parent, parents and closest methods of jQuery library. Thank you for reading.

Monday, 14 April 2014

Export database table data to excel format

Export database table data to excel format

Select the table to be exported to Excel Format
excel.php
<table style="width:100%;left:0px;position:relative;empty-cells:show;" border=0 cellpadding=0 cellspacing=0>
<tr height=50>
    <td style="color:#CC3300;font-size:13px;font-weight:bold;">Select the table to be exported to Excel Format</td>
   
</tr>
<tr>
    <td style="color:blue;font-size:12px;">Select Table</td>
</tr>
<tr>
    <td style="color:blue;font-size:12px;">
    <select name="selected_table" >
    <option value=""> </option>
    <?php 
            $fromdb=$_SESSION['COMPANY_DB'];
            $sql = "SHOW TABLES FROM ".$fromdb;
            $result = mysql_query($sql);
            while ($row = mysql_fetch_row($result))
            {
                        $table=$row[0];
                        echo "<option value=$table>$table</option>";
            }   
    ?>
    </select>
    </td>
</tr>
</table>
<BR></br>
<input type=submit name="export" value="Export">
export.php
if($export)
{
            $my_table=$_REQUEST['selected_table'];
            $result = mysql_query('select * from '.$my_table);
            $count = mysql_num_fields($result);
           
            for ($i = 0; $i < $count; $i++){
            $header .= mysql_field_name($result, $i)."\t";
            }
           
            while($row = mysql_fetch_row($result)){
            $line = '';
            foreach($row as $value){
            if(!isset($value) || $value == ""){
            $value = "\t";
            }else{
            # important to escape any quotes to preserve them in the data.
            $value = str_replace('"', '""', $value);
            # needed to encapsulate data in quotes because some data might be multi line.
            # the good news is that numbers remain numbers in Excel even though quoted.
            $value = '"' . $value . '"' . "\t";
            }
             
           
            $line .= $value;
            }
            $data .= trim($line)."\n";
            }
            # this line is needed because returns embedded in the data have "\r"
            # and this looks like a "box character" in Excel
            $data = str_replace("\r", "", $data);
           
             
            # Nice to let someone know that the search came up empty.
            # Otherwise only the column name headers will be output to Excel.
            if ($data == "") {
            $data = "\nno matching records found\n";
            }
           
            header("Content-type: application/x-msdownload");
            # This line will stream the file to the user rather than spray it across the screen
            //header("Content-Type: application/vnd.ms-excel; name='excel'");
           
           
           
            header("Content-Disposition: attachment; filename=excelfile.xls");
            header("Pragma: no-cache");
            header("Expires: 0");
           
            echo $header."\n".$data;
           
            //print "done";
}
header("Location: excel.php");

PHP Interview Questions

How to prevent web browser to image caching?       

The simple way to prevent image caching is to append time stamp with the name on image.
Ex- <img src=’image.jpg?<?php echo time() ?>’ />

What is the difference between Primary Key and Unique key?    

Both Primary Key and Unique Key enforces uniqueness of the column on which they are defined. But by default Primary Key creates a Clustered Index on the column, where are Unique Key creates a Non clustered Index by default. Another major difference is that, Primary Key doesn’t allow Nulls, but Unique Key allows one NULL only.

What is the difference between $name and $$name?

$name is variable where as $$name is reference variable
like $name=Sadiq and $$name=Akhtar so $Sadiq value is Akhtar.

What’s the difference between md5(), crc32() and sha1() crypto on PHP?        

The major difference is the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1() returns a 128 bit md5() returns a 160 bit value. This is important when avoiding collisions.