Home

Showing posts with label Interview. Show all posts
Showing posts with label Interview. Show all posts

Monday, October 29, 2012

PHP Interview Questions


PHP Interview Questions 
1. What's PHP ?

The PHP Hypertext Preprocessor is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications.

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

$date1 = date('Y-m-d');
$date2 = '2006-07-01';
$days = (strtotime($date1) - strtotime($date2)) / (60 * 60 * 24);
echo "Number of days since '2006-07-01': $days";

3. How do you define a constant?
 define ("MYCONSTANT", 100);

4. 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.

5. How To Get the Uploaded File Information in the Receiving Script?

 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.

6. 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

7. How do you pass a variable by value?

Just like in C++, put an ampersand in front of it, like $a = &$b.

8. 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;
}

9. What is the difference between ereg_replace() and eregi_replace()?

eregi_replace() function is identical to ereg_replace() except that it ignores case distinction when matching alphabetic characters.

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

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

12. 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.

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

14. 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 hyper links to submit a form. But you need to use some JavaScript code in the URL of the link.
<a href="javascript: document.myform.submit();">Submit Me</a>

15. How can we extract string 'abc.com ' from a string http://info@abc.com using regular expression of php?

We can use the preg_match() function with "/.*@(.*)$/" as the regular expression pattern.
For example:
preg_match("/.*@(.*)$/","http://info@abc.com",$data);
echo $data[1];

16. 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.

17. What is the difference between characters \047 and \x47?
The first one is octal 47, the second is hex 47.

18. How can we create a database using PHP and mysql?

We can create MySQL database with the use of mysql_create_db($databaseName) to create a database.

19. 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

20. 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

21. 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.

22. What are the other commands to know the structure of a table using MySQL commands except EXPLAIN command?

DESCRIBE table_name;

23. How can we find the number of rows in a table using MySQL?

SELECT COUNT(*) FROM table_name;

24. 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);
echo "$num_rows rows found";

25. 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.

26. 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.

27. 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

28. How can we get the properties (size, type, width, height) of an image using php image functions?

image size use getimagesize() function
image width use imagesx() function
image height use imagesy() function

29. How can we increase the execution time of a php script?

By the use of void set_time_limit(int seconds)

30. 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 define by its implemented class.

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

change maximum size of a file set upload_max_filesize variable in php.ini file

32. 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.

33. What’s 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.

34. How many ways can we get the value of current session id?

session_id() returns the session id for the current session.

35. What is the difference between $message and $$message?

They are both variables. But $message is a variable with a fixed name. $$message is a variable who's name is stored in $message. For example, if $message contains "var", $$message is the same as $var.

36. How can we get the browser properties using php?

<?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";
$browser = get_browser(null, true);
print_r($browser);
?>

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

38. 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.

39. What is the difference between Split and Explode?

split()-used for JavaScript for processing the string and the explode()-used to convert the String to Array, implode()-used for convert the array to String
Here the Example
<?php
$x="PHP is a ServerSide Scripting Language";
$c=explode(" ",$x);
print_r($c);
$d=implode(" ",$c);
echo "
".$d;
?>
Javascript Example:
list($month, $day, $year) = split('[/.-]', $date);

40. Which will execute faster on php POST or GET?

Both are same while performing the action but using POST security is there.
Because using GET method in the action, form field values send along with URL, so at the time of sending password, problem will occur means password also will shown in the URL.
Using of POST there is no problem.

GET method has a limit of sending parameters 100 characters but POST method does not have a limit of sending data

GET is faster than POST. Because GET fetch the data directly from the URL but POST method fetch the encrypted data from the page.

41. What is the use of sprintf() function?

The sprintf() function writes a formatted string to a variable.

42. What Is a Session?

Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.

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

The header() function is used for redirect the page.if you want to redirect one page to another we can use it.

44. How can i get ip address?

REMOTE_ADDR - the IP address of the client
REMOTE_HOST - the host address of the client

45. What is htaccess?

.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis.

46. What is the diffrence between Notify URL and Return URL?

Notify URL is used to just notify the status while processing.
Return URL is used to return after processing.

47. What is the difference between ucfirst and ucwords?

ucfirst() to convert the first letter of every string to uppercase, and ucwords(), to convert the first letter of every word in the string to uppercase.

48. What is meant by nl2br()?

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

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

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

50. What are the different functions in sorting an array?

Sorting functions in PHP:
asort()
arsort()
ksort()
krsort()
uksort()
sort()
natsort()
rsort()  

Monday, December 26, 2011

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

imap_body &ndash; Read the message body
imap_check &ndash; Check current mailbox
imap_delete &ndash; Mark a message for deletion from current mailbox
imap_mail &ndash; Send an email message

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’); 

What are the features and advantages of OBJECT ORIENTED PROGRAMMING?

One of the main advantages of OO programming is its ease of modification; objects can easily be modified and added to a system there by reducing maintenance costs. OO programming is also considered to be better at modeling the real world than is procedural programming. It allows for more complicated and flexible interactions. OO systems are also easier for non-technical personnel to understand and easier for them to participate in the maintenance and enhancement of a system because it appeals to natural human cognition patterns. For some systems, an OO approach can speed development time since many objects are standard across systems and can be reused. Components that manage dates, shipping, shopping carts, etc. can be purchased and easily modified for a specific system.

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


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 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’.

