50 Interview Questions

1.    PHP has two object operators.

    The first, ->, is used when you want to call a method on an instance or access an instance property.

    The second, ::, is used when you want to call a static method, access a static variable, or call a parent class's version of a method within a child class.


2.     A. How do I quickly rename a mysql database (change schema name)?
    For InnoDB, the following seems to work: create the new empty database, then rename each table in turn into the new database:

 

    RENAME TABLE old_db.table TO new_db.table;

    B. Use these few simple commands

    mysqldump -u username -p -v olddatabase > olddbdump.sql
    mysqladmin -u username -p create newdatabase
    mysql -u username -p newdatabase < olddbdump.sql
    Or to reduce IO use the following as suggested by @Pablo Marin-Garcia

    mysqladmin -u username -p create newdatabase
    mysqldump -u username -v olddatabase -p | mysql -u username -p -D newdatabase


    C. the simple way

    Change to DB directory:

    cd /var/lib/mysql/
    Shut down SQL…this is important!

    /etc/init.d/mysql stop
    Okay,this way doesn't work for InnoDB or BDB-Databases

    Rename Database:

    mv old-name new-name
    …or the table…

    cd database/

    mv old-name.frm new-name.frm

    mv old-name.MYD new-name.MYD

    mv old-name.MYI new-name.MYI
    Restart MySQL

    /etc/init.d/mysql start
    done…

    OK,this way doesn't work with InnoDB or BDB-DBs. In this case you have to dump the db and re-import it

    D. MySQL does not support the renaming of a database through its command interface at the moment, but you can rename the database if you have access to the directory in which MySQL stores its databases. For default MySQL installations this is usually in the Data directory under the directory where MySQL was installed. Locate the name of the database you want to rename under the Data directory and rename it. Renaming the directory could cause some permissions issues though. Be aware.

    Note: You must stop MySQL before you can rename the database

    I would recommend creating a new database (using the name you want) and export/import the data you need from the old to the new. Pretty simple.


3. How To Write the FORM Tag Correctly for Uploading Files? 
    When users clicks the submit button, files specified in the <INPUT TYPE=FILE…> will be transferred from the browser to the Web server. This transferring (uploading) process is controlled by a properly written <FORM…> tag as:

    <FORM ACTION=receiving.php METHOD=post ENCTYPE=multipart/form-data>

    Note that you must specify METHOD as "post" and ENCTYPE as "multipart/form-data" in order for the uploading process to work. The following PHP code, called logo_upload.php, shows you a complete FORM tag for file uploading:
    <?php
        print("<html><form action=processing_uploaded_files.php method=post enctype=multipart/form-data> ");
        print("Please submit an image file a Web site logo for fyicenter.com:<br> ");
        print("<input type=file name=fyicenter_logo><br> ");
        print("<input type=submit> ");
        print("</form></html> ");
    ?>
    


4.     Give a brief description of Multi-level caching scenarios. E.g. when to use it, and how?
    
    Multi level cache means a situation where we use more than one caching methods e.g. on the server side we can use memchache or Varnish or we can cache pages too (caching both on the PHP and SQL sides).
    
    A  multilevel cache spreads the cached data contents across several servers across the network.
    1. The top level caching server holds the most commonly accessed pages, and the lowest-level caching server holds the least commonly accessed pages.
    2. The various levels combine in a network of cache servers called a Web caching mesh.
    3. The caches communicate among themselves, using HTTP and special cache-coordination protocols, to divide the contents appropriately and maintain consistency among the servers.
    


5.     Explain the "unlink" and "unset" functions. 

 

    unlink() function is for file system handling. It just deletes the file in context.
    unset() function is for variable management. It makes a variable undefined


6.     Explain "GET" and "POST" methods. 

    Both the methods are used to send data to the server. 
    GET method – the browser appends the data onto the URL. 
    Post method – the data is sent as “standard input.”


7.     What do you mean by PEAR in PHP?
    PEAR is a framework and distribution system for reusable PHP components.

    What is meant by PEAR in php? What is the purpose of it?

    PEAR stands for "PHP Extension and Application Repository". As the name suggests, it gives advanced functionality to the PHP language and include many applications which can be used on fly. The purpose of it is as follows:- 

    – Open source structured library for PHP users
    – Code distribution and package maintenance system
    – Standard style for code written in PHP


