PHP ZCE mock test, interview preparation, daily lessons under chalk talk

Thursday, December 20, 2012

Weird comparison of a string in PHP



Weird comparison of a string in PHP

Say there is a dropdown named message as
<select name='message'>
<option value=0>Please select Message</option>
<option value='decoded'>Decoded</option>
<option value='processing'>Processing</option>
</select>


Now I want to validate the form and throw an error if user dint selects anything. What I wrote is.


if($message == 0)
{
echo "Error!!!";
echo "Message is not yet received";
}



Can you see anything wrong in this code?
What's happening is, for all selected values of message drop down, it throws an error!!!

it's quite surprising ... :-O


Any guesses on why is it happening...


Let me tell you...
Reason is that while comparing $message with 0, where 0 is an int, php converts string to int. that is it compares
(int) $message to 0.



To my full surprise, interger casting of any string yields 0. Which is why for all selected values, the comparison gets bypassed.


Solution to this is.

if($message == '0')
{
echo "Error!!!";
echo "Message is not yet received";
}

Wednesday, December 19, 2012

Avoid two users trying to access with same session cookie data?

How would you avoid two users trying to access with the same session cookie data?

This is same as asking how would you avoid Session Fixation or Session Hijacking.



Solution:
  1. Regenerate the Session Id on each user request i.e.  call session_regenerate_id() at the beginning of each request.
  2. Fix the active time of a session. If a user is logged in from time more than time out value, automatically log off the User.
  3. Check the 'browser fingerprint' on each request. This is a hash, stored in a $_SESSION variable, comprising some combination of the user-agent header, client IP address, a salt value, and/or other information. 
  4. Check referrer: this does not work for all systems, but if we know that users of this site must be coming from some known domain we can discard sessions tied to users from elsewhere.







Below is a sample code to implement this.


$timeout = 3 * 60; // 3 minutes
$fingerprint = md5('SECRET-SALT'.$_SERVER['HTTP_USER_AGENT']);
session_start();
if ( (isset($_SESSION['last_active']) && (time() > ($_SESSION['last_active']+$timeout))) || (isset($_SESSION['fingerprint']) && $_SESSION['fingerprint']!=$fingerprint) || isset($_GET['logout']) ) 
{ 
         do_logout();
}
session_regenerate_id();
$_SESSION['last_active'] = time();
$_SESSION['fingerprint'] = $fingerprint;




Wednesday, December 5, 2012

git resolve merge or rebase conflicts

When you do rebase or merge on your local git repository, there are chances that snippet of code changed by you is also changes by one of your colleague.



If such case occurs, git has no clue on which one to choose and which one to reject. You need to dig into the files, see the changes and decide on which one to keep.Git helps us in doing so by means of two files.

1. It creates file_with_conflict.php.orig --> it contain your local, original file before merge happened.


2. file_with_conflict.php --> it notifies you of changes done by your colleague and how they are contradicting your changes.


3. You will find below symbols in file_with_conflict.php

<<<<<<< HEAD
changes in your local repository
========
changes done by your colleague
.>>>>>> commit name of your colleague


4. Meanings of these notations are as

<<<<<<<: Indicates the start of the lines that had a merge conflict. The first set of lines are the lines from the file that you were trying to merge the changes into.

=======: Indicates the break point used for comparison. Breaks up changes that user has committed (above) to changes coming from merge (below) to visually see the differences.

>>>>>>>: Indicates the end of the lines that had a merge conflict.



If you find it helpful or if you have any queries, please leave your valuable comments.

Tuesday, December 4, 2012

git remove untracked files from git status

git clean -f

git-clean - Remove untracked files from the working tree

git clean [-d] [-f] [-n] [-q] [-e <pattern>] [-x | -X] [--] <path>…

Thursday, November 15, 2012

jQuery check if an element with id exists

How would you if an element with particular id exists on the page?


$('#element').length == 0; // no element found

javascript OR jquery - get the calling function code

We all know javascript is a messy language. There may be a time when you have to fix some frontend bug, and you are wandering around javascript code to know its flow.

One solution to this problem is using attributes of arguments property. Such as

1. alert(arguments.callee);

