Thursday, June 2, 2016

PHP Interview Questions Part 6

1) What is the use of “Final class” and can a final class be an abstract?

(Ans) The “Final” keyword is used to make the class un-inheritable. So the class or it’s methods can not be overridden.
final class Class1 {
// ...
}

class FatalClass extends Class1 {
// ...
}

$out= new FatalClass();

An Abstract class will never be a final class as an abstract class must be extendable.

2) How can we know the number of days between two given dates using PHP?

(Ans) 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”;

3)  How To Write the FORM Tag Correctly for Uploading Files?

(Ans) 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) Consider the following code snippet. Is this code acceptable from a security standpoint?

Assume that the $action and $data variables are designed to be accepted from the user and
register_globals is enabled.

<?php
if(isUserAdmin()) {
$isAdmin = true;
}
$data = validate_and_return_input($data);
switch($action){
case add:
addSomething($data);
break;
case delete:
if($isAdmin) {
deleteSomething($data);
}
break;
case edit:
if($isAdmin) {
editSomething($data);
}
break;
default:
print “Bad Action.”;
}
?>

A. Yes, it is secure. It checks for $isAdmin to be True before executing protected operations
B. No, it is not secure because it doesn’t make sure $action is valid input
C. No, it is not secure because $isAdmin can be hijacked by exploiting register_globals
D. Yes, it is secure because it validates the user-data $data
E. Both A and B

(Ans) The correct answer is C. This code is, by any means, not secure! In fact, it is the classic security exploit of PHP scripts using the register_globals configuration directive. The problem lies in the $isAdmin variable: although this is clearly a Boolean value, it is only set in the event that the user is an Admin and not set at all if the user is not. Because register_globals is enabled, by simply appending that variable to the end of the URL as a GET parameter, a malicious user could easily impersonate an administrator.


5) Which of the following will not combine strings $s1 and $s2 into a single string?
$s1 = a;
$s2 = b;
A. $s1 + $s2
B. "{$s1}{$s2}"
C. $s1.$s2
D. implode(, array($s1,$s2))
E. All of the above combine the strings

(Ans) You can not concatenate 2 string using “+”. The answer will be “0?; so here the answer is A.

6) Consider the following php script. What line of code should be inserted in the marked location in order to display the string php when this script is executed?

$alpha = abcdefghijklmnopqrstuvwxyz;
$letters = array(15, 7, 15);
foreach($letters as $val) {
/* What should be here */
}
A. echo chr($val);
B. echo asc($val);
C. echo substr($alpha, $val, 2);
D. echo $alpha{$val};
E. echo $alpha{$val+1}

(Ans) The answer is D. An array can be accessed like this as well. $alpha{$val}

7)  How can I execute a PHP script using command line?

(Ans) Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, "php myScript.php", assuming "php" is the command to invoke the CLI program.Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment.

8) I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem?

(Ans) PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems.

9) Would I use print "$a dollars" or "{$a} dollars" to print out the amount of dollars in this example?

(Ans) In this example it wouldn’t matter, since the variable is all by itself, but if you were to print something like "{$a},000,000 mln dollars", then you definitely need to use the braces.

10) What are the different types of errors in PHP?

(Ans) Here are three basic types of runtime 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 behavior.

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 behavior is to display them to the user when they take place.

Internally, these variations are represented by twelve different error types.

11) What is the maximum size of a file that can be uploaded using PHP and how can we change this?

(Ans) By default the maximum size is 2MB,and we can change the following setup at php.iniupload_max_filesize = 2M

12) How can we get the browser properties using PHP?

(Ans)     By using
$_SERVER[HTTP_USER_AGENT]
variable.

13) What is session_set_save_handler in PHP?

(Ans) session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a local database.

14) How can I retrieve values from one database server and store them in other database server using PHP?

(Ans) We can always fetch from one database and rewrite to another.
Here is a nice solution of it.

$db1 = mysql_connect("host","user","pwd")
mysql_select_db("db1", $db1);
$res1 = mysql_query("query",$db1);$db2 = mysql_connect("host","user","pwd")
mysql_select_db("db2", $db2);
$res2 = mysql_query("query",$db2);
 At this point you can only fetch records from you previous ResultSet, i.e $res1. But you cannot execute new query in $db1, even if you supply the link as because the link was overwritten by the new db.so at this point the following script will fail.
$res3 = mysql_query("query",$db1); //this will failSo how to solve that?

Take a look below:

$db1 = mysql_connect("host","user","pwd")
mysql_select_db("db1", $db1);
$res1 = mysql_query("query",$db1);
$db2 = mysql_connect("host","user","pwd", true)
mysql_select_db("db2", $db2);
$res2 = mysql_query("query",$db2);
 So mysql_connect has another optional boolean parameter which indicates whether a link will be created or not. as we connect to the $db2 with this optional parameter set to true, so both link will remain live.

Now the following query will execute successfully.

$res3 = mysql_query("query",$db1);

 15)  How can we extract string "abc.com" from a string "mailto:info@abc.com?subject=Feedback" using regular expression of PHP?

(Ans) Try this:
$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].

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.

Enjoy!

Still more to come.Wait for the next part.You can also subscribe below to receive the next part of "PHP Interview Questions" series directly in your email.

Cheers!