Q. Explain Cookies in PHP.
bool setcookie ( string $name [, string $value [, int $expire [, string $path [, string $domain [, bool $secure [, bool $httponly ]]]]]] ) : A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too with the http headers before any output. It is a simple way to maintain data between the different pages in a web application. Cookies are sent by PHP through the web server with the setcookie() function and are stored in the browser. Official maximum size for a HTTP cookie header is 4K. So the actual cookie will be slightly smaller. Some browsers will work with bigger cookies, others won't. The maximum number of cookies from a host that can be stored by a browser is 20.
Q. Explain Sessions in PHP.
A PHP session allows an application to store information for the current session, which can be defined as one user being logged in to your application. A session is identified by a unique session ID. PHP creates a session ID that is an MD5 hash of the remote IP address, the current time, and some extra randomness represented in a hexadecimal string. This session ID can be passed in a cookie or added to all URLs to navigate your application. For security reasons, it’s better to force the user to have cookies enabled than to pass the session ID on the URL where it might end up in web server’s logs as a HTTP_REFERER or be found by some evil person monitoring your traffic. That evil person can still see the session cookie data, of course, so you might want to use an SSL-enabled server to be really safe. When a visitor accesses your site, PHP will check automatically (if session.auto_start is set to 1) or on your request (explicitly through session_start() or implicitly through session_register()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated. If you do turn on session.auto_start then you cannot put objects into your sessions since the class definition has to be loaded before starting the session in order to recreate the objects in your session. All registered variables are serialized after the request finishes.
* Security : The session module cannot guarantee that the information you store in a session is only viewed by the user who created the session. If you want to protect users from simple social engineering tactics (eg. copying the url), you need to enable session.use_only_cookies. In that case, cookies must be enabled unconditionally on the user side, or sessions will not work.
Q. Compare Sessions & Cookies ?
Sessions & Cookies serve somewhat the same purpose, and are, to a certain extent, usable interchangeably. Cookies can be used to track information even from one session to another by setting it's time() parameter, Differences :
* Cookies are stored on the client, while the session data is stored on the server. As a result, sessions are more secure than cookies (no information is being sent back and forth between the client and the server).
* Cookies, having their data stored on the client, work smoothly when you have a cluster of web servers, whereas sessions are stored on the server, meaning in one of your web servers handles the first request, the other web servers in your cluster will not have the stored information.
* Cookies can be stooped woking as it can be disabled at client end, but session cann't be as they stored on the server.
* A cookie can store only single value, a session can hold multiple variables.
* Cookies can be set to a long lifespan as stored at client's machine.
Q. How can you get round the stateless nature of HTTP using PHP?
The top two options that are used are sessions and cookies. To access a session, you will need to have session_start() at the top of each page, and then you will use the $_SESSION hash to access and store your session variables. For cookies, you only have to remember one rule. You must use the set_cookie function before any output is started in your PHP script. From then on you can use the $_COOKIE has to access your cookie variables and values.
There are other methods, but they are not as fool proof and most often than not depend on the IP address of the visitor, which is a very dangerous thing to do.
Q. What is meant by PEAR in php?
PEAR - PHP Extension and Application Repository is the next revolution in PHP. This repository is bringing higher level programming to PHP. PEAR is a framework and distribution system for reusable PHP components. It eases installation by bringing an automated wizard, and packing the strength and experience of PHP users into a nicely organised OOP library. PEAR also provides a command-line interface that can be used to automatically install "packages"
Q. Explain different sort functions in php.
bool sort ( array &$array [, int $sort_flags ] ) : Sorts an array in alphabetical order based on the value of each element. This function assigns new keys for the elements in array . It will remove any existing keys you may have assigned, rather than just reordering the keys. Sorting type flags: SORT_REGULAR, SORT_NUMERIC, SORT_STRING, SORT_LOCALE_STRING. Reverse is rsort.
bool asort ( array &$array [, int $sort_flags ] ) : This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant. Reverse is arsort.
bool ksort ( array &$array [, int $sort_flags ] ) : Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays. Reverse is krsort.
bool uksort ( array &$array , callback $cmp_function ) : will sort the keys of an array using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.
bool natsort ( array &$array ) : Sort an array using a "natural order" algorithm.
bool usort ( array &$array , callback $cmp_function ) : Sort an array by values using a user-defined comparison function.
Q. What's the difference between mysql_fetch_row() and mysql_fetch_array()?
mysql_fetch_object() collects first single matching record
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.
mysql_fetch_assoc() returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.
mysql_fetch_array() returns an array that corresponds to the fetched row and moves the internal data pointer ahead.
Q. What are magic methods in PHP?
Functionalities like serializing, converting objects to string, getting setting values without explicit get and set methods for the variables etc, are magic functionality. PHP defines methods with names starting with __(double underscore).
Eg. __get, __set, __construct, __destruct, __set, __isset, __unset, __sleep, __wakeup, __toString, __clone, __autoload, __set_state
http://in.php.net/manual/en/language.oop5.magic.php
Q. What are predefined variables, predifined classes in php ?
PHP provides an additional set of predefined arrays containing variables from the web server (if applicable), the environment, and user input. These new arrays are rather special in that they are automatically global
http://in.php.net/manual/en/language.variables.predefined.php
e.g., $_SERVER, $_REQUEST, $_POST, $_GET, $_ENV, $_COOKIE, $_FILES, $_SESSION, $GLOBALS, $php_errormsg, $http_response_header
Predefined classes : stdClass, Exception,_PHP_Incomplete_Class, php_user_filter, Directory
Exception : for exception handling
Directory: dir class
eg. public/private/protected [static] class extends {
{
public $x;
…
public function method_a() {
…
}
}
Q. 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. For 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_load respectively you can incorporate COM objects and .NET libraries into your PHP code.
Q. How do you debug a PHP application?
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 in apd.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
Q. 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:
if (strpos("abc", "a") == true)
{
// this does not get hit, since "a" is in the 0 index position, it returns false.
}
if (strpos("abc", "a") === true)
{
// this does get hit as the === ensures this is treated as non-boolean.
}
Q. What is the difference between include, include_once, require and require_once?
All three allow the script to include another file, be it internal or external depending on if allow_url_fopen is enabled. However, they do have slight differences, which are denoted below.
1. include()
The include() function allows you to include a file multiple times within your application and if the file does not exist it will throw a Warning and continue on with your PHP script.
2. include_once()
include_once() is like include() except as the name suggests, it will only include the file once during the script execution.
3. require()
Like include(), you can request to require a file multiple times, however, if the file does not exist it will throw a Warning that will result in a Fatal Error stopping the PHP script execution.
Q. string ereg_replace (string $pattern, string $replacement, string $string)
1. Convert mm/dd/yyyy => dd/mm/yyyy format
print ereg_replace("([0-9]+)/([0-9]+)/([0-9]+)","\\2/\\1/\\3",'08/26/2003');
2. Replace URLs with links
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "\\0", "http://php-question.blogspot.com");
3. Strip all the HTML tags
echo preg_replace("/<(.*?)>(.*?)<\/(.*?)>/", "\\2", "testing hereha ha ha");
echo ereg_replace("(<.*>)(.*)", "\\2", "testing hereha ha ha");
echo preg_replace("/(<[^>]*>)/", "", "testing hereha ha ha");
4. Email check :
5."div\b(?:(?=(\s+(?:id="([^"]*)"|class="([^"]*)")|[^\s>]+|\s+))\1)*>"
6. "img\s+(?:alt="([^"]*)"|class="([^"]*)"|style="([^"]*)"|src="([^"]*)"|height="([^"]*)"|width="([^"]*)")|[^\s>]+|\s+)*>"
7. "img\s+(?:alt="([^"]*)"()|class="([^"]*)"())|[^\s>]+|\s+)*\2\4>"
Q. What's the difference between the way PHP and Perl distinguish between arrays and hashes?
In Perl, you are required to use the @ sign to start all array variable names, for example, @myArray. In PHP, you just continue to use the $ (dollar sign), for example, $myArray.
Now for hashes in Perl you must start the variable name with the % (percent sign), as in, %myHash. Whereas, in PHP you still use the $ (dollar sign), as in, $myHash.
Q. What does the GD library do?
This is probably one of my favorite libraries, as it is built into PHP as of version 4.3.0 (I am very happy with myself, I didn't have to look up the version of PHP this was introduced on php.net). This library allows you to manipulate and display images of various extensions. More often than not, it is used to create thumbnail images. An alternative to GD is ImageMagick, however, unlike GD, this does not come built in to PHP and must be installed on the server by an Administrator.
Q. Is PHP better than Perl? - Discuss.
"Pick the language for the job, do not fit the job into a particular language."
Perl in my opinion is great for command line utilities, yes it can be used for the web as well, but its' real power can be really demonstrated through the command line. Likewise, PHP can be used on the command line too, but I personally feel it's more powerful on the web. It has a lot more functions built with the web in mind, whereas, Perl seems to have the console in mind.
Pick the language for the job. If I needed a console application that was meant to show off the performance differences between a quick sort, bubble sort, and a merge sort, give me C/C++! If you want a Photo Gallery, give me PHP or C# (though I personally find .NET languages better for quick GUI applications than web).
Q. 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:
$myVariable = "its' value";
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.
Q. 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. eg. @mysql_connect()
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.
Q. Can we write windows like applications in PHP?
Yes, using PHP-GTK on linux and WinBinder on windows.
Q. What are the ways to find out if a variable has been declared?
isset or empty language constructs.
Q. What is the difference between echo and print ?
1. echo can take more than one parameter for displaying, while print cannot take more than one (parse error : unexpected ',')
2. echo cannot be used to return anything (parse error : unexpected T_ECHO), while print returns 1 always.
Q. What is eval in php?
Evaluates the string given in code_str as PHP code. Among other things, this can be useful for storing code in a database text field for later execution.
No comments:
Post a Comment