It will alert the code of the function from this alert is being called.

2. alert(arguments.callee.caller);

It will alert the code of the function from which function containing alert was called.


Its quite a helpful thing!!! now say thanks :P

Tuesday, November 6, 2012

difference between echo and print in PHP

Question : What is the difference between echo and print in PHP? Why do you use one over the other?


Solution: 

print and echo both are more or less the same. Both are used to display strings. 

They are not actually functions in php. They are language constructs. Benefit of language construct is that you dont have to put parantheses for the argument list.

Differences are
  • print has a return value of 1 so it can be used in expressions whereas echo returns void.
  • echo can take multiple parameters. 
  • echo is slightly faster than print.

Monday, September 24, 2012

Classes and Basic Program to operate an elevator


Logical problem :


Write Classes and logic to operate an elevator in a building which has 20 floors. The classes and logic should cover all possible scenarios. Following points must be taken care of while making any assumptions:
·         There is only one elevator
·         There can be a maximum of 8 people at a time in the elevator
·         There are 20 buttons inside the elevator for each floor and 1 button for emergency alarm
·         Any number of these buttons could be pressed at any point of time
·         At each floor outside there are 2 buttons to instruct the elevator to either go up or down
·         At any point of time requests from outside (using 2 buttons) can come from any floor
·         The elevator processes requests in the order in which they are made but of course it stops at a floor which comes in between in its direction of motion even if the request was made later
·         When power goes off, the elevator reaches the nearest floor in its direction of motion


Below is solution that I wrote for this problem. If you find any correction required, please do comment.
I would be happy to know if this solution is helping you anywhere.



Class Diagram :




Basic Logic Program :

/**
Person Class Depicts person at various floors who may request Elavator by pressing Button;
@atFloor - Floor where person is
@requestDirection - Direction where he wants to go
**/

Class Person
{
atFloor;
requestDirection;
function pressButton(direction,floor)
{
this->requestDirection = direction;
this->atFloor = floor;
ElevatorController.requestElevator(person); //pass or call?
}

}




/**
ElevatorController class handles all the manipulations required to operate the elevator
@currentFloor - currentFloor of elevator
@currentDirection - direction where elevator is moving
@stopFloors - array of Floors keeping track of at what all floors does the elevator need to stop
@pendingQueue - array of Person Objects that are put in queue because they are out of way of elevator's current direction
**/


