Sunday, February 20, 2011

PHP Interview Questions

 ---------------------------PHP ---------------------------

PHP
PHP (Hypertext Pre Processor) is a scripting language commonly used for web applications. PHP can be easily embedded in HTML. PHP generally runs on a web server. It is available for free and can be used across a variety of servers, operating systems and platforms.

What does a special set of tags <?= and ?> do in PHP?
The output is displayed directly to the browser
What’s new in PHP5?
Xml functions
OOP concept have newly introduced constructors, destructors and interfaces
Uses Zend engine 2.0
Supports MySQLi

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.
Alphanumeric characters are maintained as is.
Space characters are converted to “+” characters.
Other non-alphanumeric characters are converted “%” followed by two hex digits representing the converted character.

How to Get the Uploaded File Information in the Receiving Script?
Once the Web server received the uploaded file, it will call the PHP script specified in the form action attribute to process them. This receiving PHP script can get the uploaded file information through the predefined array called $_FILES.
We must use enctype="multipart/form-data" with the form
Uploaded file information is organized in $_FILES as a two-dimensional array as:
$_FILES[$fieldName]['name'] – The Original file name on the browser system.
$_FILES[$fieldName]['type'] – The file type determined by the browser.
$_FILES[$fieldName]['size'] – The Number of bytes of the file content.
$_FILES[$fieldName]['tmp_name'] – The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES[$fieldName]['error'] – The error code associated with this file upload.
The $fieldName is the name used in the <INPUT TYPE=FILE, NAME=fieldName> 

What is enctype? 
The enctype attribute specifies how form-data should be encoded before sending it to the server.
The form-data is encoded to "application/x-www-form-urlencoded" by default. This means that all characters are encoded before they are sent to the server (spaces are converted to "+" symbols, and special characters are converted to ASCII HEX values).
application/x-www-form-urlencoded - All characters are encoded before sent (this is default)
multipart/form-data - No characters are encoded. This value is required when you are using forms that have a file upload control
text/plain - Spaces are converted to "+" symbols, but no special characters are encoded

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().

What are the different types of errors in php?
1. 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 you can change this default behaviour.
2. 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.
3. 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.

How many ways can we pass the variable through the navigation between the pages?
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.

How can we start/stop sessions ?
session_ start();
$_SESSION['dpk'] ='dpk';
session_unset();

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

How can we increase the execution time of a php script?
By the use of void set_time_limit(int seconds)
Check if a variable is an integer in JAVASCRIPT ?
var myValue =9.8;
if(parseInt(myValue)== myValue)
alert(‘Integer’);
else
alert(‘Not an integer’)

What’s the difference between accessing a class method via -> and via ::?
:: is allowed to access methods that can perform static operations, i.e. those, which do not require object initialization

What is the difference between include and require?
It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue

What is the difference between $message and $$message?
$message is a simple variable whereas $$message is a reference variable. Example:
$user = 'bob'
is equivalent to
$holder = 'user';
$$holder = 'bob';

If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b?
100, it’s a reference to existing variable.

How do you pass a variable by value?
Just like in C++, put an ampersand in front of it, like $a = &$b

Will comparison of string "10" and integer 11 works in PHP?
Yes, internally PHP will cast everything to the integer type, so numbers 10 and 11 will be compared.

When are you supposed to use endif to end the conditional statement?
There are 2 methods of using if statement-
1.       Using braces if() {…..}
2.       Using if() :    …….   endif;
The given scenario belong to the second method

Are objects passed by value or by reference?
Everything is passed by value.

What is a Session?
A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests.
There is only one session object available to your PHP scripts at any time. Data saved to the session by a script can be retrieved by the same script or another script when requested from the same visitor.
Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.

What is meant by PEAR in php?
This repository is bringing higher level programming to PHP.
PEAR is a framework and distribution system for reusable PHP components.
PEAR also provides a command-line interface that can be used to automatically install "packages"
PEAR is short for "PHP Extension and Application Repository" and is pronounced just like the fruit.

How can we know the number of days between two given dates using PHP?
Simple arithmetic:
$date1 = date('Y-m-d');
$date2 = '2006-07-01';
$days = (strtotime() - strtotime()) / (60 * 60 * 24);
echo "Number of days since '2006-07-01': $days";