8.    What Is a Persistent Cookie?

    Persistent cookie is a cookie which is permanently stored on user’s computer in a cookie file. They are used for tracking the user information of the users who are browsing from a very long time. They also have the drawbacks of being unsecure, as user can see the cookies which are saved on the computer. 

    A cookie which is stored in a cookie file permanently on the browser’s computer. 


9.    Differentiate between DROP a table and TRUNCATE a table. 
    DROP – It will delete the table and table data. 
    TRUNCATE – It will delete data of the table but not the table definition. 


10.    List the different run time errors in PHP. 

    a. Notices
    b. Warnings
    c. Fatal errors 


11. Is PHP a loosely Typed Language? What is the difference between strongly typed and loosely typed language?

    Yes, PHP is a loosely typed language. In this type of language variable doesn’t need to be declared before their use. This language converts the data according to its given value. Whereas, in strongly typed language first every type has to be declared (defined) then only it can be used.


12.    What is a PHP Session? 

    PHP session allows you to store the user session, like their information on server for faster access and for later use like username, IP addresses, their actions etc. The information which is saved is temporary and can be deleted after the user is no longer active. Example of starting a PHP session is as follows:

    <?php 
        session_start(); // start up your PHP session! 
    ?>


13. What is the use of obj_start()? 


    Its intializing the object buffer, so that the whole page will be first parsed (instead of parsing in parts and thrown to browser gradually) and stored in output buffer so that after complete page is executed, it is thrown to the browser once at a time.


14. What is the difference between session_register and $_session? 

    session_register() is used for register one or more global variables with the current session. While $_SESSION[] array is used for storing one or more variables with in the current session.

    If session_start() was not called before session_register() is called, an implicit call to session_start() with no parameters will be made. But $_SESSION requires session_start() before use.

    session_register function returns boolean value and $_SESSION returns string value

    session_register() function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0.


15.    What are new features that are in added in PHP5? 

    Following are new features added in PHP5

    1. PHP 5 introduces the Standard PHP Library (SPL), which provides a number of ready-made classes and interfaces.
    2. Access Modifiers are added in PHP5
    3. PHP5 has built-in exception classes that makes it very easy to create your own customized exceptions through inheritance.
    4. PHP 5 introduces the mysqli (MySQL Improved) extension with support for the features of MySQL databases versions 4.1 and higher. So use of prepare statements are allowed
    5. PHP5 comes with PDO which is a common interface for different database systems is only made possible by the new object model.
    6. SQLite is a database engine incorporated in php5 which can be used to develope faster, leaner and more versatile applications.
    7. In PHP 5 all Extensible Markup Language (XML) support is provided by the libxml2 XML toolkit.
    8. The reflection classes included in PHP 5 provide ways to introspect objects and reverse engineer code.
    9. In addition to built-in classes, PHP 5 also offers built-in interfaces. Iterator is the most important, as a number of classes and interfaces are derived from this interface.
    10. PHP 5 introduces a number of new "magic" methods. Magic methods begin with a double underscore, and this requires changing any user-defined methods or functions that use this naming convention.
    11. The major change to PHP in version 5 relating to OOP is usually summed up by saying that objects are now passed by reference.


16.    What is meant by urlencode and urldecode?
    urlencode() returns the URL encoded version of the given string. URL coding converts special characters into % signs followed by two hex digits. For example: urlencode("10.00%") will return "10%2E00%25". URL encoded strings are safe to be used as part of URLs. 
    urldecode() returns the URL decoded version of the given string.

 


17.    How do we know browser properties?


    get_browser() attempts to determine the capabilities of the user's browser. This is done by looking up the browser's information in the browscap.ini file. 
    echo $_SERVER[‘HTTP_USER_AGENT’];
    $browser = get_browser();
    
    foreach ($browser as $name => $value) {
        echo "<b>$name</b> $value <br />";
    }