Class ElevatorController
{
const MAX_FLOORS = 20;
const MAX_PASSENGERS = 8;
const MAX_QUEUE = 20;
currentFloor;
currentDirection;
stopFloors[MAX_FLOORS];
pendingQueue[MAX_QUEUE];

function ElevatorController() //Constructor
{
this->currentFloor = 0;
this->currentDirection = 'NONE';
Person PendingQueue[MAX_QUEUE];
for(i = 0; i<MAX_FLOORS;i++)
{
stopFloors[i] = false;
}
}


/**
if elevator is idle or if request from floor is on the way, stop at the given floor
otherwise add it to queue
**/
function requestElevator(request)
{
if(this->currentDirection == 'NONE')
{
addtoStopFloors(request);
}
elseif(inBetweenWay(request) && sufficientPeople())
{
addtoStopFloors(request);
}
else
{
addtoQueue(request);
}
}

/**
if there are more stops in the current direction, move there and serve requests
else pick next requests fromt the pending queue
if other requests from the queue fall on the way, stop at those floors too
**/
function serveRequests()
{
if(next = getNextStopFloor)
{
moveTo(next);
}
else
{
request = getNextFromQueue();
addToStopFloors();
onTheWay = pickOnTheWayFromQueue();
foreach(onTheWay)
{
addToStopFloors();
}
}
}


/**
Add floor to stop floor array
**/
function addToStopFloors(request)
{
stopFloor[request.atFloor] = true;
}


/**
Depending on current direction, get next floor to stop at
**/
function getNextStopFloor()
{
if(this->currentDirection == 'UP')
{
for(i=this->currentFloor;i<=MAX_FLOOR;i++)
{
if(stopFloor[i])
return i;
}
}
elseif(this->currentDirection == 'DOWN')
{
for(i=this->currentFloor;i>=0;i--)
{
if(stopFloor[i])
return i;
}
}
else
return false;
}

/**
Check if request is in between the way of current direction
**/
function inBetweenWay(request)
{
if($this->currentDirection == request->requestDirection)
{
if($this->currentDirection  == 'UP' && request->atFloor > $this->currentFloor)
{
return yes;
}
elseif($this->currentDirection == 'DOWN' && request->atFloor < $this->currentFloor)
{
return yes;
}
else return false;
}
else return false;
}


/**
append Person to pending queue
**/
function addToQueue(request)
{
for(i=0;i<MAX_QUEUE;i++)
{
if(!pendingQueue[i])
pendingQueue[i] = request;
}
}


/**
get the next person from the pending queue to be served
shift the queue after fetching it
**/
function getNextFromQueue()
{
returnVal = pendingQueue[0];
sizeOfQueue = arrayCount(pedingQueue);
for(i=1;i<sizeOfQueue;i++)
{
pedingQueue[i-1] = pedingQueue[i];
}
unset(pendingQueue[sizeOfQueue-1]);
return returnVal;
}

/**
Pick persons from the queue that will fall on the way of current direction
and remove pits generated alongwith
**/
function PickOntheWayFromQueue()
{
sizeOfQueue = arrayCount(pedingQueue);
for(i=0;i<sizeOfQueue;i++)
{
if(inBetweenWay(pendingQueue[i].request))
{
returnVal[] = pendingQueue[i].request;
for(j=i+1;j<sizeOfQueue;j++)
{
pedingQueue[j-1] = pedingQueue[j];
}
unset(pending[i].request);
}
}
return returnVal;
}


/**
Check if passengers limit has been crossed
**/
function sufficientPeople()
{
if(this->noOfPeople > MAX_PASSENGERS)
return false;
else
return true;
}

/**
move the elevator to next floor in the direction of motion
**/
function moveToDefaultFloor()
{
Elevator->moveTo(this->currentFloor-1, this->currentFloor)
}


/**
removes all the pending requests and stop destinations
**/
function vanishAllRequests();
{
unsetStopFloors();
unsetPendingQueue();
}


/**
Destructor - execute when power go off to make the lift move to the floor in direction of motion
**/
~ElevatorController()
{
moveToDefaultFloor();
}
}


class Elevator
{
/**Move to the given floor given the current floor
operate the doors of elevator
keep a count of people in and out
**/
moveTo(floor,currentFloor)
{
if(floor >= currentFloor)
{
ElevatorController.currentDirection = 'UP';
for(i=currentFloor;i<=floor;i++)
}
elseif(floor < currentFloor)
{
ElevatorController.currentDirection = 'DOWN';
for(i=currentFloor;i>=floor;i--)
}
ElevatorController.currentFloor = i;
door->open();
door->countPeopleIn();
door->countPeopleOut();
door->close();
}

}

class StopButton
{
stopFloor;
pressButton(buttonNo)
{
this->stopFloor = buttonNo;
elevatorController->addToStopFloor(this->stopFloor);
}
}

class EmergencyButton
{
pressButton()
{
ElevatorController->moveToDefaultFloor();
ElevatorController->vanishAllRequests();
}
}

Monday, July 30, 2012

How conflict occurs in svn?


Many times, the SVN can automatically merge changes to different parts of a file. Conflicts can arise when changes appear that don’t gel: Joe wants to remove eggs and replace it with cheese (-eggs, +cheese), and Sue wants to replace eggs with a hot dog (-eggs, +hot dog).






Basic conflicts in SVN




At this point it’s a race: if Joe checks in first, that’s the change that goes through (and Sue can’t make her change).

When changes overlap and contradict like this, SVN may report a conflict and not let you check in — it’s up to you to check in a newer version that resolves this dilemma. 



A few approaches:

  • Re-apply your changes
    . Sync to the the latest version (r4) and re-apply your changes to this file: Add hot dog to the list that already has cheese.

  • Override their changes with yours
    . Check out the latest version (r4), copy over your version, and check your version in. In effect, this removes cheese and replaces it with hot dog.




Conflicts are infrequent but can be a pain. Usually I update to the latest and re-apply my changes.



