Jun 29, 2014

Check if a string is valid JSON in php

A little function to check if a string is valid JSON or not

 function isValidJson($string){
  json_decode($string, true);
  if (json_last_error() == JSON_ERROR_NONE) {
   return true;
  }
  return false;
 }


May 27, 2014

Problems and solutions during installing Magento

Different types of issues are found during installing Magento. Here are some compilation of Magento installation problems and their solutions.

Problem 1 : Database server does not support the InnoDB storage engine while installing magento

Solution 1 :

Go To Line 59 of the file app/code/core/Mage/Install/Model/Installer/Db/Mysql4.php
Change this function

    public function supportEngine()
    {
        $variables  = $this->_getConnection()
            ->fetchPairs('SHOW VARIABLES');
        return (!isset($variables['have_innodb']) || $variables['have_innodb'] != 'YES') ? false : true;
    }

With this

    public function supportEngine()
    {
        $variables  = $this->_getConnection()
            ->fetchPairs('SHOW ENGINES');
        return (isset($variables['InnoDB']) && $variables['InnoDB'] != 'NO');
    } 


Problem 2: 404 Not Found Error After Installation

Sometimes after installing magento, clicking on any link results in 404 not found error. This happens because the rewrite module of the server is not enabled. Just enable the mod_rewrite and it will work.

Solution 2:

Enable rewrite_module (mod_rewrite) of your Apache Server

Jan 15, 2014

List all files of a directory in php

Listing all files of a directory in php is quite easy with php DirectoryIterator class. This class provides a simple interface for viewing the contents of filesystem directories.

Here is a simple php function to list all files of a directory. This is a recursive function so that it will list files of all of its subdirectories too.

   function list_directory_contents($dir){
 
     $dh = new DirectoryIterator($dir);    
     foreach ($dh as $item) {
         if (!$item->isDot()) {
            if ($item->isDir()) {
                list_directory_contents("$dir/$item");
            } else {
                echo $dir . "/" . $item->getFilename();
                echo "<br>";
            }
         }
      }
   }

  # Call function 
  
  list_directory_contents("abc");
  
The output will be something like

   abc/abc1.txt
   abc/abc2.txt
   abc/abc3.txt
   abc/xyz/xyz1.txt
   abc/xyz/xyz2.txt

Jan 14, 2014

Using MySql replace function

MySql has a very useful function replace() which allows you to replace substring or characters. It is really useful while working with huge database table where you want to update certain values with another value. Its syntax is quite simple.

   REPLACE ( field_name, 'find_string', 'replacement_string' );

To update some values in database table use query as follows using replace function.

   UPDATE tutorials SET topic = REPLACE (topic, 'Php', 'Php MySql');

You can also run a select query using this function if you don't want to update table but want to fetch data as replaced. This will only output replaced values and there will be no changes in database.

   SELECT REPLACE (topic, 'Php', 'Php MySql') as new_topic 
   FROM tutorials 
   WHERE topic = 'Php';

Dec 14, 2013

Commonly used abbreviations in php

While working with php or when we talk about php, some abbreviations are more frequently used. I have compiled some most commonly used abbreviations. Here is the list.

    

    AJAX  =>  Asynchronous JavaScript And XML
    API   =>  Application Programming Interface
    ASCII =>  American Standard Code for Information Interchange
    CMS   =>  Content Management System
    CSS   =>  Cascading Style Sheet
    CGI   =>  Common Gateway Interface
    CLI   =>  Command Line Interface
    DB    =>  DataBase
    DNS   =>  Domain Name System
    DOM   =>  Document Object Model
    FTP   =>  File Transfer Protocol
    GD    =>  Graphics Draw | Gif Draw
    HTML  =>  Hypertext Markup Language
    HTTP  =>  Hypertext Transfer Protocol
    HTTPS =>  Hypertext Transfer Protocol Secure
    IP    =>  Internet Protocol
    IIS   =>  Internet Information Services
    JS    =>  JavaScript  
    JSON  =>  JavaScript Object Notation
    LAMP  =>  Linux Apache MySQL PHP
    MAMP  =>  Macintosh Apache MySQL PHP
    MIME  =>  Multipurpose Internet Mail Extensions
    OOP   =>  Object Oriented Programming
    PCRE  =>  Perl Compatible Regular Expressions
    PEAR  =>  PHP Extension and Application Repository
    PECL  =>  PHP Extension Community Library
    PHP   =>  Hypertext Preprocessor
    PDO   =>  PHP Data Objects
    POSIX =>  Portable Operating System Interface
    RegEx =>  Regular Expression
    REST  =>  Representational State Transfer
    RSS   =>  Really Simple Syndication
    SAPI  =>  Server Application Programming Interface
    SOAP  =>  Simple Object Access Protocol
    SPL   =>  Standard PHP Library
    SMTP  =>  Simple Mail Transfer Protocol
    SQL   =>  Structured Query Language
    INI   =>  INItialization
    SEO   =>  Search Engine Optimization
    PING  =>  Packet InterNet Groper
    SSH   =>  Secure SHell
    SSL   =>  Secure Sockets Layer
    UCS   =>  Universal Character Set
    URI   =>  Uniform Resource Identifier
    URL   =>  Uniform Resource Locator
    UTF   =>  Unicode Transformation Format
    WAMP  =>  Windows Apache MySQL PHP
    WWW   =>  World Wide Web
    XAMPP =>  X (any of four different operating systems) Apache MySQL PHP & Perl
    XML   =>  eXtensible Markup Language
    XML-RPC=> XML Remote Procedure Call
    XPATH =>  XML PATH
    XSS   =>  cross Site Scripting