18.    Name and explain five of the PHP error constants? 


    Some of the five PHP error constants are E_ERROR, E_WARNING, E_PARSE, E_USER_WARNING, E_COMPILE_WARNING, etc
    E_ERROR: -This error is displayed when there is fatal error which halts the execution of the script immediately.
    E_WARNING: -This warns the programmer about the error but the execution of the script is not stopped.
    E_PARSE: -These errors occur during compile time and these errors should only be generated by the parser.
    E_USER_WARNING: -This warning error is generated by the user and is non fatal. This is set by the programmer using trigger_error().
    E_COMPILE_WARNING: -this error is generated by the Zend scripting engine. This is a compile time non fatal error.

    In PHP 5 a new error level E_STRICT is available. As E_STRICT is not included within E_ALL you have to explicitly enable this kind of error level.


19. What do you need to do to improve the performance (speedy execution) for the script you have written? 
    
    There are many things to be considered. If your application based on Database, you should think about re-factoring queries try to use high performance queries (Use EXPLAIN to monitor the amount of records retrieved for each query. You can use UNIQUE, LIMIT, WHERE to filter the no of records returned).And also you should be aware of fine tuning configuration for your needs.
    
    In PHP you should use native functions instead of aliases. And also you should choose best function for the job. If you are going to do simple string replace use str_replace than ereg_replace. Use is_int() instead of is_integer().Use DBG or xdebug to profile your scripts, find the bottle neck function and try to re factor if possible.


20.    How do you create subdomains using PHP?

    Create the appropriate web root directory for example /home/sites/username/web and any subdirectories you wish
    A. Edit httpd.conf – add a new virtual host section
    B. Restart httpd


21.    What is the use of friend function in PHP?
    
    Friend functions
    Sometimes a function is best shared among a number of different classes. Such functions can be declared either as member functions of one class or as global functions. In either case they can be set to be friends of other classes, by using a friend specifier in the class that is admitting them. Such functions can use all attributes of the class which names them as a friend, as if they were themselves members of that class.

    A friend declaration is essentially a prototype for a member function, but instead of requiring an implementation with the name of that class attached by the double colon syntax, a global function or member function of another class provides the match.

    class mylinkage {
        private:
        mylinkage * prev;
        mylinkage * next;

        protected:
        friend void set_prev(mylinkage* L, mylinkage* N);
        void set_next(mylinkage* L);

        public:
        mylinkage * succ();
        mylinkage * pred();
        mylinkage();
    };

    void mylinkage::set_next(mylinkage* L) { next = L; }

    void set_prev(mylinkage * L, mylinkage * N ) { N->prev = L; }

    Friends in other classes. It is possible to specify a member function of another class as a friend as follows:
    
    class C    {
        friend int B::f1();
    };
    
    class B {
        int f1();
    };

    It is also possible to specify all the functions in another class as friends, by specifying the entire class as a friend.

    class A {
        friend class B;
    };


22.    What is meant by MIME?
    
    A. MIME is Multipurpose Internet Mail Extensions is an Internet standard for the format of e-mail. However browsers also uses MIME standard to transmit files. MIME has a header which is added to a beginning of the data. When browser sees such header it shows the data as it would be a file (for example image)

    Some examples of MIME types:
    audio/x-ms-wmp
    image/png
    aplication/x-shockwave-flash


    B. Multipurpose Internet Mail Extensions.
    WWW's ability to recognize and handle files of different types is largely dependent on the use of the MIME (Multipurpose Internet Mail Extensions) standard. The standard provides for a system of registration of file types with information about the applications needed to process them. This information is incorporated into Web server and browser software, and enables the automatic recognition and display of registered file types. ?


23. Explain normalization concept?

    The normalization process involves getting our data to conform to three progressive normal forms, and a higher level of normalization cannot be achieved until the previous levels have been achieved (there are actually five normal forms, but the last two are mainly academic and will not be discussed).

    First Normal Form
    The First Normal Form (or 1NF) involves removal of redundant data from horizontal rows. We want to ensure that there is no duplication of data in a given row, and that every column stores the least amount of information possible (making the field atomic).

    Second Normal Form
    Where the First Normal Form deals with redundancy of data across a horizontal row, Second Normal Form (or 2NF) deals with redundancy of data in vertical columns. As stated earlier, the normal forms are progressive, so to achieve Second Normal Form, your tables must already be in First Normal Form.

    Third Normal Form
    I have a confession to make; I do not often use Third Normal Form. In Third Normal Form we are looking for data in our tables that is not fully dependent on the primary key, but defendant on another value in the table


