Showing posts with label PHP Interviews Questions. Show all posts
Showing posts with label PHP Interviews Questions. Show all posts

Friday 17 May 2013

Concurrent Connections of Apache Server

First of all you should understand below

  • ServerLimit: 16
  • StartServers: 2
  • MaxClients: 200
  • MinSpareThreads: 25
  • MaxSpareThreads: 75
  • ThreadsPerChild: 25



First of all, whenever an apache is started, it will start 2 child processes which is determined by StartServers parameter.
Then each process will start 25 threads determined by ThreadsPerChild parameter so this means 2 process can service only 50 concurrent connections/clients i.e. 25x2=50.

Now if more concurrent users comes, then another child process will start, that can service another 25 users. But how many child processes can be started is controlled by ServerLimit parameter, this means that in the configuration above, I can have 16 child processes in total, with each child process can handle 25 thread, in total handling 16x25=400 concurrent users. 


But if number defined in MaxClients is less which is 200 here, then this means that after 8 child processes, no extra process will start since we have defined an upper cap of MaxClients

This also means that if I set MaxClients to 1000, after 16 child processes and 400 connections, no extra process will start and we cannot service more than 400 concurrent clients even if we have increase the MaxClient parameter. 

In this case, we need to also increase ServerLimit to 1000/25 i.e. MaxClients/ThreadsPerChild=40 So this is the optmized configuration to server 1000 clients


    ServerLimit          40
    StartServers          2
    MaxClients          1000
    MinSpareThreads      25
    MaxSpareThreads      75 
    ThreadsPerChild      25
    MaxRequestsPerChild   0


File Location: C:/wamp/bin/apache/Apache2.2.17/conf/extra/httpd-mpm.conf

Sunday 27 January 2013

Regular Expressions PHP/Javascript

MetaCharacter: It is special chacter(s) which have special meaning in Regular Expression.

For Example:
*, ., /, \, ? and ^.

Sr
Meta character
Desctiption
1
[ ]
Match any character within [phc]
Means find “p” OR “h” OR “c”
2
-
Range
a-z means a to z(a,b,c, ... z)
0-0 means 0 to 9 (0,1,2,3,4,5,6,7,8,9)
A-Z means A to Z(A,B,C,D ..... Z)
3
^
Caret It means start with a character
For example: ^ab (start with “a”)

Inside the bracket if have opposite meaning.
For example: [^a](must not start with “a”)

4
$
End with character
For Example
Abc$ means end with “c”
5
.
The . (period) means any character(s) in this position,
For example, ph. will find php, php-tutorial and php-tutorial-php but not aphp because it has no following character
6
?
Matches the preceding character 0 or 1 times only.
For example:
colou?r will find both color (0 times) and colour (1 time).
7
*
Matches the preceding character 0 or more times.
For example:
tre* will find tree (2 times) and tread (1 time) and trough (0 times).
8
+
Matches the previous character 1 or more times.
For example:
tre+ will find tree (2 times) and tread (1 time) but NOT trough (0 times).
9
{n}
Preceding character, or character range, n times exactly.
For example:
find a local phone number we could use [0-9]{3}-[0-9]{4} which would find any number of the form 723-4567 OR 132-3234 OR 214-3433.
10
()
To group a character.
For Example:
(php), will find the “php” only.
11
|
Vertical bar used for OR
(a|c) find either “a” OR “c”
12
\d
any character in the range 0 – 9
13
\D
Any character not in between 0-9
14
\s
Whitespace or tab
15
\S
Not whitespace or tab
16
\w
Alphanumeric characters (a-z, 0-9, A-Z)
17
\W
Not alphanumeric character (a-z, 0-9, A-Z)


Tuesday 9 October 2012

PHP Interview Questions and Answers for fresher

PHP Interview Questions and Answers for fresher


Question: What is PHP?
Answer: 
php interview questions and answers

PHP is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.



Question: What is name of function that allows you to store session data in a database?
Answer: session_set_save_handler





Question: What is obj_start()?
Answer:It is used to initialize the object buffer, so that whole page first parsed instead of parsing in parts and send to browser.



