PHP Interview Questions

Qus:- What is PHP?

Answer

PHP (Hyper text Pre Processor) is a scripting language commonly used for web applications. PHP can be easily embedded in HTML. PHP generally runs on a web server. It is available for free and can be used across a variety of servers, operating systems and platforms.


Qus:- What is a Session in PHP?

Answer

A PHP session is no different from a normal session. It can be used to store information on the server for future use. However this storage is temporary and is flushed out when the site is closed. Sessions can start by first creating a session id (unique) for each user.

Syntax : session_start()
E.g. storing a customer’s information.  


Sessions allow data to be transferred from one page to another. Session information is temporary and information is valid until the user is using the website. A session assigns a unique ID, UID, to each visitor.

A PHP session starts using:

<?php session_start(); ?>


PHP Session Variables

A PHP session variable is used to hold values of the current session. A session needs to be started first.

<?php
session_start();
// store session data
$_SESSION['sample']=1;
?>

They can be used to hold information about a single user that is applicable to all web pages.



Qus:- Explain the difference between $message and $$message?

Answer

$message is used to store variable data. $$message can be used to store variable of a variable. Data stored in $message is fixed while data stored in $$message can be changed dynamically.

E.g. $var1 = ‘Variable 1’
$$var1= ‘variable2’
This can be interpreted as $ Variable 1=‘variable2’;

For me to print value of both variables, I will write
$var1 $($var1)


Qus:- Explain the difference between $message and $$message in PHP

Ans:- 

$message is a variable and $$message is a variable of another variable. For example

$Message = "YOU";
$you= "Me";

echo $message //Output:- you
echo $$message //output :-Me

$$message allows the developer to change the name of the variable dynamically.


Qus:-   PHP cookies

Ans:-

A cookie is used for identification purposes. It is more commonly used to identify a user in a session. It is a small file the application inserts on the users computer. With PHP one can create and retrieve the cookie.

Setting cookie in php:

Cookies in PHP can be set using the setcookie() function. This must appear before the HTML tag.

Syntax:

Setcookie(name, value, expire, path, domain);

Example: here, the cookie name sample is assigned a value jim. The cookie expires after an hour.

Setcookie(“sample”, “jim”, time()+3600);

Retrieving cookie value:

The cookie that is set can be retrieved as shown below:

Echo $_cookie[“user”];

Isset() function can be used to find if the cookie is set.

What is a Persistent Cookie?

Cookies are used to remember the users. Content of a Persistent cookie remains unchanged even when the browser is closed. ‘Remember me’ generally used for login is the best example for Persistent Cookie.

Qus:- How to set cookies? How to reset/destroy a cookie?

Ans:-

Cookies in PHP can be set using the setcookie() function. This must appear before the HTML tag,

Syntax:

Setcookie(name, value, expire, path, domain);

Example: here, the cookie name sample is assigned a value robin. The cookie expires after an hour.

Setcookie(“sample”, “jim”, time()+3600);


Reset/destroy cookie

Cookies can be deleted either by the client or by the server. Clients can easily delete the cookies by locating the Cookies folder on their system and deleting them. The Server can delete the cookies in two ways:

Reset a cookie by specifying expiry time
Reset a cookie by specifying its name only



PHP sessions introduction

When a user logs in an application, his details are usually stored in a session variable. This information is available to all pages in one application. Sessions in PHP work using a unique id for each visitor.

Starting a php session: This tag must also appear before the HTML tag.

Session_start();

Storing a session variable: Here in the sample variable value is set to 1

Session_start();

$_session[‘sample]=1;

Destroying a session:

Session_destory();

What is session_start() ?

When a user logs in an application, his details are usually stored in a session variable. This information is available to all pages in one application. Sessions in PHP work using a unique id for each visitor.

Starting a php session: This tag must also appear before the HTML tag.

Session_start();

Storing a session variable: Here in the sample variable value is set to 1

Session_start();

$_session[‘sample]=1;

Qus:- What is session hijacking?

Ans:-

Session hijacking is the misuse of a valid computer session. It is used to attain unauthorized and illegal access to a system. This access is attained using the “brute force” attack where in he tries multiple id’s to login in a system while the session is in progress. The most common method of session hijacking is IP spoofing where an attacker uses source-routed IP packets to insert commands into an active communication between two systems on a network and pretending itself as one of the authenticated users.

What is meant by Session Clustering?

Session clustering is used to provide scalability for keeping the session data in synch across a “cluster” of PHP servers. The sessions reside on the machine in which they are created. These sessions are then delivered from one machine to another. This delivery is fully distributed. The Zend Session manager is used for transferring sessions from the system (session storage) to remote addresses.

How many ways I can register the variables into session?

Global variables in PHP can be registered using the session_register() function. It accepts different number of arguments, any of which can be either a string holding the name of a variable or an array consisting of variable names or other arrays

Example:
Session_register(“smple”);

$_session can also be used for registering variables.

Example:
$_SESSION['count'] = 0;

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

