PHP – Interview Question

Interview Tips & Tricks —-

What is CAPTCHA?

CAPTCHA stands for Completely Automated Public Turing Test to tell Computers and Humans Apart. To prevent spammers from using bots to automatically fill out forms, CAPTCHA programmers will generate an image containing distorted images of a string of numbers and letters. Computers cannot determine what the numbers and letters are from the image but humans have great pattern recognition abilities and will be able to fairly accurately determine the string of numbers and letters. By entering the numbers and letters from the image in the validation field, the application can be fairly assured that there is a human client using it. To read more look here:

http://en.wikipedia.org/wiki/Captcha

What is difference between require_once(), require(), include().
Becouse above three function usely use to call a file in another file?

Difference between require() and require_once(): require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page). So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don’t include the file more times and you will not get the “function re-declared” error. Difference between require() and include() is that require() produces a FATAL ERROR if the file you want to include is not found, while include() only produces a WARNING. There is also include_once() which is the same as include(), but the difference between them is the same as the difference between require() and require_once().

If you have to work with dates in the following format: “Tuesday, February 14, 2006 @ 10:39 am”, how can you convert them to another format, that is easier to use?

The strtotime function can convert a string to a timestamp. A timestamp can be converted to date format. So it is best to store the dates as timestamp in the database, and just output them in the format you like.

So let’s say we have
$date = “Tuesday, February 14, 2006 @ 10:39 am”;
In order to convert that to a timestamp, we need to get rid of the “@” sign, and we can use the remaining string as a parameter for the strtotime function.

So we have
$date = str_replace(“@ “,”",$date);
$date = strtotime($date);

now $date is a timestamp
and we can say:

echo date(“d M Y”,$date);

How 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'] . “


\n”;

$browser = get_browser();

foreach ($browser as $name => $value) {
echo “$name $value
\n”;
}

How i will check that user is, logged in or not. i want to make it a function and i want to use in each page and after login i want to go in current page(same page. where i was working)?

For this we can use the session objec($_SESSION)t. When the user login with his/ her user name and password, usually we check those to ensure for correctness. If that user name and password are valid one then we can store that user name in a session and then we can very that session variable has been set or not in a single files and we can include that file in all pages.

How i can get ip address?

We can use SERVER var $_SERVER['SERVER_ADDR'] and getenv(“REMOTE_ADDR”) functions to get the IP address.

What is differenc between mysql_connect and mysql_pconnec?

mysql_pconnect establishes a persistent connection. If you don’t need one (such as a website that is mostly HTML files or PHP files that don’t call the db) then you don’t need to use it. mysql_connect establishes a connection for the duration of the script that access the db. Once the script has finished executing it closes the connection. The only time you need to close the connection manually is if you jump out of the script for any reason.

If you do use mysql_pconnect. You only need to call it once for the session. That’s the beauty of it. It will hold open a connection to the db that you can use over and over again simply by calling the resource ID whenever you need to interact with the db.

What is the difference between echo and print statement?

There is a slight difference between print and echo which would depend on how you want to use the outcome. Using the print method can return a true/false value. This may be helpful during a script execution of somesort. Echo does not return a value, but has been considered as a faster executed command. All this can get into a rather complicated discussion, so for now, you can just use whichever one you prefer.

How to make a download page in own site, which i can know that how many file has been loaded by particular user or particular ipaddress?

We can use hyperlink having URL where file are kept. and we only allow regisetered user to download. from session of user we can get the user detail

How We Can Use Php Xml For each Loop?

PHP XML FOREACH LOOP

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load(“checkbox array.xml”);

$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item)
{
echo $item->nodeName . ” = ” . $item->nodeValue . “
“;
}
?>

What Is THe Reason For  Virus  Attack In Site

Reason for virus attack
—————————Nowadays most of the sites are attacked by the virus which result to be the terrible cause for the owners. By means of E-commerce site and shopping cart site it will result in huge loss to the owners. So, most of the people would be thinking that what might be the reason for the virus attack. There might be some of the reasons for the virus attack below are some of the points specified for the cause of the virus attack. Check your site whether it escapes from these sequence.
Is there any open source is added in your site?
Is comment posting is enabled in your site?
Is there any iframe in your site?
Is there any third party site link is in your site?
If you have any one of the above said points please review the remedy for it.
If your site have included the open source then disable it.
Is there any option for comment posting, disable it
If you are using the iframe then remove it.
If any third party links are added in your site remove it. Because that third party site might be spreading the virus in your site. So be cautious while adding the third party link to your site

Diiference between session and cookies?

Ans:- 1. session stored at server while cookie get stored at client’s webbrowser.

2. session are stored as an object on server side on the path specified in the php.in file for session_savepath variable while cookies are passed as header and stored on client’s web browser as text file.

3. session variables are exists only when session doesn’t expires while cookies[presistent not session] can be stored for future time also and can be used to handle user’s preference.

what are encryption methods available in php and mysql?Difference between sha1 and md5?