How do you define a constant?            
Via define() directive, like define ("MYCONSTANT", 100);
If a number starts with zero in php it becomes octal
If it starts with x it is hexadecimal

File handling
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
$data = fread($handle,filesize($my_file));
$data = 'This is the data';
fwrite($handle, $data);
fclose($handle);
unlink($my_file);

Cookie and session
The key difference would be cookies are stored in client side and sessions are stored in server side. The second difference would be cookies can only store strings. We can store our objects in sessions. Storing objects in sessions were really useful according to my experience. Another difference was that we could be save cookie for future reference, but session couldn’t. When users close their browser, they also lost the session.

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.
$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)

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.

Where is the php.ini file located?
We can easily find the location of php.ini using phpinfo() function. It is actually located inside wamp/bin/php

What type of headers has to be added in the mail function to attach a file?
$boundary = '--' . md5( uniqid ( rand() ) );
$headers = "From: \"Me\"\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"";

What are encryption functions in PHP?
CRYPT()
MD5()

How to set cookies?
setcookie('variable','value','time')

How to reset/destroy a cookie ?
Reset a cookie by specifying its name only
Example: setcookie('Test');

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.

How many ways can we get the value of current session id?
session_id() returns the session id for the current session.

How can we know the count/number of elements of an array?
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.

How can we find the number of rows in a result set using PHP?
$result = mysql_query($any_valid_sql, $database_link);
$num_rows = mysql_num_rows($result);

Would you initialize your strings with single quotes or double quotes?
Since the data inside the single-quoted string is not parsed for variable substitution, it’s always a better idea speed-wise to initialize a string with single quotes, unless you specifically need variable substitution.

How do I find out the number of parameters passed into function ?
func_num_args() function returns the number of parameters passed in.

How do you call a constructor for a parent class?
parent::constructor($value)

How to store the uploaded file to the final location?
move_uploaded_file ( string filename, string destination)

Why doesn’t the following code print the newline properly? <?php $str = 'Hello, there.\nHow are you?\nThanks for visiting techpreparation'; print $str; ?> ?
Because inside the single quotes the \n character is not interpreted as newline, just as a sequence of two characters - \ and n.

Difference between split() and explode() ?
split() can work using regular expressions while explode() cannot.

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

Difference between echo and print and printf ?
echo is the most primitive of them, and just outputs the contents following the construct to the screen. echo is also the fastest method for printing. print is also a construct (so parentheses are optional when calling it), but it returns TRUE on successful output and FALSE if it was unable to print out the string.
However, you can pass multiple parameters to echo, like:
 <?php echo 'Welcome ', 'to', ' ', 'dpkhere com!'; ?>
and it will output the string "Welcome to dpkhere com!" print does not take multiple parameters.
Printf is not a construct but a function; and it’s the slowest method for printing data

What is the functionality of the functions STRSTR() and STRISTR()?
string strstr ( string haystack, string needle ) returns part of haystack string from the first occurrence of needle to the end of haystack. This function is case-sensitive.
stristr() is identical to strstr() except that it is case insensitive

What are the differences between GET and POST methods in form submitting, give the case where we can use GET and we can use POST methods?
When we submit a form, which has the GET method it displays pair of name/value used in the form at the address bar of the browser preceded by url. Post method doesn’t display these values.

What is the difference between the functions unlink and unset?
unlink() is a function for file system handling. It will simply delete the file in context.
unset() is a function for variable management. It will make a variable undefined

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

What Is a Persistent Cookie?
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 cannot 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.

What is the maximum size of a file that can be uploaded using PHP and how can we change this?
You can change maximum size of a file set upload_max_filesize variable in php.ini file

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'

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.

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.

What’s the special meaning of __sleep and __wakeup?
__sleep returns the array of all the variables than need to be saved, while __wakeup retrieves them.

What is meant by MIME?
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

What are the difference between abstract class and interface?
Abstract class: abstract classes are the class where one or more methods are abstract but not necessarily all method has to be abstract. Abstract methods are the methods, which are declare in its class but not define. The definition of those methods must be in its extending class.
Interface: Interfaces are one type of class where all the methods are abstract. That means all the methods only declared but not defined. All the methods must be defined by its implemented class. If a definition is given for a function inside an interface error will be produced.