Question: Why whitelists afford stronger protection against attacks than blacklists?
Answer: Blacklists words are some bad words (like s*x, f**k etc) that are not allowed to input by users into application. Except blacklists words, all words are allowed to input into the database.
whitelists words are those words that only allowed to input by user in application. Except Whitelists, all words removed while input the data into database.



Question: What is Session Register?
Answer: It is used to register a one or more global variable with current session. It session_start() was not called then it will call automatically when you call session_register;


Question: What are new Featues in PHP5?
Answer:  Type hinting
                Magic method and Magic constants
                Standard PHP Libarary (SPL)
                Namespaces
                Access Modifier (Public, Privated & Protected)
                Changes in Functions
                Heredoc introduced
                E_STRICT : warning for deprecated function
                2nd option is optional in ternary operator



Question: List the Error constants in php?
Answer: E_ERROR, E_NOTICE, E_PARSE, E_WARNING, E_USER_WARNING, E_COMPILE_WARNING.
               


Question: What are the advantages of stored procedures, triggers, indexes in PHP?
AnswerStored Procedure: It is set of sql command 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. this improve the performance because the query has to be parsed only once.



Question: What is difference between cookie and session?
AnswerSession stored in server side and cookie stored in client side.
Session is logical object that store the object OR data and preserver on navigation of multiple page.
Cookie is stored temporary in browser (like mozilla, IE) and expired after close the browser.



Question: What is Persistent Cookie ?
AnswerPersistent cookie stored in browser and don't expired after close the browser. It retain the information until manually removed the cookie.



Question: Is overloading possible in PHP? How?
AnswerYes, overloading is possible. It is possible through Magic method



Question: Name of php function that Counts the number of occurrences of ever character.
Answercount_chars



Question: What is cache?
Answer: It is high speed access protected area in a computer which is reserved for temporary storage of data. It can be divided into two parts.
A) Cache Memory - It is more fast access area(Static RAM).
B) Disk Cache - Cache stored in disk (Dynamic RA)




Question: How session is working?
Answer: When we create a session, it stored in server side but store the protected key in browser cookie.
That's why most of sites stop login functionality when you disable the cookie.




Question: What is PHPUnit?
Answer: It is framework, written in PHP used testing the code.




Question: How to Store Session in databases?.
Answer: To store the session in database, we have to get access whenever session is created, read, write, destroy. For this their is one function in php session_set_save_handler

bool session_set_save_handler ( callable $open , callable $close , callable $read  , callable $write , callable $destroy , callable $gc )

Just pass the 6 function name, that will be call automatically whenever you start using session.



Question: Get the Images source from the html source?
Answer:
$htmlSource = ".......";
$imageArray = array();
$doc = new DOMDocument();
$doc->loadHTML( $htmlSource  );

$tags = $doc->getElementsByTagName('img');

foreach ($tags as $tag) {
       $imageArray[] = $tag->getAttribute('src');
}



Question: What is traits in PHP?

Answer: PHP5.4 implements a method of code reuse called Traits.




Question: Difference between Notice, warning and Error ?
Answer: NOTICE: this is a short message for saying what to do or what not to do. For Example, When you are trying to use undefined varaible
echo $noExist; 
WARNING: occcurs at run time. Code execution continues. more serious as compare to warning. For Example, When you are trying to include a noexistfile
 echo include "notexist.php"; 
ERROR: this also occurs at run time, execution terminates. Its more serious to above both. For Example, When you are trying to use require a noexistfile
 echo require "notexist.php"; 

Question: How to set cookie
Answer: Use setcookie function to set the cookie. you can set the cookie name, value, expiration date, domain, secure, httponly.
http://www.web-technology-experts-notes.in/2012/10/setcookie.html



Question: What does a special set of tags <?= and ?> do in PHP?
Answer: The output is sent directly to the browser.



Question: What is default port of FTP?
Answer: 21

Question: What is default port of SFTP?
Answer: 22

Question: What is default port of SMTP?
Answer: 25

Question: What is default port of MYSQL?
Answer: 3306

Question: What is default port of HTTP?
Answer: 80

Question: How to set and get a constant value?
Answer:
/*set a value as constant*/
define("MAXSIZE", 100);

/*get a value of constant*/
echo MAXSIZE;
echo constant("MAXSIZE")