Ans:- some encryption methods availavle in php are md5,sha1,encrypt,password.Difference between sha1 and md5 encryption is that sha1 take more space than md5 in terms of storing information in the database.Some encryption available in mySql are password,MD5,encrypt.

What is Ajax & how it works?

Ans:- AJAX stands for asyncronous javascript and xml.It’s asyncronous this script doesn’t wait for the response.Regardless of this it can make another request without waiting for the response.Fist of all it creates XMLHttpRequest object by which it makes a request.and when response comes back script handover it to another function which will check for the response readyStatus and returns the response.

OOPs principles?

Ans:- Polymorphism [not supported in PHP]

Encapsulation

Abstraction

Dynamic binding

class and Object

for more detail please refer http://in2.php.net/manual/en/language.oop5.php

Mysql Joins?

Ans:- I don’t have idea but know about types.Cross,Left,right,inner and outer join.

Strings and array functions.array_walk,in_array?

Ans:- check functionlist available on

http://in2.php.net/manual/en/ref.array.php [for array]

http://in2.php.net/manual-lookup.php?pattern=string&lang=en [for strings function]

Difference between include,include_once,require,require_once?

Ans:- Unlike include(), require() will always read in the target file, even if the line it’s on never executes. If you want to conditionally include a file, use include(). The conditional statement won’t affect the require(). However, if the line on which the require() occurs is not executed, neither will any of the code in the target file be executed.include() may give warning and proceed further but require() will hault whenever warning/error faced in the script.include_once(),require_once() as name suggest can be used to include a file only one.[useful in case we include a class file]

How can we submit a form without a submit button?

Ans:- you can call a function in javascript onclick event of any form element/link and in the function you amy use document.formName.submit(); to submit the form

What is the difference between mysql_fetch_object, mysql_fetch_rows and mysql_fetch_array?

Ans:- mysql_fetch_object will return an object by which we can access the database fields records while mysql_fetch_aaray and mysql_fetch_rows return array of database records.mysql_fetch_row will not return associative array while mysql_array will return associative array too.

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

$message is used as a veriable while $$message can be used to assign a value as variable.for eg:

$message=’uttam’;

$$message=’kumar’;

in this case $kumar will give you value as ‘uttam’.

What is meant by nl2br()?

Returns string with ‘<br />’ inserted before all newlines(\n).

$msg=”these are \n interview question”;

$nl2brmsg=nl2br($msg);

$nl2brmsg will return value as “these are </br> interview question”.

List of php Array Functions

array_change_key_case()
– Returns an array with all string keys lowercased or uppercased

array_chunk()
– syntax
array array_chunk ( array $input , int $size [, bool $preserve_keys= false ])
– Chunks an array into size large chunks.

array_combine()
– syntax
array array_combine ( array $keys , array $values )
– Creates an array by using one array for keys and another for its values

array_count_values()
– syntax
array array_count_values ( array $input )
– returns an array using the values of the input array as keys and their frequency in input as values.
– Case Insensitive

array_diff_assoc()
– syntax
array array_diff_assoc ( array $array1 , array $array2 [, array $... ] )
– Computes the difference of arrays with additional index check. Returns an array with the elements in first array which are not present in rest of arrays.

array_diff_uassoc
– syntax
Computes the difference of arrays with additional index check which is performed by a user supplied callback function
– sample use : $result = array_diff_uassoc($array1, $array2, “key_compare_func”);
– converse function : array_intersect_assoc()

array_diff_key
– syntax
array array_diff_key ( array $array1 , array $array2 [, array $... ] )
– Computes the difference of arrays using keys for comparison.
– Converse function : array_intersect_key()

array_diff_ukey()
– syntax
– Computes the difference of arrays using a callback function on the keys for comparison
– sample use
var_dump(array_diff_ukey($array1, $array2, ‘key_compare_func’));

array_diff()
– syntax
array array_diff ( array $array1 , array $array2 [, array $ ... ] )
– Compares array1 against array2 and returns the difference.

array_fill_keys()
– syntax
– Sample use
$arr1 = array(0 => ‘abc’, 1 => ‘def’);
$arr2 = array(0 => 452, 1 => 128);

array_fill_keys($arr1,$arr2);
returns: [abc] => 452, [def] => 128

array_fill()
– syntax
array array_fill ( int $start_index , int $num , mixed $value )
– Creates an array with starting index as $start_index and with $num no of elements and value of each element will be taken from $value

array_filter()
– syntax
array_filter($array,’function_name’);
– Iterate through each array element and pass each of them to callback function specified as second argument.

array_flip
– syntax
array array_flip ( array $trans )
– Exchanges all keys with their associated values in an array
Array keys becomes values and values become keys.

.htaccess/.htpassword tutorial

AuthUserFile /home/yourdomain/www/.htpasswd
AuthType Basic
AuthName “yourUsername”
Require valid-user

note: The password will be stored in .htpasswd file which is in root directory of the site.