Thursday, October 20, 2011

How to find second highest salary in mysql

select max(sal) from salary where sal not in (select max(sal) from salary )

Thursday, May 26, 2011

PHP cURL functions tutorial

cURL is a library which allows you to connect and communicate to many different types of servers with many different types of protocols. Using cURL you can:
  • Implement payment gateways’ payment notification scripts.
  • Download and upload files  from remote servers.
  • Login to other websites and access members only sections.
PHP cURL library is definitely the odd man out. Unlike other PHP libraries where a whole plethora of functions is made available, PHP cURL wraps up a major parts of its functionality in just four functions.
A typical PHP cURL usage follows the following sequence of steps.
curl_init – Initializes the session and returns a cURL handle which can be passed to other cURL functions.
curl_opt – This is the main work horse of cURL library. This function is called multiple times and specifies what we want the cURL library to do.
curl_exec – Executes a cURL session.
curl_close – Closes the current cURL session.
Below are some examples which should make the working of cURL more clearer.
The below piece of PHP code uses cURL to download Google’s RSS feed.
<?php
/**
* Initialize the cURL session
*/

$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/

curl_setopt($ch, CURLOPT_URL,
‘http://news.google.com/news?hl=en&topic=t&output=rss’);
/**
* Ask cURL to return the contents in a variable
* instead of simply echoing them to the browser.
*/

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
/**
* Execute the cURL session
*/

$contents = curl_exec ($ch);
/**
* Close cURL session
*/

curl_close ($ch);
?>

As you can see, curl_setopt is the pivot around which the main cURL functionality revolves. cURL functioning is controlled by way of passing predefined options and values to this function.
The above code uses two such options.
  • CURLOPT_URL: Use it  to specify the URL which you want to process. This could be the URL of the file you want to download or it could be the URL of the script to which you want to post some data.
  • CURLOPT_RETURNTRANSFER: Setting this option to 1 will cause the curl_exec function to return the contents instead of echoing them to the browser.

MYSQL Coalesce Function

Table Contact_Info

Name Business_Phone Cell_Phone Home_Phone
Jeff 531-2531 622-7813 565-9901
Laura NULL 772-5588 312-4088
Peter NULL NULL 594-7477
and we want to find out the best way to contact each person according to the following rules:
1. If a person has a business phone, use the business phone number.
2. If a person does not have a business phone and has a cell phone, use the cell phone number.
3. If a person does not have a business phone, does not have a cell phone, and has a home phone, use the home phone number.
We can use the COALESCE function to achieve our goal:
SELECT Name, COALESCE(Business_Phone, Cell_Phone, Home_Phone) Contact_Phone
FROM Contact_Info;

Result:
Name Contact_Phone
Jeff 531-2531
Laura 772-5588
Peter 594-7477

MySQL ISNULL

Table Sales_Data

store_name Sales
Store A 300
Store B NULL
The following SQL,
SELECT SUM(ISNULL(Sales,100)) FROM Sales_Data;
returns 400. This is because NULL has been replaced by 100 via the ISNULL function.

SQL CASE

Table Store_Information

store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
San Francisco $300 Jan-08-1999
Boston $700 Jan-08-1999

if we want to multiply the sales amount from 'Los Angeles' by 2 and the sales amount from 'San Diego' by 1.5, we key in,
SELECT store_name, CASE store_name
  WHEN 'Los Angeles' THEN Sales * 2
  WHEN 'San Diego' THEN Sales * 1.5
  ELSE Sales
  END
"New Sales",
Date
FROM Store_Information

"New Sales" is the name given to the column with the CASE statement.
Result:
store_name New Sales Date
Los Angeles $3000 Jan-05-1999
San Diego $375 Jan-07-1999
San Francisco $300 Jan-08-1999
Boston $700 Jan-08-1999

Subquery

Table Store_Information

store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $300 Jan-08-1999
Boston $700 Jan-08-1999
Table Geography
region_name store_name
East Boston
East New York
West Los Angeles
West San Diego

SELECT SUM(Sales) FROM Store_Information
WHERE Store_name IN
(SELECT store_name FROM Geography
WHERE region_name = 'West')

Result:
SUM(Sales)
2050

Tuesday, April 5, 2011

what is the difference between union and union all

union is used to select distinct values from two tables 
where as union all is used to select all values including 
duplicates from the tables

Monday, April 4, 2011

Difference between include() and include_once() in php

function.php
<?php
function foo(){
echo 'some code';
}
?>
Global.php
<?php
include('FUNCTIONS.PHP');
foo();
?>
Header.php
<?php
include('FUNCTIONS.PHP');
include('GLOBALS.PHP');
foo();
?>

now if you try to open HEADER.PHP you will get an error because global.php includes function.php already. you will get an error saying that function foo() was already declared in global.php, and i also included in Header.php - which means i have included function.php two times.

so to be sure i only include function.php only ONE time, i should use the include_once() function, so my Header.php should look like this: 

Header.php
<?php
include_once('FUNCTIONS.PHP');
include('GLOBALS.PHP');
?>

now when i open Header.php, i will not get an error anymore because PHP knows to include the file function.php only ONCE  

 
rathoddhirendra.blogspot.com-Google pagerank and Worth