Question: What does do ob_start();
Answer: ob_start Function is used to turn on output buffering.The PHP output buffering will save all the server outputs to a string variable.it  returns TRUE on success or FALSE on failure.If you are using ob_start, then you should also use ob_end_flush  function for flushing the output buffer. You can also use a call-back function like ob_start("function_name");




Question: What is Difference JSON and JSONP
Answer: JSONP is JSON with padding, that is, you put a string at the beginning and a pair of parenthesis around.

//JSON format
{"name":"Rob Allen","id":5}
//JSONP format
func({"name":"Rob Allen","id":5});



Question: List out the predefined classes in PHP?
Answer: Following are some predefined class in PHP.
  • Directory
  • stdClass
  • __PHP_Incomplete_Class
  • exception
  • php_user_filter




Question: What is the difference between session_register and $_session?
Answer: If session_start() was not called before session_register() is called, an implicit call to session_start() with no parameters will be made. But $_SESSION requires session_start() before use.
session_register function returns boolean value and $_SESSION returns string value
session_register() function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0.



Question: How to Change the Session name?
Answer: session_name — Get and/or set the current session name.




Question: What is JSON?
Answer: Full form of JSON is JavaScript Object Notation. It is a lightweight data-interchange format, which is independent of operating system and languages. Its similar to XML, but better in performance like smallar and fast.



Question: How do you capture audio/video in PHP?
Answer: FFmpeg is a complete solution to record, convert and stream
audio and video.


Question: How to prevent form hijacking in PHP?
Answer: Use token system in form.


Question: What is the difference between mysql_fetch_object, mysql_fetch_array and mysl_fetch_row?
Answer: 
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_row() - Get a result row as an enumerated array
mysql_data_seek() - Move internal result pointer
mysql_query() - Send a MySQL query
mysql_fetch_object: Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead.



Question: What are the differences between require and include, include_once?
Answer: 
File will not be included more than once. If we want to include a file once only and further calling of the file will be ignored then we have to use the PHP function include_once().

This will prevent problems with function redefinitions, variable value reassignments, etc.



Question: What is meant by nl2br()?
Answer: Returns string with '<br />' or '<br>' inserted before all newlines (\r\n, \n\r, \n and \r).




Question: How to set the response code in PHP?
http_response_code(404);



Question: How to get the response code in PHP?
echo http_response_code();//404

Tuesday 10 July 2012

SQL Injection Attack - PHP & MySQL


In this attack, a  hacker is able to execute SQL queries in your website's database. This attack is usually performed by entering text into a form field which causes a subsequent SQL query, generated from the PHP form processing code, to execute part of the content of the form field as though it were SQL. The effects of this attack range from the harmless (simply using SELECT to pull another data set) to the devastating (DELETE, for instance).

It is a basically a trick to inject SQL command or query as a input mainly in the form of the POST or GET method in the web pages. Most of the websites takes parameter from the form and make SQL query to the database.
For a example, in a product detail page of php, it basically takes a parameter product_id from a GET method and get the product detail from database using SQL query. With SQL injection attack, a intruder can send a crafted SQL query from the URL of the product detail page and that could possibly do lots of damage to the database. And even in worse scenario, it could even drop the database table as well.


For Example
you have login page and ask user to login via putting username & password into form.
suppose that a intruder called user injected x’ OR ‘x’='x in the username field and x’ OR ‘x’='x in the password field. Then the final query will become like this.

SELECT * FROM users WHERE username=’x’ OR ‘x’='x’ AND password=’x’ OR ‘x’='x’;

Now what happen, it will return the first record of table users 
&
user who is not authorize, will be able to login in website.

use mysql_real_escape_string function to avoid the problem.




http://dev.mysql.com/tech-resources/articles/guide-to-php-security-ch3.pdf


How can I prevent SQL-injection in PHP?
1. USe PDO
$stmt = $pdo->prepare('SELECT * FROM users WHERE name = :name');
$stmt->execute(array('name' => $name));
foreach ($stmt as $row) {
    /* Do your Action **/

    /* Do your Action **/
}


2. USe MySqlI instead of MySQL. MySQLI is far better than MySql
$stmt = $dbConnection->prepare('SELECT * FROM users WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    /* Do your Action **/

    /* Do your Action **/
}

3. Use framework and execute the query with framework like zend, cakephp and magento etc. But for this you must install the framework.