Which of the following will NOT add john to the users array?

    1. $users[] = 'john';
      Successfully adds john to the array
    2. array_add($users,’john’);
      Fails stating Undefined Function array_add()
    3. array_push($users,‘john’);
      Successfully adds john to the array
    4. $users ||= 'john';
      Fails stating Syntax Error
  1. What’s the difference between sort(), assort() and ksort? Under what circumstances would you use each of these?
    1. sort()
      Sorts an array in alphabetical order based on the value of each element. The index keys will also be renumbered 0 to length – 1. This is used primarily on arrays where the indexes/keys do not matter.
    2. assort()
      The assort function does not exist, so I am going to assume it should have been typed asort().

      asort()
      Like the sort() function, this sorts the array in alphabetical order based on the value of each element, however, unlike the sort() function, all indexes are maintained, thus it will not renumber them, but rather keep them. This is particularly useful with associate arrays.

    3. ksort()
      Sorts an array in alphabetical order by index/key. This is typically used for associate arrays where you want the keys/indexes to be in alphabetical order.
  2. What would the following code print to the browser? Why?

    PHP:

    1. $num = 10;
    2. function multiply(){
    3. $num = $num * 10;
    4. }
    5. multiply();
    6. echo $num; // prints 10 to the screen

    Since the function does not specify to use $num globally either by using global $num; or by $_GLOBALS['num'] instead of $num, the value remains 10.

  3. What is the difference between a reference and a regular variable? How do you pass by reference and why would you want to?

    Reference variables pass the address location of the variable instead of the value. So when the variable is changed in the function, it is also changed in the whole application, as now the address points to the new value.

    Now a regular variable passes by value, so when the value is changed in the function, it has no affect outside the function.

    PHP:

    1. $myVariable = “its’ value”;
    2. Myfunction(&$myVariable); // Pass by Reference Example

    So why would you want to pass by reference? The simple reason, is you want the function to update the value of your variable so even after you are done with the function, the value has been updated accordingly.

  4. What functions can you use to add library code to the currently running script?

    This is another question where the interpretation could completely hit or miss the question. My first thought was class libraries written in PHP, so include(), include_once(), require(), and require_once() came to mind. However, you can also include COM objects and .NET libraries. By utilizing the com_load and the dotnet_loadrespectively you can incorporate COM objects and .NET libraries into your PHP code, thus anytime you see “library code” in a question, make sure you remember these two functions.

  5. What is the difference between foo() & @foo()?

    foo() executes the function and any parse/syntax/thrown errors will be displayed on the page.

    @foo() will mask any parse/syntax/thrown errors as it executes.

    You will commonly find most applications use @mysql_connect() to hide mysql errors or @mysql_query. However, I feel that approach is significantly flawed as you should never hide errors, rather you should manage them accordingly and if you can, fix them.

  6. How do you debug a PHP application?

    This isn’t something I do often, as it is a pain in the butt to setup in Linux and I have tried numerous debuggers. However, I will point out one that has been getting quite a bit of attention lately.

    PHP – Advanced PHP Debugger or PHP-APD. First you have to install it by running:
    pear install apd

    Once installed, start the trace by placing the following code at the beginning of your script:
    apd_set_pprof_trace();

    Then once you have executed your script, look at the log inapd.dumpdir.
    You can even use the pprofp command to format the data as in:
    pprofp -R /tmp/pprof.22141.0

    For more information see http://us.php.net/manual/en/ref.apd.php

  7. What does === do? What’s an example of something that will give true for ‘==’, but not ‘===’?

    The === operator is used for functions that can return a Boolean false and that may also return a non-Boolean value which evaluates to false. Such functions would be strpos and strrpos.

    I am having a hard time with the second portion, as I am able to come up with scenarios where ‘==’ will be false and ‘===’ would come out true, but it’s hard to think of the opposite. So here is the example I came up with:

    PHP:

    1. if (strpos(“abc”, “a”) == true)
    2. {
    3. // this does not get hit, since “a” is in the 0 index position, it returns false.
    4. }
    5. if (strpos(“abc”, “a”) === true)
    6. {
    7. // this does get hit as the === ensures this is treated as non-boolean.
    8. }
  8. How would you declare a class named “myclass” with no methods or properties?

    PHP:

    1. class myclass
    2. {
    3. }
  9. How would you create an object, which is an instance of “myclass”?

    PHP:

    1. $obj = new myclass();

    t doesn’t get any easier than this.

    How do you access and set properties of a class from within the class?

    You use the $this->PropertyName syntax.

    PHP:

    1. class myclass
    2. {
    3. private $propertyName;
    4. public function __construct()
    5. {
    6. $this->propertyName = “value”;
    7. }
    8. }

1 Comment »

RSS feed for comments on this post. TrackBack URI

  1. Please add some complex question here…..

    SandeepVerma
    (http://sandeepverma.wordpress.com/)


Leave a comment

XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Blog at WordPress.com. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.