How to Remove conflicts in svn


When we commit our changes on svn, we may get an error message:
$ svn commit -m "Updated README"
Sending    README
Transmitting file data .svn: Commit failed (details follow):
svn: Out of date: '/myproject/README'
It says that the file we want to commit has changed since we last updated it. Update the file to get it up-to-date again.
$ svn update
C   README
Updated to revision 6.
The 'C' indicates there is a conflict with the README file, and Subversion does not know how to solve this.
If we now take a look at README, we'll notice that there are several markers that indicate what parts of the code are conflicting. We can easily see what we changed, and what has changed in the repository:
<<<<<<< .mine
This is fun stuff!
=======
This is a documentation file
>>>>>>> .r6

What are our options?

We have three options for resolving the conflict. Whatever to choose, make sure you confer with your colleague on the matter.


1. Scrap your changes, and go with the current work from your colleague.
This is the easiest solution. All you have to do is revert the changes you made, and update your working copy:
$ svn revert README
Reverted 'README'
$ svn update README
At revision 6.




2. Keep your changes, and dump whatever your colleague did.
Performing a simple 'ls' will show you that there are four files related to this conflict:
  • README – the original with markers
  • README.mine – your version
  • README.r5 – the original your worked with
  • README.r6 – the most update version from your colleague
To check in your changes, copy your version over the original and tell Subversion you have resolved the conflict.
$ cp README.mine README
$ svn resolved README
Resolved conflicted state of 'README'
The 'resolved' command will clean up all the special files that were generated.




3. Merge both version to a new version
If you choose this option, you will have to manually edit README. Remove the markers and add whatever you need to add here.
Subversion won't let you commit this file, so you'll have to mark it as 'resolved' as we saw during option 2:
$ svn resolved README
Resolved conflicted state of 'README'


To better understand why does conflicts occur visit http://php-geeks-wink.blogspot.in/2012/07/how-conflict-occurs-in-svn.html

Friday, July 6, 2012

Difference between innerHTML and appendChild

Jquery / Javascript : What is the difference between innerHTML and appendChild?


Answer :

  • appendChild is used to insert new node in DOM.
  • innerHTML is a property of DOM that allows to replace content of an element with different HTML, which automatically gets parsed into DOM nodes.

Monday, June 11, 2012

How does MVC pattern work?

How does MVC pattern work?


MVC ie Model View Controller pattern is a methodology for separating the business
logic (model) from the display logic (view) and the decisional controls (controller).


When a User clicks on a URL say http://php-geeks-wink.blogspot.in/ below are the steps processed
1. Front Controller receives the request and sets up the environment.
2. Thereon request reaches the controller.
3. Controller interacts with Model to perform any db queries.
4. Control then reaches to View, preparing the response.
5. Response is then sent back to the browser.

Tuesday, June 5, 2012

Difference between div and table


What is the difference between a div and table? When will you prefer one over the other?

1. Tables are quite acceptable for displaying layout elements that are in a tabular layout format. On the other hand, divs do not restrict the layout to tabular format. Instead, a div is like a “floating box” that can be positioned anywhere you want.

2. Divs helps seperating content from presentation.

3. Table make it more difficult for the search engine to find relevant information.

Tuesday, May 22, 2012

Zend Certified Engineer ZCE PHP Basics Mock Test



Questions

1. Choose the selection that best matches the following statements:
      PHP is a _____ scripting language based on the ____ engine. It is primarily used to
      develop dynamic _____ content, although it can be used to generate ____ documents
      (among others) as well.

      A.   Dynamic, PHP, Database, HTML
      B.   Embedded, Zend, HTML, XML
      C.   Perl-based, PHP, Web, Static
      D.   Embedded, Zend, Docbook, MySQL
      E.   Zend-based, PHP, Image, HTML



2. Which of the following tags is not a valid way to begin and end a PHP code block?

      A.   <% %>
      B.   <? ?>
      C.   <?= ?>
      D.   <! !>
      E.   <?php ?>



3. Which of the following is not valid PHP code?

      A.   $_10
      B.   ${“MyVar”}
      C.   &$something
      D.   $10_somethings
      E.   $aVaR