I want to combine two variables together:
$var1 = 'Welcome to ';
$var2 = 'TechInterviews.com';
What will work faster?
Code sample 1: $var 3 = $var1.$var2;
Or code sample 2: $var3 = "$var1$var2";
Both examples would provide the same result - $var3 equal to "Welcome to TechInterviews.com". However, Code Sample 1 will work significantly faster. Try it out with large sets of data (or via concatenating small sets a million times or so), and you will see that concatenation works significantly faster than variable substitution.

How do you match the character ^ at the beginning of the string?
^^

 ---------------------------MySQL ---------------------------

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

What is the difference between mysql_fetch_object and mysql_fetch_array?
MySQL fetch object will collect first single matching record where mysql_fetch_array will collect all matching records from the table in an array

How can we encrypt the username and password using PHP?
You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD(“Password”);

Default table is myisam

Can we use order by in a delete query?
If the DELETE statement includes an ORDER BY clause, rows are deleted in the order specified by the clause. This is useful primarily in conjunction with LIMIT.
For example, the following statement finds rows matching the WHERE clause, sorts them by timestamp_column, and deletes the first (oldest) one:
DELETE FROM user WHERE user = 'jcole'
ORDER BY timestamp_column LIMIT 1;

Difference between primary key and unique key?
There can only one primary key. Any number of unique keys can be possible. A primary key can be combination of unique keys. There can be only one auto increment field for a table and if set it must be the primary key. Primary key is used to uniquely identify each and every row in a table.

Transactions
A transaction is simply a number of individual queries that are grouped together.
It’s started by BEGIN
Terminated by COMMIT
The queries run after the BEGIN will be temporary unless COMMIT is used
Changes can be reverted using ROLLBACK, must be used before COMMIT

What are the advantages of stored procedures, triggers, indexes?
A stored procedure is a set of SQL commands that can be compiled and stored in the server. Once this has been done, clients don't need to keep re-issuing the entire query but can refer to the stored procedure. This provides better overall performance because the query has to be parsed only once, and less information needs to be sent between the server and the client. However, stored procedures of course do increase the load on the database server system, as more of the work is done on the server side and less on the client (application) side.
A trigger is effectively a type of stored procedure, one that is invoked when a particular event occurs. For example, you can install a stored procedure that is triggered each time a record is deleted from a transaction table and that stored procedure automatically deletes the corresponding customer from a customer table when all his transactions are deleted. Indexes are used to find rows with specific column values quickly.
Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks.

Explain the difference between MySQL and MySQLi interfaces in PHP?
MySQLi (MySQL improved) is the object-oriented version of MySQL library functions. MySQLi is highly faster than MySQL
MySQLi has following:
Object-oriented interface
Support for Prepared Statements
Support for Multiple Statements
Support for Transactions
Enhanced debugging capabilities
Embedded server support

What’s the default port for MySQL Server?
3306

Explain advantages of MyISAM over InnoDB?
Much more conservative approach to disk space management - each MyISAM table is stored in a separate file, which could be compressed then with myisamchk if needed. With InnoDB the tables are stored in tablespace, and not much further optimization is possible. All data except for TEXT and BLOB can occupy 8,000 bytes at most. No full text indexing is available for InnoDB. The COUNT(*)s execute slower than in MyISAM due to tablespace complexity

Difference between myisam and InnoDB?
Myisam : MyISAM tables are split between three different files on the disk. One for the table format, another for the data, and lastly a third for the indexes. The maximum number of rows supported amounts to somewhere around ~4.295E+09 and can have up to 64 indexed fields per table. Both of these limits can be greatly increased by compiling a special version of MySQL. Text/Blob fields are able to be fully-indexed which is of great importance to search functions. Table locking. Full text search index
InnoDB : row locking. transaction-safe. ability to use foreign-key constraints. Better crash recovery.
  
What happens when the column is set to AUTO INCREMENT and you reach the maximum value for that table?
It stops incrementing. It does not overflow to 0 to prevent data losses, but further inserts are going to produce an error, since the key has been used already.