Dec 6, 2013

Move list box items from one box to another with jquery

While working with select boxes somewhere you need to use multiple selections and selecting multiple items from a bigger list is not user friendly. Here the idea is to make two select boxes and move items from one box to another. So it becomes more user friendly and looks good when it comes to UX.

It is quite easy to implement this with jquery. Just remove the item from one box and append to another.
You can move all items at once or you can move only selected items.

jQuery to move selected list box items from one box to another

 
  $('#from option:selected').remove().appendTo('#to'); 

jQuery to move all list box items from one box to another

 
  $('#from option').remove().appendTo('#to');

The above two lines of jquery does all the trick. Here is the full script. The jquery, css and the html.

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Move from one select box to another</title>
    <style type="text/css">
    select {
        width: 200px;
        float: left;
    }
    .controls {
        width: 40px;
        float: left;
        margin: 10px;
    }
    .controls a {
        background-color: #222222;
        border-radius: 4px;
        border: 2px solid #000;
        color: #ffffff;
        padding: 2px;
        font-size: 14px;
        text-decoration: none;
        display: inline-block;
        text-align: center;
        margin: 5px;
        width: 20px;
    }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
    </script>
    <script>
    function moveAll(from, to) {
        $('#'+from+' option').remove().appendTo('#'+to); 
    }
    
    function moveSelected(from, to) {
        $('#'+from+' option:selected').remove().appendTo('#'+to); 
    }
    </script>
    </head>
    
    <body>
    <select multiple size="10" id="from">
      <option value="html">Html</option>
      <option value="css">Css</option>
      <option value="google">Google</option>
      <option value="javascript">Javascript</option>
      <option value="jquery">Jquery</option>
      <option value="regex">Regex</option>
      <option value="php">Php</option>
      <option value="mysql">Mysql</option>
      <option value="xml">Xml</option>
      <option value="json">Json</option>
    </select>
    <div class="controls"> 
        <a href="javascript:moveAll('from', 'to')">&gt;&gt;</a> 
        <a href="javascript:moveSelected('from', 'to')">&gt;</a> 
        <a href="javascript:moveSelected('to', 'from')">&lt;</a> 
        <a href="javascript:moveAll('to', 'from')" href="#">&lt;&lt;</a> </div>
    <select multiple id="to" size="10">
    </select>
    </body>
    </html>

See the demo of the code.

>> > < <<

Nov 27, 2013

Convert currency using google finance calculator in php

Earlier we used to Convert currency using Google api. But as Google has closed its iGoogle service from 1st Nov 2013, this api will no longer work. But we have an alternative to convert currency using google finance calculator.


Here is a little code snippet that can be used to convert currency from one format to another.
It takes three parameters The amount to be converted, convert from and convert to

  <?php
  function convertCurrency($amount, $from, $to){
    $url  = "https://www.google.com/finance/converter?a=$amount&from=$from&to=$to";
    $data = file_get_contents($url);
    preg_match("/<span class=bld>(.*)<\/span>/",$data, $converted);
    $converted = preg_replace("/[^0-9.]/", "", $converted[1]);
    return round($converted, 3);
  }

  # Call function  
  echo convertCurrency(1, "USD", "INR");
  ?>

The above php function returns something like 62.285

