Tuesday, July 3, 2012

Regular expresion

1. Remove extra spaces instring:

$str = "                 Dipanwita                                          kundu";
echo $str = preg_replace( "/[^\w\s]/", "", $str ); //return Dipanwita kundu
echo preg_replace('/\s\s+/', ' ', $str);//Dipanwita kundu

2.Remove extra space between each comma seperated fields:
$sTestString ="
Authentiek   ,   Eenvoudig, Exclusief,    Familiair,               Informeel,Klassiek,Modern,Romantisch,Sfeervol,Sjiek,          Trendy,Zakelijk";


$sTestString1 = preg_replace( '/\s*/m', '', $sTestString );
echo $sTestString; //retun Authentiek , Eenvoudig, Exclusief, Familiair, Informeel,Klassiek,Modern,Romantisch,Sfeervol,Sjiek, Trendy,Zakelijk


3. Check Url

if (preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url1))
{
  echo "right";
}
else
{
 echo "Wrong";
}


Wednesday, December 29, 2010

array in php

array_combine: php 5.x

This function takes two arrays and puts them together, though not in the way you might think at first. This function takes the first array and uses it as the keys for your new array. It then takes the second array and uses it as the values for your new array. It is important to ensure that both of your input arrays have the same number of elements. If they don’t, the function will return boolean FALSE rather than returning your new array.

$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>
The above example will output:

Array
(
[green] => avocado
[red] => apple
[yellow] => banana
)


array_flip — Exchanges all keys with their associated values in an array