24.    How can we find the number of rows in a table using MySQL? 
    
    SELECT COUNT(*) FROM table_name;


25.    What is 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 value, and md5() returns a 160 bit value. This is important when avoiding collisions.


26.    How many ways we can we find the current date using MySQL? 

    SELECT CURDATE();
    SELECT CURRENT_DATE();
    SELECT CURTIME();
    SELECT CURRENT_TIME();


27.    Give the syntax of GRANT commands? 
    
    The generic syntax for GRANT is as following

    GRANT [rights] on [database] TO [username@hostname] IDENTIFIED BY [password]

    Now rights can be:
    a) ALL privilages
    b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.

    We can grant rights on all databse by usingh *.* or some specific database by database.* or a specific table by database.table_name.


28.    How many values can the SET function of MySQL take? 

    MySQL SET function can take zero or more values, but at the maximum it can take 64 values.


29.    Give the syntax of REVOKE commands? 

    * Collapse/Expand Answer of Question Give the syntax of REVOKE commands?

    The generic syntax for revoke is as following

    REVOKE [rights] on [database] FROM [username@hostname]

    Now rights can be:
    a) ALL privilages
    b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.

    We can grant rights on all databse by usingh *.* or some specific database by database.* or a specific table by database.table_name.


30.    What is the use of header() function in php? 

    The header() function sends a raw HTTP header to a client.We can use herder() function for redirection of pages. It is important to notice that header() must be called before any actual output is seen.


    simply,it is used for redirect the page.if you want to redirect one page to another we can use it….
    


31. How can we repair a MySQL table?

    The syntex for repairing a mysql table is:

    REPAIR TABLE tablename
    REPAIR TABLE tablename QUICK
    REPAIR TABLE tablename EXTENDED

    This command will repair the table specified.
    If QUICK is given, MySQL will do a repair of only the index tree.
    If EXTENDED is given, it will create index row by row.


32.    What is meant by nl2br()? 

    nl2br() inserts a HTML tag <br> before all new line characters 'n' in a string.

    echo nl2br("god bless n you");

    output:
    god bless<br>
    you


33.    Explain the ternary conditional operator in PHP?

    Expression preceding the ? is evaluated, if it?s true, then the expression preceding the : is executed, otherwise, the expression following : is executed.

    The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.
    Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
    
    <?php
        $action = (empty($_POST[‘action’])) ? ‘default’ : $_POST[‘action’];

        if (empty($_POST[‘action’])) {
            echo "<br>".$action = 'default';            
        } else {
            echo "<br>".$action = $_POST[‘action’];
        }
    ?>


34.    What Is a Persistent Cookie in PHP? 

    A persistent cookie is a cookie which is stored in a cookie file permanently on the browser's computer. By default, cookies are created as temporary cookies which stored only in the browser's memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:

    * Temporary cookies can not be used for tracking long-term information.
    * Persistent cookies can be used for tracking long-term information.
    * Temporary cookies are safer because no programs other than the browser can access them.
    * Persistent cookies are less secure because users can open cookie files see the cookie values.


35.    What is htaccess?

    A) Using this ".htaccess" file we can control "php.ini" and "httpd.conf" file.

    For php.ini:

    for register globals Enter "php_flag register_globals on" in that file and place it inside the context folder where you are running the php files. Now this is set to globals throughout the files present inside that context folder. This is boolean so we are giving like "php_flag". if it is the value we have to give like "php_value"

    For example : [php_value sendmail_from “dineshsdk85@gmail.com”] we have to give like this for the values

    B) .htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. 
    In several web servers (most commonly Apache), .htaccess (hypertext access) is the default name of a directory-level configuration file that allows for decentralized management of web server configuration. The .htaccess file is placed inside the web tree, and is able to override a subset of the server's global configuration; the extent of this subset is defined by the web server administrator.[1] The original purpose of .htaccess was to allow per-directory access control (e.g. requiring a password to access the content), hence the name. Nowadays .htaccess can override many other configuration settings, mostly related to content control, e.g. content type and character set, CGI handlers, etc.