The Currency formats can be of following types


    AED => United Arab Emirates Dirham (AED)
    AFN => Afghan Afghani (AFN)
    ALL => Albanian Lek (ALL)
    AMD => Armenian Dram (AMD)
    ANG => Netherlands Antillean Guilder (ANG)
    AOA => Angolan Kwanza (AOA)
    ARS => Argentine Peso (ARS)
    AUD => Australian Dollar (A$)
    AWG => Aruban Florin (AWG)
    AZN => Azerbaijani Manat (AZN)
    BAM => Bosnia-Herzegovina Convertible Mark (BAM)
    BBD => Barbadian Dollar (BBD)
    BDT => Bangladeshi Taka (BDT)
    BGN => Bulgarian Lev (BGN)
    BHD => Bahraini Dinar (BHD)
    BIF => Burundian Franc (BIF)
    BMD => Bermudan Dollar (BMD)
    BND => Brunei Dollar (BND)
    BOB => Bolivian Boliviano (BOB)
    BRL => Brazilian Real (R$)
    BSD => Bahamian Dollar (BSD)
    BTN => Bhutanese Ngultrum (BTN)
    BWP => Botswanan Pula (BWP)
    BYR => Belarusian Ruble (BYR)
    BZD => Belize Dollar (BZD)
    CAD => Canadian Dollar (CA$)
    CDF => Congolese Franc (CDF)
    CHF => Swiss Franc (CHF)
    CLF => Chilean Unit of Account (UF) (CLF)
    CLP => Chilean Peso (CLP)
    CNH => CNH (CNH)
    CNY => Chinese Yuan (CN¥)
    COP => Colombian Peso (COP)
    CRC => Costa Rican Colón (CRC)
    CUP => Cuban Peso (CUP)
    CVE => Cape Verdean Escudo (CVE)
    CZK => Czech Republic Koruna (CZK)
    DEM => German Mark (DEM)
    DJF => Djiboutian Franc (DJF)
    DKK => Danish Krone (DKK)
    DOP => Dominican Peso (DOP)
    DZD => Algerian Dinar (DZD)
    EGP => Egyptian Pound (EGP)
    ERN => Eritrean Nakfa (ERN)
    ETB => Ethiopian Birr (ETB)
    EUR => Euro (€)
    FIM => Finnish Markka (FIM)
    FJD => Fijian Dollar (FJD)
    FKP => Falkland Islands Pound (FKP)
    FRF => French Franc (FRF)
    GBP => British Pound Sterling (£)
    GEL => Georgian Lari (GEL)
    GHS => Ghanaian Cedi (GHS)
    GIP => Gibraltar Pound (GIP)
    GMD => Gambian Dalasi (GMD)
    GNF => Guinean Franc (GNF)
    GTQ => Guatemalan Quetzal (GTQ)
    GYD => Guyanaese Dollar (GYD)
    HKD => Hong Kong Dollar (HK$)
    HNL => Honduran Lempira (HNL)
    HRK => Croatian Kuna (HRK)
    HTG => Haitian Gourde (HTG)
    HUF => Hungarian Forint (HUF)
    IDR => Indonesian Rupiah (IDR)
    IEP => Irish Pound (IEP)
    ILS => Israeli New Sheqel (₪)
    INR => Indian Rupee (Rs.)
    IQD => Iraqi Dinar (IQD)
    IRR => Iranian Rial (IRR)
    ISK => Icelandic Króna (ISK)
    ITL => Italian Lira (ITL)
    JMD => Jamaican Dollar (JMD)
    JOD => Jordanian Dinar (JOD)
    JPY => Japanese Yen (¥)
    KES => Kenyan Shilling (KES)
    KGS => Kyrgystani Som (KGS)
    KHR => Cambodian Riel (KHR)
    KMF => Comorian Franc (KMF)
    KPW => North Korean Won (KPW)
    KRW => South Korean Won (₩)
    KWD => Kuwaiti Dinar (KWD)
    KYD => Cayman Islands Dollar (KYD)
    KZT => Kazakhstani Tenge (KZT)
    LAK => Laotian Kip (LAK)
    LBP => Lebanese Pound (LBP)
    LKR => Sri Lankan Rupee (LKR)
    LRD => Liberian Dollar (LRD)
    LSL => Lesotho Loti (LSL)
    LTL => Lithuanian Litas (LTL)
    LVL => Latvian Lats (LVL)
    LYD => Libyan Dinar (LYD)
    MAD => Moroccan Dirham (MAD)
    MDL => Moldovan Leu (MDL)
    MGA => Malagasy Ariary (MGA)
    MKD => Macedonian Denar (MKD)
    MMK => Myanma Kyat (MMK)
    MNT => Mongolian Tugrik (MNT)
    MOP => Macanese Pataca (MOP)
    MRO => Mauritanian Ouguiya (MRO)
    MUR => Mauritian Rupee (MUR)
    MVR => Maldivian Rufiyaa (MVR)
    MWK => Malawian Kwacha (MWK)
    MXN => Mexican Peso (MX$)
    MYR => Malaysian Ringgit (MYR)
    MZN => Mozambican Metical (MZN)
    NAD => Namibian Dollar (NAD)
    NGN => Nigerian Naira (NGN)
    NIO => Nicaraguan Córdoba (NIO)
    NOK => Norwegian Krone (NOK)
    NPR => Nepalese Rupee (NPR)
    NZD => New Zealand Dollar (NZ$)
    OMR => Omani Rial (OMR)
    PAB => Panamanian Balboa (PAB)
    PEN => Peruvian Nuevo Sol (PEN)
    PGK => Papua New Guinean Kina (PGK)
    PHP => Philippine Peso (Php)
    PKG => PKG (PKG)
    PKR => Pakistani Rupee (PKR)
    PLN => Polish Zloty (PLN)
    PYG => Paraguayan Guarani (PYG)
    QAR => Qatari Rial (QAR)
    RON => Romanian Leu (RON)
    RSD => Serbian Dinar (RSD)
    RUB => Russian Ruble (RUB)
    RWF => Rwandan Franc (RWF)
    SAR => Saudi Riyal (SAR)
    SBD => Solomon Islands Dollar (SBD)
    SCR => Seychellois Rupee (SCR)
    SDG => Sudanese Pound (SDG)
    SEK => Swedish Krona (SEK)
    SGD => Singapore Dollar (SGD)
    SHP => Saint Helena Pound (SHP)
    SLL => Sierra Leonean Leone (SLL)
    SOS => Somali Shilling (SOS)
    SRD => Surinamese Dollar (SRD)
    STD => São Tomé and Príncipe Dobra (STD)
    SVC => Salvadoran Colón (SVC)
    SYP => Syrian Pound (SYP)
    SZL => Swazi Lilangeni (SZL)
    THB => Thai Baht (฿)
    TJS => Tajikistani Somoni (TJS)
    TMT => Turkmenistani Manat (TMT)
    TND => Tunisian Dinar (TND)
    TOP => Tongan Paʻanga (TOP)
    TRY => Turkish Lira (TRY)
    TTD => Trinidad and Tobago Dollar (TTD)
    TWD => New Taiwan Dollar (NT$)
    TZS => Tanzanian Shilling (TZS)
    UAH => Ukrainian Hryvnia (UAH)
    UGX => Ugandan Shilling (UGX)
    USD => US Dollar ($)
    UYU => Uruguayan Peso (UYU)
    UZS => Uzbekistan Som (UZS)
    VEF => Venezuelan Bolívar (VEF)
    VND => Vietnamese Dong (₫)
    VUV => Vanuatu Vatu (VUV)
    WST => Samoan Tala (WST)
    XAF => CFA Franc BEAC (FCFA)
    XCD => East Caribbean Dollar (EC$)
    XDR => Special Drawing Rights (XDR)
    XOF => CFA Franc BCEAO (CFA)
    XPF => CFP Franc (CFPF)
    YER => Yemeni Rial (YER)
    ZAR => South African Rand (ZAR)
    ZMK => Zambian Kwacha (1968-2012) (ZMK)
    ZMW => Zambian Kwacha (ZMW)
    ZWL => Zimbabwean Dollar (2009) (ZWL)