$trans = array("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip($trans);
print_r($trans);
?>
now $trans is:

Array
(
[1] => b
[2] => c
)

array_product — Calculate the product of values in an array


$a = array(2, 4, 6, 8);
echo "product(a) = " . array_product($a) . "\n";

?>
The above example will output:

product(a) = 384

array_merge — Merge one or more arrays
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
The above example will output:

Array
(
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)

Zend for beginners

The Bootstrap
Your Bootstrap class defines what resources and components to initialize. By default, Zend Framework's Front Controller is initialized, and it uses the application/controllers/ as the default directory in which to look for action controllers (more on that later). The class looks like the following:

1.// application/Bootstrap.php
2. 
3.class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
4.{
5.}

Your application's action controllers contain your application workflow, and do the work of mapping your requests to the appropriate models and views.
An action controller should have one or more methods ending in "Action"; these methods may then be requested via the web. By default, Zend Framework URLs follow the schema /controller/action, where "controller" maps to the action controller name (minus the "Controller" suffix) and "action" maps to an action method (minus the "Action" suffix).
1.// application/controllers/IndexController.php
2. 
3.class IndexController extends Zend_Controller_Action
4.{
5. 
6.    public function init()
7.    {
8.        /* Initialize action controller here */
9.    }
10. 
11.    public function indexAction()
12.    {
13.        // action body
14.    }
15.}

Views in Zend Framework are written in plain old PHP. View scripts are placed in application/views/scripts/, where they are further categorized using the controller names.

[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"
resources.view[] =
resources.db.adapter = "PDO_SQLITE"
resources.db.params.dbname = APPLICATION_PATH "/../data/db/guestbook.db"
 
[staging : production]
 
[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.db.adapter = "PDO_SQLITE"
resources.db.params.dbname = APPLICATION_PATH "/../data/db/guestbook-testing.db"
 
[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.db.adapter = "PDO_SQLITE"
resources.db.params.dbname = APPLICATION_PATH "/../data/db/guestbook-dev.db"

layout()->content ?>

We grab our application content using the layout() view helper, and accessing the "content" key.

1.// application/models/DbTable/Guestbook.php
2. 
3./**
4.* This is the DbTable class for the guestbook table.
5.*/
6.class Application_Model_DbTable_Guestbook extends Zend_Db_Table_Abstract
{
2.    /** Table name */
3.    protected $_name    = 'guestbook';
4.}

Zend_Loader::loadClass() to load classes.


To connect database:
1.$config = new Zend_Config(
2.    array(
3.        'database' => array(
4.            'adapter' => 'Mysqli',
5.            'params'  => array(
6.                'host'     => '127.0.0.1',
7.                'dbname'   => 'test',
8.                'username' => 'webuser',
9.                'password' => 'secret',
10.            )
11.        )
12.    )
13.);
14. 
15.$db = Zend_Db::factory($config->database);
OR
$pdoParams = array(
    PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
);
 
$params = array(
    'host'           => '127.0.0.1',
    'username'       => 'webuser',
    'password'       => 'xxxxxxxx',
    'dbname'         => 'test',
    'driver_options' => $pdoParams
);
 
$db = Zend_Db::factory('Pdo_Mysql', $params);

The second argument to fetchAll() is an array of values to substitute for parameter placeholders in the SQL statement.

The fetchAssoc() method returns data in an array of associative arrays, regardless of what value you have set for the fetch mode, using the first column as the array index.

1.$db->setFetchMode(Zend_Db::FETCH_OBJ);
2. 
3.$result = $db->fetchAssoc(
4.    'SELECT bug_id, bug_description, bug_status FROM bugs'
5.);
6. 
7.// $result is an array of associative arrays, in spite of the fetch mode
8.echo $result[2]['bug_description']; // Description of Bug #2
9.echo $result[1]['bug_description']; // Description of Bug #1

The fetchOne() method is like a combination of fetchRow() with fetchCol(), in that it returns data only for the first row fetched from the result set, and it returns only the value of the first column in that row.

You can add new rows to a table in your database using the insert() method. The first argument is a string that names the table, and the second argument is an associative array, mapping column names to data values.
1.$data = array(
2.    'created_on'      => '2007-03-22',
3.    'bug_description' => 'Something wrong',
4.    'bug_status'      => 'NEW'
5.);
6. 
7.$db->insert('bugs', $data);
The return value of the insert() method is not the last inserted ID, because the table might not have an auto-incremented column. Instead, the return value is the number of rows affected (usually 1).
If your table is defined with an auto-incrementing primary key, you can call the lastInsertId() method after the insert. This method returns the last value generated in the scope of the current database connection.
Example #19 Using lastInsertId() for an Auto-Increment Key
1.$db->insert('bugs', $data);
2. 
3.// return the last value generated by an auto-increment column
4.$id = $db->lastInsertId();
1.$data = array(
2.    'updated_on'      => '2007-03-23',
3.    'bug_status'      => 'FIXED'
4.);
5. 
6.$where[] = "reported_by = 'goofy'";
7.$where[] = "bug_status = 'OPEN'";
8. 
9.$n = $db->update('bugs', $data, $where);
10. 
11.// Resulting SQL is:
12.//  UPDATE "bugs" SET "update_on" = '2007-03-23', "bug_status" = 'FIXED'
13.//  WHERE ("reported_by" = 'goofy') AND ("bug_status" = 'OPEN')
Deleting Rows
1.$n = $db->delete('bugs', 'bug_id = 3');
Using quote()
1.$name = $db->quote("O'Reilly");
2.echo $name;
3.// 'O\'Reilly'
4. 
5.$sql = "SELECT * FROM bugs WHERE reported_by = $name";
6. 
7.echo $sql;
8.// SELECT * FROM bugs WHERE reported_by = 'O\'Reilly'
Closing a Database Connection
1.$db->closeConnection();
server version before running a query
1.$version = $db->getServerVersion();

zend_Acl:

Zend_Acl provides a lightweight and flexible access control list (ACL) implementation for privileges management. In general, an application may utilize such ACL's to control access to certain protected objects by other requesting objects.
For the purposes of this documentation:
a resource is an object to which access is controlled.
a role is an object that may request access to a Resource.
Put simply, roles request access to resources. For example, if a parking attendant requests access to a car, then the parking attendant is the requesting role, and the car is the resource

$acl = new Zend_Acl();
1. 
2.$acl->addRole(new Zend_Acl_Role('guest'))
3.    ->addRole(new Zend_Acl_Role('member'))
4.    ->addRole(new Zend_Acl_Role('admin'));
5. 
6.$parents = array('guest', 'member', 'admin');
7.$acl->addRole(new Zend_Acl_Role('someUser'), $parents);
8. 
9.$acl->add(new Zend_Acl_Resource('someResource'));
10. 
11.$acl->deny('guest', 'someResource');
12.$acl->allow('member', 'someResource');
13. 
14.echo $acl->isAllowed('someUser', 'someResource') ? 'allowed' : 'denied';
the example code would print "allowed".

$acl = new Zend_Acl();
1. 
2.$roleGuest = new Zend_Acl_Role('guest');
3.$acl->addRole($roleGuest);
4.$acl->addRole(new Zend_Acl_Role('staff'), $roleGuest);
5.$acl->addRole(new Zend_Acl_Role('editor'), 'staff');
6.$acl->addRole(new Zend_Acl_Role('administrator'));
7. 
8.// Guest may only view content
9.$acl->allow($roleGuest, null, 'view');
10. 
11./*
12.Alternatively, the above could be written:
13.$acl->allow('guest', null, 'view');
14.//*/
15. 
16.// Staff inherits view privilege from guest, but also needs additional
17.// privileges
18.$acl->allow('staff', null, array('edit', 'submit', 'revise'));
19. 
20.// Editor inherits view, edit, submit, and revise privileges from
21.// staff, but also needs additional privileges
22.$acl->allow('editor', null, array('publish', 'archive', 'delete'));
23. 
24.// Administrator inherits nothing, but is allowed all privileges
25.$acl->allow('administrator');
echo $acl->isAllowed('guest', null, 'view') ?
     "allowed" : "denied";
// allowed
 
echo $acl->isAllowed('staff', null, 'publish') ?
     "allowed" : "denied";
// denied
 
echo $acl->isAllowed('staff', null, 'revise') ?
     "allowed" : "denied";
// allowed
 
echo $acl->isAllowed('editor', null, 'view') ?
     "allowed" : "denied";
// allowed because of inheritance from guest
 
echo $acl->isAllowed('editor', null, 'update') ?
     "allowed" : "denied";
// denied because no allow rule for 'update'
 
echo $acl->isAllowed('administrator', null, 'view') ?
     "allowed" : "denied";
// allowed because administrator is allowed all privileges
 
echo $acl->isAllowed('administrator') ?
     "allowed" : "denied";
// allowed because administrator is allowed all privileges
 
echo $acl->isAllowed('administrator', null, 'update') ?
     "allowed" : "denied";
// The new marketing group inherits permissions from staff
1.$acl->addRole(new Zend_Acl_Role('marketing'), 'staff');
// newsletter
$acl->addResource(new Zend_Acl_Resource('newsletter'));
 
// news
$acl->addResource(new Zend_Acl_Resource('news'));
 
// latest news
$acl->addResource(new Zend_Acl_Resource('latest'), 'news');
 
// announcement news
$acl->addResource(new Zend_Acl_Resource('announcement'), 'news');
// Marketing must be able to publish and archive newsletters and the
1.// latest news
2.$acl->allow('marketing',
3.            array('newsletter', 'latest'),
4.            array('publish', 'archive'));
5. 
6.// Staff (and marketing, by inheritance), are denied permission to
7.// revise the latest news
8.$acl->deny('staff', 'latest', 'revise');
9. 
10.// Everyone (including administrators) are denied permission to
11.// archive news announcements
12.$acl->deny(null, 'announcement', 'archive');
echo $acl->isAllowed('staff', 'newsletter', 'publish') ?
1.     "allowed" : "denied";
2.// denied 
3.echo $acl->isAllowed('marketing', 'newsletter', 'publish') ?
4.     "allowed" : "denied";
5.// allowed 
6.echo $acl->isAllowed('staff', 'latest', 'publish') ?
7.     "allowed" : "denied";
8.// denied 
9.echo $acl->isAllowed('marketing', 'latest', 'publish') ?
10.     "allowed" : "denied";
11.// allowed 
12.echo $acl->isAllowed('marketing', 'latest', 'archive') ?
13.     "allowed" : "denied";
14.// allowed 
15.echo $acl->isAllowed('marketing', 'latest', 'revise') ?
16.     "allowed" : "denied";
17.// denied 
18.echo $acl->isAllowed('editor', 'announcement', 'archive') ?
19.     "allowed" : "denied";
20.// denied 
21.echo $acl->isAllowed('administrator', 'announcement', 'archive') ?
22.     "allowed" : "denied";
23.// denied
Zend_Form
$form = new Zend_Form();
1.$form->setAction('/user/login')
2.     ->setMethod('post');
3. 
4.// Create and configure username element:
5.$username = $form->createElement('text', 'username');
6.$username->addValidator('alnum')
7.         ->addValidator('regex', false, array('/^[a-z]+/'))
8.         ->addValidator('stringLength', false, array(6, 20))
9.         ->setRequired(true)
10.         ->addFilter('StringToLower');
11. 
12.// Create and configure password element:
13.$password = $form->createElement('password', 'password');
14.$password->addValidator('StringLength', false, array(6))
15.         ->setRequired(true);
16. 
17.// Add elements to form:
18.$form->addElement($username)
19.     ->addElement($password)
20.     // use addElement() as a factory to create 'Login' button:
21.     ->addElement('submit', 'login', array('label' => 'Login'));

The Registry

A registry is a container for storing objects and values in the application space. By storing the value in a registry, the same object is always available throughout your application. This mechanism is an alternative to using global storage.
The typical method to use registries with Zend Framework is through static methods in the Zend_Registry class.

Thursday, April 29, 2010

To disable right click:
Note1:The following script works for IE6 and Netscape.

Note2:Right click cannot be disabled for Opera browsers!


<script>
var isNS = (navigator.appName == "Netscape") ? 1 : 0;

if(navigator.appName == "Netscape")
document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);

function mischandler(){
return false;
}

function mousehandler(e){
var myevent = (isNS) ? e : event;
var eventbutton = (isNS) ? myevent.which : myevent.button;
if((eventbutton==2)||(eventbutton==3)) return false;
}
document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;

Tuesday, February 2, 2010

Mysql Help

Get database size:
SELECT table_schema "Data Base Name", sum( data_length + index_length ) / 1024 / 1024 "Data Base Size in MB"
FROM information_schema.TABLES GROUP BY table_schema ; 

 
use REPLACE in mysql:
UPDATE table_name SET column_name = REPLACE(column_name,”original_string”,”replace_string”)

concate & replace extra space if any field is missing
SELECT CONCAT(COALESCE(CONCAT(salutation,' '),''),COALESCE(CONCAT(first_name,' '),''),COALESCE(surname,'')) DriverName

//to check mysql version from query
select version();

Sort in ENUM fields :
To sort in ENUM fields using ORDER BY clause on  use one of these techniques:
  • Specify the ENUM list in alphabetic order.:
    like : ORDER BY FIELD(alert_type,'For Sale','For Rent','Sale Agreed') desc
  • Make sure that the column is sorted alphabetically rather than by index number by coding ORDER BY CAST(col AS CHAR) or ORDER BY CONCAT(col)
Create Wordcase in mysql :
update survey_event_question_langs set response1= CONCAT(LEFT(`response1`, 1),lower(
SUBSTRING(`response1`, 2)))

Thursday, December 10, 2009

Interfaces in php

implements: (php5.x)

To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.

Note: A class cannot implement two interfaces that share function names, since it would cause ambiguity.

Note: Interfaces can be extended like classes using the extends operator.

Note: The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error.

interface a
{
public function foo();
}

interface b extends a
{
public function baz(Baz $baz);
}

// This will work
class c implements b
{
public function foo()
{
}

public function baz(Baz $baz)
{
}
}

Php Mysql Question

Ques. How can I set the time zone for MySQL to UK time?
Ans. You can also set environment variables in my.cnf; In the data (normally var) directory.

Ques. How do I set the browser timeout?
Ans. If your script is too complex to finish within the standard 30 seconds you can set a new value with the function: set_time_limit(900); this sets the timeout too 900 seconds / 15 minutes.

Ques. How to count number of parameters given in URL by POST?
Ans. echo count ($HTTP_POST_VARS); Or count($_POST)

Ques. How do I check whether a string contains HTML?
Ans. There are two ways you can do it, one is using a regular expression the other is comparing strings.
First the regular expression approach:
if (preg_match("/([\<])([^\>]{1,})*([\>])/i", $string)) {
echo "string contains html";
}
And here is the other approach:
if(strlen($string) != strlen(strip_tags($string)){
echo "string contains HTML";
}
Ques. What Is a Session?
A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests.
There is only one session object available to your PHP scripts at any time. Data saved to the session by a script can be retrieved by the same script or another script when requested from the same visitor.
Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.

Ques. 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() - strtotime()) / (60 * 60 * 24);
echo "Number of days since '2006-07-01': $days";
OR:
$dateparts1=explode('-', $strDate);
$dateparts2=explode('-', $currDate);
$start_date=@gregoriantojd($dateparts1[1], $dateparts1[2], $dateparts1[0]);
$end_date=@gregoriantojd($dateparts2[1], $dateparts2[2], $dateparts2[0]);
$dateDiff = $end_date-$start_date;

As per Php manual, strtotime() only works date upto 2038.

Ques. What Is a Persistent Cookie?
A persistent cookie is a cookie which is stored in a cookie file permanently on the browser's computer. By default, cookies are created as temporary cookies which stored only in the browser's memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:
* Temporary cookies can not be used for tracking long-term information.
* Persistent cookies can be used for tracking long-term information.
* Temporary cookies are safer because no programs other than the browser can access them.
* Persistent cookies are less secure because users can open cookie files see the cookie values.

Ques. When are you supposed to use endif to end the conditional statement?
When the original if was followed by : and then the code block without braces.

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

Ques. How can we encrypt and decrypt a data presented in a table using MySQL?
You can use functions: AES_ENCRYPT() and AES_DECRYPT() like:
AES_ENCRYPT(str, key_str); AES_DECRYPT(crypt_str, key_str)

Ques. How can we increase the execution time of a php script?
By the use of void set_time_limit(int seconds)
Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini. If seconds is set to zero, no time limit is imposed.

Ques. What are the functions for IMAP?
imap_body - Read the message body
imap_check - Check current mailbox
imap_delete - Mark a message for deletion from current mailbox
imap_mail - Send an email message

Ques. What is DDL, DML and DCL ?
If you look at the large variety of SQL commands, they can be divided into three large subgroups. Data Definition Language deals with database schemas and descriptions of how the data should reside in the database, therefore language statements like CREATE TABLE or ALTER TABLE belong to DDL. DML deals with data manipulation, and therefore includes most common SQL statements such SELECT, INSERT, etc. Data Control Language includes commands such as GRANT, and mostly concerns with rights, permissions and other controls of the database system.

Ques. You wrote a search engine that should retrieve 10 results at a time, but at the same time you’d like to know how many rows there’re total. How do you display that to the user?

SELECT SQL_CALC_FOUND_ROWS page_title FROM web_pages LIMIT 1,10;
SELECT FOUND_ROWS();

The second query (not that COUNT() is never used) will tell you how many results there’re total, so you can display a phrase “Found 13,450,600 results, displaying 1-10″. Note that FOUND_ROWS does not pay attention to the LIMITs you specified and always returns the total number of rows affected by query.

Ques. How do you find out which auto increment was assigned on the last insert?
SELECT LAST_INSERT_ID() will return the last value assigned by the auto_increment function. Note that you don’t have to specify the table name.
Ques. What does –i-am-a-dummy flag to do when starting MySQL?
Makes the MySQL engine refuse UPDATE and DELETE commands where the WHERE clause is not present.

Ques. When would you use ORDER BY in DELETE statement?
When you’re not deleting by row ID. Such as in DELETE FROM techpreparation_com_questions ORDER BY timestamp LIMIT 1. This will delete the most recently posted question in the table techpreparation_com_questions.

Ques. How can you see all indexes defined for a table?
SHOW INDEX FROM techpreparation_questions;

Ques. How would you change a column from VARCHAR(10) to VARCHAR(50)?
ALTER TABLE techpreparation_questions CHANGE techpreparation_content techpreparation_CONTENT VARCHAR(50).

Ques. How would you delete a column?
ALTER TABLE techpreparation_answers DROP answer_user_id.

Ques. How would you change a table to InnoDB?
ALTER TABLE techpreparation_questions ENGINE innodb;

Ques. When you create a table, and then run SHOW CREATE TABLE on it, you occasionally get different results than what you typed in. What does MySQL modify in your newly created tables?
1. VARCHARs with length less than 4 become CHARs
2. CHARs with length more than 3 become VARCHARs.
3. NOT NULL gets added to the columns declared as PRIMARY KEYs
4. Default values such as NULL are specified for each column

Ques. What’s the difference between CHAR_LENGTH and LENGTH?
The first is, naturally, the character count. The second is byte count. For the Latin characters the numbers are the same, but they’re not the same for Unicode and other encodings.

Ques. How do you convert a string to UTF-8?
SELECT (techpreparation_question USING utf8);

Ques. What do % and _ mean inside LIKE statement?
% corresponds to 0 or more characters, _ is exactly one character.

Ques. What does + mean in REGEXP?
At least one character.

Ques. What’s the difference between Unix timestamps and MySQL timestamps?
Internally Unix timestamps are stored as 32-bit integers, while MySQL timestamps are stored in a similar manner, but represented in readable YYYY-MM-DD HH:MM:SS format.

Ques. How do you convert between Unix timestamps and MySQL timestamps?
UNIX_TIMESTAMP converts from MySQL timestamp to Unix timestamp, FROM_UNIXTIME converts from Unix timestamp to MySQL timestamp.

Ques. Explain the usage of encapsulation?
Encapsulation specifies the different classes which can use the members of an object. The main goal of encapsulation is to provide an interface to clients which decrease the dependency on those features and parts which are likely to change in future. This facilitates easy changes to the code and features.

Ques. Explain about abstraction?
Abstraction can also be achieved through composition. It solves a complex problem by defining only those classes which are relevant to the problem and not involving the whole complex code into play.

Q.Is it possible to set a time expire page in PHP.?
Yes it is
Using header(“Expires: fri, 07 mar 2007 05:00:00 GMT”);
header(“Expires: fri, 07 mar 2007 05:00:00 GMT”);
?>

Q.How can we SAVE an image from a remote
web Server to my web server using PHP?
$file_rimg = fopen(“http://w3answers /image23.jpg”,’rb’);
$newfile_name_img = “/tmp/tutorial.file”;
$file_wnew = fopen($newfile_name_img,’wb’);
while (!feof($file_rimg)) {
$chunk_rd = fread($file_rimg,1024);
fwrite($file_wnew,$chunk_rd);
}
fclose($file_wnew);
fclose(file_rimg);
?>

Q.What is the output of 2^2 in php ?
The answer is 0 (Zero)
Important note
Everyone expected answer would be 4. But answer is zero. How it happened only in php ?
The ^ operator is different in each language.In PHP ^ means the bitwise exlusive or of the two numbers.

Q.What is the output of below script?
$x = 3;
switch ($x) {
case 2: echo ‘line 1′; break;
case 3:
case 4: echo ‘line 2′; break;
default: echo ‘line 3′;
}
?>
a. echo ‘line 3′; b. echo ‘line 2′; c. Error d. None of the above
Ans: b (Answer is line2)

Q.What is the output here?
$x = ‘raj’;
echo ‘Hello $x’;
?>
a. helloravj b. Parse error c. hello $x d. syntax error
ANS: c

Q.What output do you get here?
$list = array(“block”,”cut”,”pens”,”dogs”);
$list[] = “elephant”;
$list[] = “dragon”;
print “$list[4]“;
?>
a. Error b. elephant c. dragon d. nothing e. dogs
ANS: b (elephant)
Q. what is the output for following code?
echo 12+FALSE;
?>
Q. 12 b. no c. parse error d. T_ECHO error e. FALSE
ANS: 12

Q.What is the output ?
$x=7;
if ($x < 2) { echo “11″; }
elseif ($x < 16) { echo “12″; }
elseif ($x < 14) { echo “13″; }
elseif ($x > 14) { echo “14″; }
elseif ($x < 10) { echo “15″; }
else { echo “16″; }
?>
a.16 b.15 c.12 d.13
ANS:12

Q.What is the result here?
echo “test”;
$x = ”;
switch ($x) {
case “0″: echo “String”; br;
case 0: echo “”; break;
case NULL: echo “NULL”; br;
case FALSE: echo “heeder”; br;
case “”: echo “no string”; br;
default: echo “nothing else”; br;
}
?>
a. Something else b. Empty string c. Integer d. String
ANS: Integer
Q.What is the output?
function x ($y) {
function y ($z) {
return ($z*2); }
return($y+3); }
$y = 4;
$y = x($y)*y($y);
echo “$y”;
?>
a. None b. 54 c. 56 d. 58
ANS:56
Ques. how to track user logged out or not? when user is idle ?
By checking the session variable exist or not while loading th page. As the session will exist longer as till browser closes.
The default behaviour for sessions is to keep a session open indefinitely and only to expire a session when the browser is closed. This behaviour can be changed in the php.ini file by altering the line session.cookie_lifetime = 0 to a value in seconds. If you wanted the session to finish in 5 minutes you would set this to session.cookie_lifetime = 300 and restart your httpd server.
Ques. 1) what is session_set_save_handler in PHP? session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a local database.

Ques. what is garbage collection? default time ? refresh time?
Garbage Collection is an automated part of PHP , If the Garbage Collection process runs, it then analyzes any files in the /tmp for any session files that have not been accessed in a certain amount of time and physically deletes them. arbage Collection process only runs in the default session save directory, which is /tmp. If you opt to save your sessions in a different directory, the Garbage Collection process will ignore it. the Garbage Collection process does not differentiate between which sessions belong to whom when run. This is especially important note on shared web servers. If the process is run, it deletes ALL files that have not been accessed in the directory.
There are 3 PHP.ini variables, which deal with the garbage collector: PHP ini value name default session.gc_maxlifetime 1440 seconds or 24 minutes session.gc_probability 1 session.gc_divisor 100

Ques. PHP how to know user has read the email?
Using Disposition-Notification-To: in mailheader we can get read receipt.
Add the possibility to define a read receipt when sending an email.
It’s quite straightforward, just edit email.php, and add this at vars definitions:
var $readReceipt = null;
And then, at ‘createHeader’ function add:
if (!empty($this->readReceipt)) { $this->__header .= ‘Disposition-Notification-To: ‘ . $this->__formatAddress($this->readReceipt) . $this->_newLine; }

Ques. default session time ?
default session time in PHP is 1440 seconds or 24 minutes.

Ques. default session save path ?
Default session save path id temporary folder /tmp

Ques. how to track user logged out or not? when user is idle ?
By checking the session variable exist or not while loading th page. As the session will exist longer as till browser closes.
The default behaviour for sessions is to keep a session open indefinitely and only to expire a session when the browser is closed. This behaviour can be changed in the php.ini file by altering the line session.cookie_lifetime = 0 to a value in seconds. If you wanted the session to finish in 5 minutes you would set this to session.cookie_lifetime = 300 and restart your httpd server.

Ques. what is design pattern? singleton pattern?
A design pattern is a general reusable solution to a commonly occurring problem in software design.
The Singleton design pattern allows many parts of a program to share a single resource without having to work out the details of the sharing themselves.

Ques. what are magic methods?
Magic methods are the members functions that is available to all the instance of class Magic methods always starts with “__”. Eg. __construct All magic methods needs to be declared as public To use magic method they should be defined within the class or program scope Various Magic Methods used in PHP 5 are: __construct, __destruct, __call, __callStatic, __get, __set, __isset, __unset, __sleep, __wakeup, __toString, __invoke, __set_state and __clone

Ques. diff b/w php4 & php5 ? In PHP5
1. 1 Implementation of exceptions and exception handling
2. Type hinting which allows you to force the type of a specific argument

3. Overloading of methods through the __call function
4. Full constructors and destructors etc through a __constuctor and __destructor function
5. __autoload function for dynamically including certain include files depending on the class you are trying to create.
6. 6 Finality : can now use the final keyword to indicate that a method cannot be overridden by a child. You can also declare an entire class as final which prevents it from having any children at all.
7. Interfaces & Abstract Classes
8. Passed by Reference : In PHP4, everything was passed by value, including objects. This has changed in PHP5 — all objects are now passed by reference.
9. An __clone method if you really want to duplicate an object

Ques. what is cross site scripting? SQL injection?
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications which allow code injection by malicious web users into the web pages viewed by other users. Examples of such code include HTML code and client-side scripts.
SQL injection is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed

Ques. what is the major php security hole? how to avoid?
1. Never include, require, or otherwise open a file with a filename based on user input, without thoroughly checking it first.
2. Be careful with eval() Placing user-inputted values into the eval() function can be extremely dangerous. You essentially give the malicious user the ability to execute any command he or she wishes!
3. Be careful when using register_globals = ON It was originally designed to make programming in PHP easier (and that it did), but misuse of it often led to security holes
4. Never run unescaped queries
5. For protected areas, use sessions or validate the login every time.
6. If you don’t want the file contents to be seen, give the file a .php extension.

Ques. HOW we can transfer files from one server to another server without web forms?
using CURL we can transfer files from one server to another server. ex:
Uploading file
/* http://localhost/upload.php: print_r($_POST); print_r($_FILES); */
$ch = curl_init();
$data = array(‘name’ => ‘Foo’, ‘file’ => ‘@/home/user/test.png’);
curl_setopt($ch, CURLOPT_URL, ‘http://localhost/upload.php’);
curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch); ?>
output:
Array ( [name] => Foo ) Array ( [file] => Array ( [name] => test.png
[type] => image/png [tmp_name] => /tmp/phpcpjNeQ [error] => 0 [size] => 279 ) )
Ques. using CSS can we have a scroll to table?
No table won't support scrolling of its data. but we can do another workaround like placing a table
in a DIV layer and setting the DIV css property to overflow:auto will do that
Ques. Difference b/w OOPS concept in php4 and PHP5 ?
version 4’s object-oriented functionality was rather hobbled. Although the very basic premises of object oriented programming (OOP) were offered in version 4, several deficiencies existed, including:
• An unorthodox object-referencing methodology
• No means for setting the scope (public, private, protected, abstract) of fields and methods
• No standard convention for naming constructors
• Absence of object destructors
• Lack of an object-cloning feature
• Lack of support for interfaces

Ques. how to set session time out at run time or how to extend the session timeout at runtime?
// Get the current Session Timeout Value
$currentTimeoutInSecs = ini_get(’session.gc_maxlifetime’);
Change the Session Timeout Value
// Change the session timeout value to 30 minutes
ini_set(’session.gc_maxlifetime’, 30*60);
Sorting function attributes