Wednesday 25 January 2012

PHp Interview Questions - Part-2


  1. I am writing an application in PHP that outputs a printable version of driving directions. It contains some long sentences, and I am a neat freak, and would like to make sure that no line exceeds 50 characters. How do I accomplish that with PHP?
    On large strings that need to be formatted according to some length specifications, use wordwrap() or chunk_split().
  2. What’s the output of the ucwords function in this example?
    $formatted = ucwords("TECHPREPARATIONS IS COLLECTION OF INTERVIEW QUESTIONS");
    print $formatted;
    What will be printed is TECHPREPARATIONS IS COLLECTION OF INTERVIEW QUESTIONS.
    ucwords() makes every first letter of every word capital, but it does not lower-case anything else. To avoid this, and get a properly formatted string, it’s worth using strtolower() first.
  3. What’s the difference between htmlentities() and htmlspecialchars()?
    htmlspecialchars only takes care of <, >, single quote ‘, double quote " and ampersand. htmlentities translates all occurrences of character sequences that have different meaning in HTML.
  4. How can we extract string "abc.com" from a string "mailto:info@abc.com?subject=Feedback" using regular expression of PHP?
    $text = "mailto:info@abc.com?subject=Feedback";
    preg_match('|.*@([^?]*)|', $text, $output);
    echo $output[1];

    Note that the second index of $output, $output[1], gives the match, not the first one, $output[0].
  5. So if md5() generates the most secure hash, why would you ever use the less secure crc32() and sha1()?
    Crypto usage in PHP is simple, but that doesn’t mean it’s free. First off, depending on the data that you’re encrypting, you might have reasons to store a 32-bit value in the database instead of the 160-bit value to save on space. Second, the more secure the crypto is, the longer is the computation time to deliver the hash value. A high volume site might be significantly slowed down, if frequent md5() generation is required.
  6. How can we destroy the session, how can we unset the variable of a session?session_unregister() - Unregister a global variable from the current session
    session_unset() - Free all session variables
  7. What are the different functions in sorting an array?
    Sorting functions in PHP:
    asort()
    arsort()
    ksort()
    krsort()
    uksort()
    sort()
    natsort()
    rsort()
  8. How can we know the count/number of elements of an array?
    2 ways:
    a) sizeof($array) - This function is an alias of count()
    b) count($urarray) - This function returns the number of elements in an array.
    Interestingly if you just pass a simple var instead of an array, count() will return 1.
  9. How many ways we can pass the variable through the navigation between the pages?
    At least 3 ways:

    1. Put the variable into session in the first page, and get it back from session in the next page.
    2. Put the variable into cookie in the first page, and get it back from the cookie in the next page.
    3. Put the variable into a hidden form field, and get it back from the form in the next page.
  10. 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
  11. 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.
  12. What are the other commands to know the structure of a table using MySQL commands except EXPLAIN command?
    DESCRIBE table_name;
  13. How can we find the number of rows in a table using MySQL?
    Use this for MySQL

    SELECT COUNT(*) FROM table_name;
  14. 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 value, and md5() returns a 160 bit value. This is important when avoiding collisions.
  15. How can we find the number of rows in a result set using PHP?
    Here is how can you find the number of rows in a result set in PHP:

    $result = mysql_query($any_valid_sql, $database_link);
    $num_rows = mysql_num_rows($result);
    echo "$num_rows rows found";
  16. How many ways we can we find the current date using MySQL?
    SELECT CURDATE();
    SELECT CURRENT_DATE();
    SELECT CURTIME();
    SELECT CURRENT_TIME();
  17. 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.
  18. 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 privileges
    b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.

    We can grant rights on all database by using *.* or some specific database by database.* or a specific table by database.table_name.
  19. What is the difference between CHAR and VARCHAR data types?
    CHAR is a fixed length data type. CHAR(n) will take n characters of storage even if you enter less than n characters to that column. For example, "Hello!" will be stored as "Hello! " in CHAR(10) column.

    VARCHAR is a variable length data type. VARCHAR(n) will take only the required storage for the actual number of characters entered to that column. For example, "Hello!" will be stored as "Hello!" in VARCHAR(10) column.
  20. How can we encrypt and decrypt a data present in a mysql table using mysql?
    AES_ENCRYPT() and AES_DECRYPT()
  21. Will comparison of string "10" and integer 11 work in PHP?
    Yes, internally PHP will cast everything to the integer type, so numbers 10 and 11 will be compared.
  22. What is the functionality of MD5 function in PHP?
    string md5(string)

    It calculates the MD5 hash of a string. The hash is a 32-character hexadecimal number.
  23. How can I load data from a text file into a table?
    The MySQL provides a LOAD DATA INFILE command. You can load data from a file. Great tool but you need to make sure that:

    a) Data must be delimited
    b) Data fields must match table columns correctly
  24. How can we know the number of days between two given dates using MySQL?
    Use DATEDIFF()

    SELECT DATEDIFF(NOW(),'2006-07-01');
  25. How can we change the name of a column of a table?
    This will change the name of column:

    ALTER TABLE table_name CHANGE old_colm_name new_colm_name
  26. How can we change the data type of a column of a table?
    This will change the data type of a column:

    ALTER TABLE table_name CHANGE colm_name same_colm_name [new data type]
  27. What is the difference between GROUP BY and ORDER BY in SQL?
    To sort a result, use an ORDER BY clause.
    The most general way to satisfy a GROUP BY clause is to scan the whole table and create a new temporary table where all rows from each group are consecutive, and then use this temporary table to discover groups and apply aggregate functions (if any).
    ORDER BY [col1],[col2],...[coln]; Tells DBMS according to what columns it should sort the result. If two rows will have the same value in col1 it will try to sort them according to col2 and so on.
    GROUP BY [col1],[col2],...[coln]; Tells DBMS to group (aggregate) results with same value of column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if you want to count all items in group, sum all values or view average.
  28. What is meant by MIME?
    Answer 1:
    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
    application/x-shockwave-flash

    Answer 2:
    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. …
  29. How can we know that a session is started or not?A session starts by session_start() function.
    This session_start() is always declared in header portion. it always declares first. then we write session_register().
  30. What are the differences between  mysql_fetch_array(),  mysql_fetch_object(),  mysql_fetch_row()?
    Answer 1:
    mysql_fetch_array() -> Fetch a result row as a combination of associative array and regular array.
    mysql_fetch_object() -> Fetch a result row as an object.
    mysql_fetch_row() -> Fetch a result set as a regular array().

    Answer 2:
    The difference between mysql_fetch_row() and mysql_fetch_array() is that the first returns the results in a numeric array ($row[0], $row[1], etc.), while the latter returns a the results an array containing both numeric and associative keys ($row['name'], $row['email'], etc.). mysql_fetch_object() returns an object ($row->name, $row->email, etc.).
  31. If we login more than one browser windows at the same time with same user and after that we close one window, then is the session is exist to other windows or not? And if yes then why? If no then why?
    Session depends on browser. If browser is closed then session is lost. The session data will be deleted after session time out. If connection is lost and you recreate connection, then session will continue in the browser.
  32. What are the MySQL database files stored in system ?
    Data is stored in name.myd
    Table structure is stored in name.frm
    Index is stored in name.myi
  33. What is the difference between PHP4 and PHP5?
    PHP4 cannot support oops concepts and Zend engine 1 is used.

    PHP5 supports oops concepts and Zend engine 2 is used.
    Error supporting is increased in PHP5.
    XML and SQLLite will is increased in PHP5.
  34. Can we use include(abc.PHP) two times in a PHP page makeit.PHP”?
    Yes we can include that many times we want, but here are some things to make sure of:
    (including abc.PHP, the file names are case-sensitive)
    there shouldn't be any duplicate function names, means there should not be functions or classes or variables with the same name in abc.PHP and makeit.php
  35. What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?
    mysql_fetch_array - Fetch a result row as an associative array and a numeric array.

    mysql_fetch_object - Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows

    mysql_fetch_row() - Fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
  36. What is meant by nl2br()?
    Anwser1:
    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
  37. How can we encrypt and decrypt a data presented in a table using MySQL?
    You can use functions: AES_ENCRYPT() and AES_DECRYPT() like:

    AES_ENCRYPT(str, key_str)
    AES_DECRYPT(crypt_str, key_str)
  38. How can I retrieve values from one database server and store them in other database server using PHP?
    For this purpose, you can first read the data from one server into session variables. Then connect to other server and simply insert the data into the database
  39. Who is the father of PHP and what is the current version of PHP and MYSQL?Rasmus Lerdorf.
    PHP 5.1. Beta
    MySQL 5.0
  40. In how many ways we can retrieve data in the result set of MYSQL using PHP?
    mysql_fetch_array - Fetch a result row as an associative array, a numeric array, or both
    mysql_fetch_assoc - Fetch a result row as an associative array
    mysql_fetch_object - Fetch a result row as an object
    mysql_fetch_row —- Get a result row as an enumerated array
  41. What are the functions for IMAP?
    imap_body - Read the message body
    imap_check - Check current mailbox
    imap_delete - Mark a message for deletion from current mailbox
    imap_mail - Send an email message
  42. What are encryption functions in PHP?
    CRYPT()
    MD5()
  43. What is the difference between htmlentities() and htmlspecialchars()?
    htmlspecialchars() - Convert some special characters to HTML entities (Only the most widely used)
    htmlentities() - Convert ALL special characters to HTML entities
  44. What is the functionality of the function htmlentities?
    htmlentities() - Convert all applicable characters to HTML entities
    This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.
  45. How can we get the properties (size, type, width, height) of an image using php image functions?
    To know the image size use getimagesize() function
    To know the image width use imagesx() function
    To know the image height use imagesy() function
  46. How can we increase the execution time of a php script?
    By the use of void set_time_limit(int seconds)
    Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini. If seconds is set to zero, no time limit is imposed.

    When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.
  47. HOW CAN WE TAKE A BACKUP OF A MYSQL TABLE AND HOW CAN WE RESTORE IT?
    Answer 1:
    Create a full backup of your database: shell> mysqldump tab=/path/to/some/dir opt db_name
    Or: shell> mysqlhotcopy db_name /path/to/some/dir
    The full backup file is just a set of SQL statements, so restoring it is very easy:

    shell> mysql "."Executed";

    Answer 2:
    To backup: BACKUP TABLE tbl_name TO /path/to/backup/directory
    ’ To restore: RESTORE TABLE tbl_name FROM /path/to/backup/directory

    mysqldump: Dumping Table Structure and Data

    Utility to dump a database or a collection of database for backup or for transferring the data to another SQL server (not necessarily a MySQL server). The dump will contain SQL statements to create the table and/or populate the table.
    -t, no-create-info
    Don't write table creation information (the CREATE TABLE statement).
    -d, no-data
    Don't write any row information for the table. This is very useful if you just want to get a dump of the structure for a table!
  48. How to set cookies?
    setcookie('variable','value','time')
    ;
    variable - name of the cookie variable
    value - value of the cookie variable
    time - expiry time
    Example: setcookie('Test',$i,time()+3600);

    Test - cookie variable name
    $i - value of the variable 'Test'
    time()+3600 - denotes that the cookie will expire after an one hour
  49. How to reset/destroy a cookie ?Reset a cookie by specifying expire time in the past:
    Example: setcookie('Test',$i,time()-3600); // already expired time

    Reset a cookie by specifying its name only
    Example: setcookie('Test');
  50. 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.

No comments:

Post a Comment