Explain the difference between FLOAT, DOUBLE and REAL. ?
FLOATs store floating point numbers with 8 place accuracy and take up 4 bytes. DOUBLE stores floating point numbers with 16 place accuracy and take up 8 bytes. REAL is a synonym of FLOAT for now.

If you specify the data type as DECIMAL (5,2), what’s the range of values that can go in this table?
999.99 to -99.99. Note that with the negative number the minus sign is considered one of the digits.

What happens if a table has one column defined as TIMESTAMP?
That field gets the current timestamp whenever the row gets altered.

If I created a column with data type VARCHAR(3), what would I expect to see in MySQL table?
CHAR(3), since MySQL automatically adjusted the data type.

How many ways we can we find the current date using MySQL?
SELECT CURDATE();
SELECT CURRENT_DATE();
SELECT CURTIME();
SELECT CURRENT_TIME();

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.

How can we know the number of days between two given dates using MySQL?
Use DATEDIFF()
SELECT DATEDIFF(NOW(),'2006-07-01');

What is the difference between GROUP BY and ORDER BY in SQL?
To sort a result, use an ORDER BY clause.
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.

What are the differences between DROP a table and TRUNCATE a table?
DROP TABLE table_name - This will delete the table and its data.
TRUNCATE TABLE table_name - This will delete the data of the table, but not the table definition.

 ---------------------------JavaScript ---------------------------

How can we submit a form without a submit button?
If you don’t want to use the Submit button to submit a form, you can use normal hyperlinks to submit a form. But you need to use some JavaScript code in the URL of the link. For example:
<a href=”javascript: document.myform.submit();”>Submit Me</a>

How can we send mail using JavaScript?
No. There is no way to send emails directly using JavaScript.
But you can use JavaScript to execute a client side email program send the email using the "mailto" code. Here is an example:
function myfunction(form)
{
tdata=document.myform.tbox1.value;
location="mailto:mailid@domain.com?subject=...";
return true;
}

What will the output for alert(2+3+'5') and alert(2+'3'+5) ?
55 and 235

 ---------------------------CSS ---------------------------

Difference between id and class?
Id cannot be used multiple times in an HTML page. If used the page will fail validation and will have negative effect while using JavaScript along with them. Id is usually used to uniquely identify the part of the page. Id can be used for positioning. We can give like <a href="#content"> to position the browser to that part of the page. Also a particular element cannot have multiple id.
Class can be used multiple times in an HTML page. Classes can not only be used more than once, but more than one can be used on an element.

If we use different definition for the same class which one will be taken?
The last one prevail
E.g.:
 #wearethesame{color:white;}
#wearethesame{color:black;}
Final color will be black

Difference between table and div?
Both are block elements. It is preferable to use div instead of table since table have cross browser issues. Still table is easier to implement than div

 ---------------------------Others ---------------------------

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 dependant on the primary key, but dependant on another value in the table

What are cron jobs?
CRON is the name of program that enables UNIX users to execute commands or scripts (groups of commands) automatically at a specified time/date.

Difference between http and https ?
Hypertext Transfer Protocol (http) is a system for transmitting and receiving information across the Internet. Http serves as a request and response procedure that all agents on the Internet follow so that information can be rapidly, easily, and accurately disseminated between servers, which hold information, and clients, who are trying to access it. Http is commonly used to access html pages, but other resources can be utilized as well through http. In many cases, clients may be exchanging confidential information with a server, which needs to be secured in order to prevent unauthorized access. For this reason, https, or secure http, was developed by Netscape Corporation to allow authorization and secured transactions.
There are some primary differences between http and https, however, beginning with the default port, which is 80 for http and 443 for https. S means secure

Who is the father of PHP and what is the current version of PHP and MYSQL?
Rasmus Lerdorf.
PHP 5.3.5
MySQL 5.5.8

How many ways I can redirect a PHP page?
1. Using Java script:
'; echo 'window.location.href="'.$filename.'";'; echo ''; echo ''; echo ''; echo ''; } } redirect('http://maosjb.com'); ?>
2. Using php function: header("Location:http://maosjb.com ");



                                                                                                                

No comments:

Post a Comment