4. What is displayed when the following script is executed?

                <?php
                    define(myvalue, "10");
                    $myarray[10] = "Dog";
                    $myarray[] = "Human";                                                                                         
                    $myarray['myvalue'] = "Cat";
                    $myarray["Dog"] = "Cat";
                    print "The value is: ";
                    print $myarray[myvalue]."\n";
               ?>

     A.    The value is: Dog
     B.    The value is: Cat
     C.    The value is: Human
     D.    The value is: 10
     E.    Dog



5. What is the difference between print() and echo()?

     A.    print() can be used as part of an expression, while echo() can’t
     B.    echo() can be used as part of an expression, while print() can’t
     C.    echo() can be used in the CLI version of PHP, while print() can’t
     D.    print() can be used in the CLI version of PHP, while echo() can’t
     E.    There’s no difference: both functions print out some text!



6. What is the output of the following script?

               <?php
                       $a  =  10;
                       $b  =  20;
                       $c  =  4;
                       $d  =  8;
                       $e  =  1.0;
                       $f  =  $c  + $d * 2;
                       $g  =  $f  % 20;
                       $h  =  $b  - $a + $c + 2;
                       $i  =  $h  << $c;
                       $j  =  $i  * $e;
                       print $j;
               ?>

     A.    128
     B.    42
     C.    242.0
     D.    256
     E.    342



                                                                                             
7. Which values should be assigned to the variables $a, $b and $c in order for the following
   script to display the string Hello, World!?

                <?php
                          $string = "Hello, World!";
                          $a = ?;
                          $b = ?;
                          $c = ?;
                          if($a) {
                                  if($b && !$c) {
                                          echo "Goodbye Cruel World!";
                                  } else if(!$b && !$c) {
                                          echo "Nothing here";
                                  }
                          } else {
                                  if(!$b) {
                                          if(!$a && (!$b && $c)) {
                                              echo "Hello, World!";
                                          } else {
                                              echo "Goodbye World!";
                                          }
                                  } else {
                                          echo "Not quite.";
                                  }
                          }
                ?>

       A.   False, True, False
       B.   True, True, False
       C.   False, True, True
       D.   False, False, True
       E.   True, True, True



8. What will the following script output?

                <?php
                $array = '0123456789ABCDEFG';
                $s = '';
                for ($i = 1; $i < 50; $i++) {
                          $s .= $array[rand(0,strlen ($array) - 1)];
                }
                echo $s;
                ?>
                                                                                         
        A. A string of 50 random characters
        B. A string of 49 copies of the same character, because the random number generator
            has not been initialized
        C. A string of 49 random characters
        D. Nothing, because $array is not an array
        E. A string of 49 ‘G’ characters



9. Which language construct can best represent the following series of if conditionals?

                 <?php
                          if($a == 'a') {
                                  somefunction();
                          } else if ($a == 'b') {
                                  anotherfunction();
                          } else if ($a == 'c') {
                                  dosomething();
                          } else {
                                  donothing();
                          }
                 ?>

        A.  A switch statement without a default case
        B.  A recursive function call
        C.  A while statement
        D.  It is the only representation of this logic
        E.  A switch statement using a default case



10. What is the best way to iterate through the $myarray array, assuming you want to modify the
    value of each element as you do?

                 <?php
                    $myarray = array ("My String",
                                        "Another String",
                                        "Hi, Mom!");
                 ?>

        A.  Using a for loop
        B.  Using a foreach loop
        C.  Using a while loop
        D.  Using a do…while loop
        E.  There is no way to accomplish this goal


                                                                                         
11. Consider the following segment of code:

                  <?php
                          define("STOP_AT", 1024);
                          $result = array();
                          /* Missing code */
                          {
                                   $result[] = $idx;
                          }
                          print_r($result);
                  ?>

    What should go in the marked segment to produce the following array output?
                  Array
                  {
                     [0] => 1
                     [1] => 2
                     [2] => 4
                     [3] => 8
                     [4] => 16
                     [5] => 32
                     [6] => 64
                     [7] => 128
                     [8] => 256
                     [9] => 512
                  }

         A.   foreach($result as $key => $val)
         B.   while($idx *= 2)
         C.   for($idx = 1; $idx < STOP_AT; $idx *= 2)
         D.   for($idx *= 2; STOP_AT >= $idx; $idx = 0)
         E.   while($idx < STOP_AT) do $idx *= 2



