Rss Feed
  1. PHP to know

    Friday 29 March 2013


    Why we used PHP?

    Because of several main reason we have to use PHP. These are:
    1.PHP runs on many different platforms like that Unix,Linux and Windows etc.
    2.It codes and software are free and easy to download.
    3.It is secure because user can only aware about output doesn't know how that comes.
    4.It is fast,flexible and reliable.
    5.It supports many servers like: Apache,IIS etc.
    6.PHP supports many databases such as MYSQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.,



    What is the session life cycle?

    life-cycle of a session: open, read, write and close

    What is CRUD?

    Create, Read, Update and Delete

    Difference between echo and print?

    ECHO : take multiple parameter while PRINT : take only one parameter.
    ECHO is much faster then PRINT.
    ECHO is an keyword, PRINT is an function


    What is an Array?
    An array is a special variable, which can hold more than one value at a time.

    Indexed arrays - Arrays with numeric index
    Associative arrays - Arrays with named keys
    Multidimensional arrays - Arrays containing one or more arrays


    In how many ways we can retrieve data in the result set of MYSQL using PHP?

    Procedural
    mysqli_fetch_array: - Fetch a result row as an associative array, a numeric array, or both.
    mysqli_fetch_assoc:- Fetch a result row as an associative array.
    mysqli_fetch_object:- Fetch a result row as an object.
    mysqli_fetch_row:- Get a result row as an enumerated array.

    Object oriented
    $result->fetch_assoc()


    How can we know the total number of elements of Array?

     
    sizeof($array_var)
    count($array_var)
    If we just pass a simple var instead of a an array it will return 1.

    Working with arrays

    array_unshift — Prepend one or more elements to the beginning of an array

    array_push — Push one or more elements onto the end of array

    array_shift — Shift an element off the beginning of array
    (i.e) removes the first element of an array.

    array_pop — Pop the element off the end of array

    array_merge — Merge one or more arrays

    array_flip — Exchanges all keys with their associated values in an array

    array_search — Searches the array for a given value and returns the corresponding key if successful

    array_key_exists — Checks if the given key or index exists in the array

    array_multisort — Sort multiple or multi-dimensional arrays

    array_reverse — Return an array with elements in reverse order

    array_slice — Extract a slice of the array

    array_splice — Remove a portion of the array and replace it with something else

    array_sum — Calculate the sum of values in an array


    What do you mean range()?

          Starting from a low value and going to a high value, the range() function creates an array of consecutive integer or character values. It takes up to three arguments: a starting value, an ending value, and an increment value. If only two arguments are given, the increment value defaults to 1.
    Example :
    echo range(1,10); // Returns 1,2,3,4,5,6,7,8,9,10
    ?>


    Sorting of arrays?
    http://php.net/manual/en/array.sorting.php

    What is strip_tags?

    It removes html and php tags in the given string

    What is the difference between GET and POST method?


    In the get method the data made available to the action page ( where data is received ) by the URL so data can be seen in the address bar. Not advisable if you are sending login info like password etc. By GET method it's possible to get query string value.

    In the post method the data will be available as data blocks and not as query string.

    What are Super Global arrays?

    Super Global array available anywhere in scripts even in classes and function.
    Important Super Global arrays are


    $GLOBALS
    $_GET
    $_POST
    $_SESSION
    $_COOKIE
    $_REQUEST
    $_ENV
    $_SERVER



    Why we use $_REQUEST variable?

    We use $_REQUEST variable in PHP to collect the data_values from $_GET,$_POST and $_COOKIE variable.


    What's the difference between COPY OF A FILE & MOVE_UPLOAD_FILE in file uploading?

    MOVE_UPLOAD_FILE :   This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.
    If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.
    Copy :Makes a copy of a file. Returns TRUE if the copy succeeded, FALSE otherwise.

    Working with Strings

    strlen() — To find the length of the string.


    strstr() — returns part of a given string from the first occurrence of a given substring to the end of the string.
    For example:
    strstr("user@example.com","@") will return "@example.com".

    stristr() — is idential to strstr() except that it is case insensitive.


    str_split — Convert a string to an array

    str_shuffle — Randomly shuffles a string

    rand — Generate a random integer



    What are the Formatting and Printing Strings available in PHP?
       
    Function                     Description
    printf()    :                 Displays a formatted string
    sprintf()   :                 Saves a formatted string in a variable
    fprintf()   :                 Prints a formatted string to a file
    number_format()  :   Formats numbers as strings

    Working with files

    fopen() opens file to handle
    fclose() close file
    How we handle errors in PHP?Explain it?

    In PHP we can handle errors easily.Because when error comes it gives error line with their respective line and send error message to the web browser.
    When we creating any web application and scripts. We should handle errors wisely.Because when this not handle properly it can make bg hole in security.
    In PHP we handle errors by using these methods:
    1.Simple "die()" statements
    2.Custom errors and error triggers
    3.Error reporting


    What is the difference b/n 'action' and 'target' in form tag?

    Action:
        Action attribute specifies where to send the form-data when
    a form is submitted.
        Syntax:
        Example:
    action="formValidation.php">
    Target:
        The target attribute specifies where to open the action URL.
         Syntax:
            Value:
             _blank – open in new window
            _self- Open in the same frame as it was clicked
            _parent- Open in the parent frameset
            _top- Open in the full body of the window
            Framename- Open in a named frame



    What do you understand about PHP accelerator ? 

    Basically PHP accelerator is used to boost up the performance of PHP programing language.We use PHP accelerator to reduce the server load and also use to enhance the performance of PHP code near about 2-10 times.In one word we can say that PHP accelertator is code optimization technique.


    How we use ceil() and floor() function in PHP?

    ceil() is use to find nearest maximum values of passing value.
    Example:
    $var=6.5;
    $ans_var=ceil($var);
    echo $ans_var;
    Output:
    7
    floor() is use to find nearest minimum values of passing value.
    Example:
    $var=6.5
    $ans_var=floor($var);
    echo $ans_var;
    Output:
    6


    PHP isset vs empty

    A very common mistake when first getting in to PHP is to think that isset() and empty() can be used as each others inverse. This is VERY far from the truth and can cause major problems in an application. In this quick article I will explore the differences between isset and empty in PHP

    isset

    isset will determine if a variable is set and is not NULL. This simply means if the variable has NEVER been set to anything or it is null isset will return false otherwise it will return true. Obviously you can add an ! before it to reverse this depending on it's purpose in your application. Here is a quick example

    var_dump(isset($var));   //will output false since it is not set
    $var=null;
    var_dump(isset($var));   //will output false since it is null
    $var=0;
    var_dump(isset($var));   //will output true
    $var="";
    var_dump(isset($var));   //will output true
    $var="0";
    var_dump(isset($var));   //will output true
    $var=array();
    var_dump(isset($var));   //will output true
    $var=false;
    var_dump(isset($var));   //will output true
    $var="this is a string";
    var_dump(isset($var));   //will output true

    empty

    empty is quite a bit different than isset. First of all, the most obvious thing is that it works in the opposite way of isset, but there is much more to it than that. Empty will return true for everything isset would return false for PLUS it will also return true for an empty string, an empty array, the string "0″, the number 0, or false. Notice the differences in the same example as above using empty instead of isset.

    var_dump(empty($var));   //will output true since it is not set
    $var=null;
    var_dump(empty($var));   //will output true since it is null
    $var=0;
    var_dump(empty($var));   //will output true 0 is considered empty
    $var="";
    var_dump(empty($var));   //will output true "" is an empty string
    $var="0";
    var_dump(empty($var));   //will output true "0" is empty
    $var=array();
    var_dump(empty($var));   //will output true for an empty array
    $var=false;
    var_dump(empty($var));   //will output true since bool false is considered empty
    $var="this is a string";
    var_dump(empty($var));   //will output false
    $var=2;
    var_dump(empty($var));   //will output false since 2 is a valid number


    The main difference b/w isset and empty are given below:
    isset: This variable is used to handle functions and checked a variable is set even through it is empty.
    empty: This variable is used to handle functions and checked either variable has a value or it is an empty string,zero0 or not set at all.

    What is $_SERVER? 

    $_SERVER is an array containing information such as headers, paths, and script locations.

    $_SERVER['SERVER_NAME'] To get server neme. Eg; www.google.com
    $_SERVER['PHP_SELF'] To get the current url
    $_SERVER['HTTP_USER_AGENT'] To get browser properties
    $_SERVER['HTTP_REFERERE'] - Return to previous url
    $_SERVER['REMOTE_ADDR'] - The IP address from which the user is viewing the current page


    What Is a Session?
    Sessions are commonly used to store temporary data in server hold information about one single user activity, and are available to all pages in one application.
    session_start() To start session
    session_register($name) To register a variable in session
    unset($name) To delete a particular data in session
    session_destroy() To destroy the current session


    What is a Cookie?

    A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.


    setcookie('variable','value','time');
    variable - name of the cookie variable
    value - value of the cookie variable
    time - expiry time
    Example:
    <?php
    setcookie("user", "Alex Porter", time()+3600);
    ?>
    user- cookie variable name
    Alex Porter- value of the variable 'Test'
    time()+3600 - denotes that the cookie will expire after an one hour


    Retrieving cookie data

    &_COOKIE['user'];


    What is a Persistent Cookie?

    Cookies are used to remember the users. Content of a Persistent cookie remains unchanged even when the browser is closed. ‘Remember me’ generally used for login is the best example for Persistent Cookie.


    Difference between SESSION and COOKIE?

    Sessions: are basically tokens which are generated when a user proceeds with a login mechanism. Each time when a user logged into a website a new and unique token is generated and it will destroyed whenever he/she logged out from that site or power goes off. However, session information is temporary and will be deleted after the user has left the website.

    - amount of data to be stored is NOT LIMITED
    - it can store OBJECTS
    - quite SLOWER as compared to cookies


    Cookies:are temporary files which are store in users hard disk. A cookie is often used to identify a user. Suppose a user enters into a website and without logging off he/she closed the page, next time when he/she open the page he/she found himself/ herself logged in. This is because of cookies, they store the user information. We can set the cookies by <b>setCookie()</b> function. The syntax if setCookie function is <b>setCookie(name, value, expire, path, domain);</b>.

    - amount of data to be stored is LIMITED
    - it can only store STRINGS
    - quite FASTER than a session

    What is the difference between the functions unlink and unset?

    unlink() deletes the given file from the file system.
    unset() deletes particular session data makes a variable undefined.

    How many ways we can pass the variable through the navigation between the pages?
     
    1.Register the variable into the session
    2.Pass the variable as a cookie
    3.Pass the variable as part of the URL


    Explain include(), include_once, require() and require_once.
     include()
    The include() function takes all the content in a specified file and includes it in the current file. If an error occurs, the include() function generates a warning, but the script will continue execution.

    include_once()
    File will not be included more than once. If we want to include a file once only and further calling of the file will be ignored then we have to use the PHP function include_once().

    require()
    The require() function is identical to include(), except that it handles errors differently. The require() generates a fatal error, and the script will stop.

    require_once()
    The required file is called only once when a page is open and further calling of the file will be ignored.

    What are the different types of errors in php?
     
    Notices: These are trivial, non-critical errors that PHP encounters while executing a script - for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all - although, as you will see, you can change this default behaviour.
    Warnings: These are more serious errors - for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.
    Fatal errors: These are critical errors - for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP’s default behaviour is to display them to the user when they take place.

    What are encryption functions in PHP?

    CRYPT(), MD5()


    What is overloading and overriding?

    Overloading is defining functions that have similar signatures, yet have different parameters. Overriding is only pertinent to derived classes, where the parent class has defined a method and the derived class wishes to override that method.


    Overloading
    1.The Methods with the same name but it differs by types of arguments and no,,of arguments.
    2.Overloading is Static Polymorphism.
    3.Overloading refers to situation where there are two or more methods in a class with the same name but with different parameters list.

    Overriding
    1.The Methods with the same name and same no,,of arguments and types,but one is in base class and second one is in derived class.
    2.Overriding is dynamic Polymorphism.
    3.Overriding refers to a situation where sub-class inherits a method from Base class which may result into adding or changing the method behavior.

    what is magic methods?


    PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality.
    The function names __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state() and __clone() are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.


    OOPS in PHP

    Class

    Classes are the templates used to define objects.

    Classes are blueprint of the objects.

    When we instantiate the class, creating instance of it, thus creating a object.
    $object_name = new class_name();

    Objects

    Objects are the real time entities . Once class is defined any number of objects can be created related to it.


    Constructor __construct()
    Constructor allows to initialize object when it is created.
    Constructor is the default function that is called default when class called.

    Destructor __destruct()

    The destructor methods are called as soon as all references to a particular object are removed or when the object is explicitly destroyed.


     Inheritance:

    Inheritance is the mechanism of deriving a new class from an existing class.It allows a sub-class / child class to share/inherit the attributes and behaviors of a base-class or parent class.


    1. Single Inheritance
    when a single derived class is created from a single base class then the inheritance is called as single inheritance.

    Different types of inheritance


    2. Hierarchical Inheritance
    when more than one derived class are created from a single base class, then that inheritance is called as hierarchical inheritance.


    Hierarical Inheritance



    3.Multi Level Inheritance
    when a derived class is created from another derived class, then that inheritance is called as multi level inheritance.



    Multi level Inheritance

    4. Multiple Inheritance

    when a derived class is created from more than one base class then that inheritance is called as multiple inheritance. But multiple inheritance is not supported by php and can be done using interfaces.

    Interface

    An interface is like a class using interface keyword and contains only function declarations(function with no body).
    An Interface should be implemented in the class and all the methods or functions should be overridden in this class.

    Multiple inheritance is achieved through interface.

    Example:
    <?php

    // Declare the interface 'iTemplate'
    interface iTemplate
    {
        public function setVariable($name, $var);
        public function getHtml($template);
    }

    // Implement the interface
    // This will work
    class Template implements iTemplate
    {
        private $vars = array();

        public function setVariable($name, $var)
        {
            $this->vars[$name] = $var;
        }

        public function getHtml($template)
        {
            foreach($this->vars as $name => $value) {
                $template = str_replace('{' . $name . '}', $value, $template);
            }

            return $template;
        }
    }




    Access specifiers or access modifiers

    Public: Property or method declared as public, No access restriction. Any one can use it.

    Private:Property or method declared as public, Only can be used within the class declared.

    Protected: Property or method declared as public, Can be used by the class declared and by the derived class of it.

    Abstract: This property or method needs to be subclassed and cannot be used directly.




  2. Multiselect Box CakePHP

    Wednesday 27 March 2013

    Making dropdown as multiple select box
    <?php echo $this->Form->input('origins', array('multiple' => 'true')); ?>



  3. CakePHP and jQuery problems.


    I kept getting Black-holed. The most common answer I found online was to disable security altogether. (Seriously, don’t do that). Rather, the correct answer via consensus in the #CakePHP IRC, as well as multiple other hidden forum posts was to disable it on a per hidden field basis.
    Easy answer. Make this:
    Into this:
    (The last one didn’t work for me as was vastly suggested, but the following worked for me and should be an alternate)
    Happy coding!

    Refer:
    http://www.sixteenink.com/tag/unlockfield/


  4. Add a custom currency / symbol


    To add a custom currency paste this code in your theme functions.php file and swap out the currency code and symbol with your own. After doing so it will be available from WooCommerce settings.

    add_filter( 'woocommerce_currencies', 'add_my_currency' );

    function add_my_currency( $currencies ) {
         $currencies['ABC'] = __( 'Currency name', 'woocommerce' );
         return $currencies;
    }

    add_filter('woocommerce_currency_symbol', 'add_my_currency_symbol', 10, 2);

    function add_my_currency_symbol( $currency_symbol, $currency ) {
         switch( $currency ) {
              case 'ABC': $currency_symbol = '$'; break;
         }
         return $currency_symbol;
    }

    Refer:

    http://docs.woothemes.com/document/add-a-custom-currency-symbol/

    Example


    add_filter( 'woocommerce_currencies', 'add_inr_currency' );
    add_filter( 'woocommerce_currency_symbol', 'add_inr_currency_symbol' );

    function add_inr_currency( $currencies ) {
        $currencies['INR'] = 'INR';
        return $currencies;
    }

    function add_inr_currency_symbol( $symbol ) {
    $currency = get_option( 'woocommerce_currency' );
    switch( $currency ) {
    case 'INR': $symbol = 'Rs.'; break;
    }
    return $symbol;
    }

    Refer:
    http://www.mrova.com/adding-currency-to-woocommerce/

  5. Cakephp Admin routing

    Sunday 24 March 2013


    Add this in routes.php

    if ($plugins = App::objects('plugin')) {
        $pluginMatch = implode('|', array_map(array('Inflector', 'underscore'), $plugins));
        Router::connect(
            "/admin/:plugin/:controller/:action/*",
            array('action' => null, 'prefix' => 'admin', 'admin' => true),
            array('plugin' => $pluginMatch)
        );
    }

    Router::connect("/admin", array('action' => 'index', 'controller' => 'settings', 'prefix' => 'admin', 'admin' => true));

    Router::connect("/admin/:controller", array('action' => 'index', 'prefix' => 'admin', 'admin' => true));

    Router::connect("/admin/:controller/:action/*", array('prefix' => 'admin', 'admin' => true));
       

  6. To create a unique cakephp slug


    Generate unique slugs in CakePHP
    I believe it was Wordpress who came up with the term "slug". It has been adopted by many other systems though, and it basically means the following: a unique identifier which can be used in a URL to create a permalink to a page.
    At least, that's my interpretation of it. In this article I will show you how you can generate a unique slug easily when working with the CakePHP Framework.
    Since the slug should be unique across records in the same database table, the best place to store slug-generating functionality is in the AppModel, which is, strictly speaking, the only business logic layer that may access the database.
    If you haven't got an AppModel created yet, add one in /app/app_model.PHP. You may fill it with the following code:
    1.   <?php
    2.   class AppModel extends Model {
    3.    
    4.   function createSlug ($string, $id=null) {
    5.   $slug = Inflector::slug ($string,'-');
    6.   $slug = low ($slug);
    7.   $i = 0;
    8.   $params = array ();
    9.   $params ['conditions']= array();
    10.               $params ['conditions'][$this->name.'.slug']= $slug;
    11.               if (!is_null($id)) {
    12.               $params ['conditions']['not'] = array($this->name.'.id'=>$id);
    13.               }
    14.               while (count($this->find ('all',$params))) {
    15.               if (!preg_match ('/-{1}[0-9]+$/', $slug )) {
    16.               $slug .= '-' . ++$i;
    17.               } else {
    18.               $slug = preg_replace ('/[0-9]+$/', ++$i, $slug );
    19.               }
    20.               $params ['conditions'][$this->name . '.slug']= $slug;
    21.               }
    22.               return $slug;
    23.               }
    24.               }
    25.               ?>
    What this code does, is providing a method, createSlug (), which can be accessed from all models in your application. It'll normalize the string, make it URL-friendly and last but not least, it makes it unique.
    To demonstrate the "unique" part, let's say we've got a record with the title "I love CakePHP". The createSlug method will turn this into "i-love-cakePHP". Human friendly and search-engine friendly.
    What happens when I wish to create two more items in my database called "I love CakePHP"? The 
    createSlug method will generate the following two slugs: i-love-cakePHP-1 and i-love-cakePHP-2.
    This way users can bookmark your URLs and always end up in the right place, even though the titles of your records may be similar.
    How to use?
    It's simple, really. Since the method is created in the AppModel base class, you can invoke it from every model in your application. When saving a record, you can simply call...

    1.   $slug = $this->createSlug ('my title');

    ...from within your models, or...
    1.   $slug = $this->MyModel->createSlug ('my title');
    2. $this->request->data['model']['slug'] = slug;
    ...from within your controllers, right before you insert new data.
    Note that you have to pass the id from the current record when you're modifying existing records, so it can exclude that from its check, like this:
    1.   $slug = $this->createSlug ('my title', 10);

    refer :
    http://www.whatstyle.net/articles/52/generate_unique_slugs_in_cakephp