36.    Explain about Type Juggling in php?

    PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable $var, $var becomes a string. If you then assign an integer value to $var, it becomes an integer.

    An example of PHP's automatic type conversion is the addition operator '+'. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated.

    $foo += 2; // $foo is now an integer (2)
    $foo = $foo + 1.3; // $foo is now a float (3.3)
    $foo = 5 + "10 Little Piggies"; // $foo is integer (15)
    $foo = 5 + "10 Small Pigs"; // $foo is integer (15)

    If the last two examples above seem odd, see String conversion to numbers.
    If you wish to change the type of a variable, see settype().
    If you would like to test any of the examples in this section, you can use the var_dump() function.
    Note: The behavior of an automatic conversion to array is currently undefined.

    Since PHP (for historical reasons) supports indexing into strings via offsets using the same syntax as array indexing, the example above leads to a problem: should $a become an array with its first element being "f", or should "f" become the first character of
 


37.    How can I use the COM components in php? 

    The COM class provides a framework to integrate (D)COM components into your PHP scripts.
    string COM::COM( string module_name [, string server_name [, int codepage]]) – COM class constructor.

    Parameters:

    module_name: name or class-id of the requested component.
    server_name: name of the DCOM server from which the component should be fetched. If NULL, localhost is assumed. To allow DCOM com, allow_dcom has to be set to TRUE in php.ini.
    codepage – specifies the codepage that is used to convert php-strings to unicode-strings and vice versa. Possible values are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 and CP_UTF8.
    Usage:
    $word->Visible = 1; //open an empty document
    $word->Documents->Add(); //do some weird stuff
    $word->Selection->TypeText("This is a test?");
    $word->Documents[1]->SaveAs("Useless test.doc"); //closing word
    $word->Quit(); //free the object
    $word->Release();
    $word = null;


38.    How can increase the performance of MySQL select query?

    We can use LIMIT to stop MySql for further search in table after we have received our required no. of records, also we can use LEFT JOIN or RIGHT JOIN instead of full join in cases we have related data in two or more tables.


39.    What type of inheritance that php supports? 

    In PHP an extended class is always dependent on a single base class, that is, multiple inheritance is not supported. Classes are extended using the keyword 'extends'.
    


40.    WHAT TYPES OF IMAGES THAT PHP SUPPORTS?

    Using imagetypes() function to find out what types of images are supported in your PHP engine.
    imagetypes() – Returns the image types supported.
    This function returns a bit-field corresponding to the image formats supported by the version of GD linked into PHP. The following bits are returned, IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM.


41.    How to use PHP to delete cookies when browser is close?.is it possible?

    When browser is closed automatically the cookies are deleted.

    If u want to delete before User's close the browser,you can use the time limit in $_COOKIE variable.

    Syntax : $_COOKIE[‘name’,’value’,’time’]

    Ex:To create cookie
    $_COOKIE[‘sumathi,’10’,time()+3600];

    so after 1 hour(3600 seconds) cookies will be deleted.

    Ex:to delete the cookie completely
    $_COOKIE[‘sumathi’,’10’time()-3600];

    The above exmaple will unset the cookie immediately.


42.    How To Read the Entire File into a Single String? 

    If you have a file, and you want to read the entire file into a single string, you can use the file_get_contents() function. It opens the specified file, reads all characters in the file, and returns them in a single string. Here is a PHP script example on how to file_get_contents():

    <?php
        $file = file_get_contents("/windows/system32/drivers/etc/services");
        print("Size of the file: ".strlen($file)."n");
    ?>

    This script will print: Size of the file: 7116


43.    What is the maximum length of a table name, a database name, or a field name in MySQL? 

    Database name:    64 characters
    Table name:     64 characters
    Column name:    64 characters


Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>