Nov 16, 2013

Get mimetype of an image in php

Mime type is an standard identifier of a file which indicates the type of data a file contains. It has two parts divided with a slash(/) like image/png.

The built in function of php getimagesize() gives lots of information about an image. And this function is enough to get the mime type of an image. It also returns Width and Height of the image.

GD Library is also not required to use this function.
   
   $image = getimagesize("imagename.jpg");
   echo $image['mime'];

It returns an array with upto 7 elements.
  Array
  (
    [0] => 200
    [1] => 125
    [2] => 2
    [3] => width="200" height="125"
    [bits] => 8
    [channels] => 3
    [mime] => image/jpeg
  )
Index 0 and 1 of the array contains the width and height of the array respectively.

This function can play a big role if you are creating an image upload script and want to limit the size of the image. Suppose if you don't want to upload an image greater than 400x250.

Just check width and height of the image using getimagesize() function and return respective messages to user to upload image smaller than the required size.

Nov 15, 2013

Validate Latitude and Longitude with regex and php

There are times when you need to validate latitude and longitude coordinates. May be you are taking it as user input or from some other source.

So here are two simple functions to validate latitude and longitude coordinates.
Regular expressions are used to match coordinates and php to check if it is valid or not.

Function to validate latitude


  function isValidLatitude($latitude){
    if (preg_match("/^-?([1-8]?[1-9]|[1-9]0)\.{1}\d{1,6}$/", $latitude)) {
        return true;
    } else {
        return false;
    }
  }
 
 # Call function
 
  if (isValidLatitude('28.6100')) {
       echo "Valid Latitude";
  }

Function to validate longitude


  function isValidLongitude($longitude){
    if(preg_match("/^-?([1]?[1-7][1-9]|[1]?[1-8][0]|[1-9]?[0-9])\.{1}\d{1,6}$/",
      $longitude)) {
       return true;
    } else {
       return false;
    }
  }

 # Call function
 
  if (isValidLongitude('77.2300')) {
       echo "Valid Longitude";
  }


 

Copyright @ 2013 Altaf hussain's blog.