Using session_id() function, the current value of the session can be found.

Syntax:
String session_id(string $id);

Short note on Starting a session

Adding session data.
Here in the sample variable value is set to 1
<?php
       Session_start();
       $_session[‘sample]=1;
?>
Reading session data
Once the data is set, it immediately becomes available to read in the $_SESSION array.
<?php
       $_SESSION[‘sample’]=1;
       Print $_SESSION [‘sample’];
?>
Removing session data
The session data can be removed using the unset() function. Only specific elements of the $_SESSION array should be unset.
<?php
$_SESSION[‘sample’]=1;
Print $_SESSION [‘sample’];
Unset ($_SESSION[‘sample’);
?>
Ending a session
A session lasts until the browser window is not closed. In order to explicitly end the session Session_destory(); is used for ending the session.



PHP security tips

Avoid the use of global variables. Hence it must be ensured that register_globals option is not enabled.
Use of variables designed to be set by GET or POST requests.
Store passwords in an encrypted format
Avoid storing credit card and other secured information. Trust a third party gateway.
Make use of server side validations and avoid trusting the user input.
Example: if the expected value is integer, use the intval function.
$post_id = intval($_GET['post_id']);
mysql_query("SELECT * FROM post WHERE id = $post_id");
Avoid using user input directly in the query. Mysql_real_escape_string()
Always use the updated version of php.
How can we encrypt the username and password using PHP?

User names and passwords in PHP can be encrypted using md5 function.
MD5 function calculates the md5 hash of a string. It is basically used for encryption. It is also used for digital signature applications, where a large file must be "compressed" in a secure manner.

Example:

Md5($str);

Crypt() function can also be used to encrypt a string,. It used MD5, DES or blow fish algorithms for encryption.

Syntax:

Crypt(str, salt)

Salt is an optional parameter used to increase the number of characters encoded, to make the encoding more secure

Explain the changing file permission and ownership using PHP's chmod() function.

Chmod() is used for changing permissions on a file.

Syntax:

Chmod(file, mode)

Mode here specifies the permissions as follows:

The first number is always zero
The second number specifies permissions for the owner
The third number specifies permissions for the owner's user group
The fourth number specifies permissions for everybody else
Possible values (to set multiple permissions, add up the following numbers)

1 = execute permissions
2 = write permissions
4 = read permissions
Example:
// everything for owner, read for owner's group
chmod("test.txt",0740);



Qus:- PHP handling file uploads

Ans

PHP handles file uploads through different method.

POST method uploads: This allows user to upload both text and binary files. PHP has a number of authentication and file manipulation functions, a control over upload is possible.

Files can be uploaded in PHP by using the tag type=”file”. An upload form must have encytype="multipart/form-data" , method also needs to be set to method="post". Also, hidden input MAX_FILE_SIZE before the file input. To restrict the size of files

E.g.

<form enctype="multipart/form-data" action="sampleuplaod.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="1000" />

Finally, using move_uploaded_file () the file can be uploaded. Parameters will be source file and destination file


Qus:- PHP creating & deleting directories

Ans:-

Creating directories:

PHP’s mkdir() can be used to create directories. It takes two parameters; path to desired directory and the permission.

Mkdir(*/temp/sample*, 0777);

Deleting directories:

PHP’s rmdir() can be used to delete directories. It takes one parameter as the directory name to be deleted.

rmdir(*/temp/sample*);

Explain the working with directories using opendir(), readdirs(), closedir() along with examples.

Opendir():- It opens the directory. This function returns a directory stream on success and FALSE and an error on failure.

Syntax:
Opendir(directory, context)
Context is a set of options that can modify the behavior of a stream
Example: opens sample directory.
$dir = opendir("directory");

Readdir(): It returns an entry from a directory handle opened by opendir().
Syntax:
Readdir(dir_stream)
Example:
$file = readdir($dir);

closedir(): It closes a directory handle opened by opendir().
Syntax:
closedir(dir_stream)
Example:
$file = close($dir);

Write short note on creating directories, mkdir function with an example.

Mkdir():- creates a directory.

Syntax:
Mkdir(path,mode,recursive,context);

Mode: Optional. Specifies permissions. By default, the mode is 0777 (widest possible access).
The mode parameter consists of four numbers:

The first number is always zero
The second number specifies permissions for the owner
The third number specifies permissions for the owner's user group
The fourth number specifies permissions for everybody else
Possible values (to set multiple permissions, add up the following numbers):

1 = execute permissions
2 = write permissions
4 = read permissions
Recursive – optional and specifies if recursive
Context – optional and Specifies the context of the file handle.
Example:
Mkdir(“sample”);

Write short note on deleting directories, rmdir() with an example.

Rmdir() removes the directory which is empty.

Syntax:
Rmdir(dir, context);

Context: optional. Context is a set of options that can modify the behavior of a stream

Example:
<?php
$var = "images";
if(!rmdir($var))
{
           echo ("Could not remove $var");
}
?>

0 comments:

Post a Comment