12. Choose the appropriate function declaration for the user-defined function is_leap(). Assume
    that, if not otherwise defined, the is_leap function uses the year 2000 as a default value:

                  <?php
                  /* Function declaration here */
                  {
                     $is_leap = (!($year %4) && (($year % 100) ||
                                 !($year % 400)));
                                                                                           
                   return $is_leap;
                }
                var_dump(is_leap(1987));         /* Displays false */
                var_dump(is_leap());             /* Displays true */
                ?>

        A.  function is_leap($year = 2000)
        B.  is_leap($year default 2000)
        C.  function is_leap($year default 2000)
        D.  function is_leap($year)
        E.  function is_leap(2000 = $year)



13. What is the value displayed when the following is executed? Assume that the code was
    executed using the following URL:
        testscript.php?c=25

                <?php
                         function process($c, $d = 25)
                         {
                                 global $e;
                                 $retval = $c + $d - $_GET['c'] - $e;
                                 return $retval;
                         }
                         $e = 10;
                         echo process(5);
                ?>

        A.  25
        B.  -5
        C.  10
        D.  5
        E.  0



14. Consider the following script:

                <?php
                         function myfunction($a, $b = true)
                         {
                                 if($a && !$b) {
                                         echo "Hello, World!\n";
                                 }
                                                                             
                         }
                         $s = array(0 => "my",
                                      1 => "call",
                                      2 => '$function',
                                      3 => ' ',
                                      4 => "function",
                                      5 => '$a',
                                      6 => '$b',
                                      7 => 'a',
                                      8 => 'b',
                                      9 => '');
                         $a = true;
                         $b = false;
                         /* Group A */
                         $name = $s[?].$s[?].$s[?].$s[?].$s[?].$s[?];
                         /* Group B */
                         $name(${$s[?]}, ${$s[?]});
                 ?>
    Each ? in the above script represents an integer index against the $s array. In order to
    display the Hello, World! string when executed, what must the missing integer indexes be?

        A.  Group A: 4,3,0,4,9,9 Group B: 7,8
        B.  Group A: 1,3,0,4,9,9 Group B: 7,6
        C.  Group A: 1,3,2,3,0,4 Group B: 5,8
        D.  Group A: 0,4,9,9,9,9 Group B: 7,8
        E.  Group A: 4,3,0,4,9,9 Group B: 7,8



15. Run-time inclusion of a PHP script is performed using the ________ construct, while
    compile-time inclusion of PHP scripts is performed using the _______ construct.

        A.  include_once, include
        B.  require, include
        C.  require_once, include
        D.  include, require
        E.  All of the above are correct



                                                                                       
16. Under what circumstance is it impossible to assign a default value to a parameter while
    declaring a function?

        A.  When the parameter is Boolean
        B.  When the function is being declared as a member of a class
        C.  When the parameter is being declared as passed by reference
        D.  When the function contains only one parameter
        E.  Never



17. The ____ operator returns True if either of its operands can be evaluated as True, but not both.
        Your Answer: ____________________________



18. How does the identity operator === compare two values?

        A. It converts them to a common compatible data type and then compares the resulting
            values
        B. It returns True only if they are both of the same type and value
        C. If the two values are strings, it performs a lexical comparison
        D. It bases its comparison on the C strcmp function exclusively
        E. It converts both values to strings and compares them



19. Which of the following expressions multiply the value of the integer variable $a by 4?
    (Choose 2)

        A.  $a *= pow (2, 2);
        B.  $a >>= 2;
        C.  $a <<= 2;
        D.  $a += $a + $a;
        E.  None of the above



20. How can a script come to a clean termination?

        A.  When exit() is called
        B.  When the execution reaches the end of the current file
        C.  When PHP crashes
        D.  When Apache terminates because of a system problem


For answers to above ZCE questions click here
http://www.php-geeks-wink.blogspot.in/search/label/zce-zend-certified-engineer-php-basic-mock-test-answers