Session, Cookies, Implode & Explode function
A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.
PHP Session Variables
When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn’t maintain state.
A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.
Starting a PHP Session
Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the <html> tag:
<?php session_start(); ?>
The code above will register the user’s session with the server, allow you to start saving user information, and assign a UID for that user’s session.
Storing a Session Variable
The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
// store session data
//retrieve session data
echo “Pageviews=”. $_SESSION[‘views’];
In the example below, we create a simple page-views counter. The isset() function checks if the “views” variable has already been set. If “views” has been set, we can increment our counter. If “views” doesn’t exist, we create a “views” variable, and set it to 1:
echo “Views=”. $_SESSION[‘views’];
Destroying a Session
If you wish to delete some session data, you can use the unset() or the session_destroy() function.
The unset() function is used to free the specified session variable:
You can also completely destroy the session by calling the session_destroy() function:
Note: session_destroy() will reset your session and you will lose all your stored session data.
A cookie is often used to identify a user.
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.
How to Create a Cookie?
The setcookie() function is used to set a cookie.
Note: The setcookie() function must appear BEFORE the <html> tag.
setcookie(name, value, expire, path, domain);
In the example below, we will create a cookie named “user” and assign the value “Alex Porter” to it. We also specify that the cookie should expire after one hour:
setcookie(“user”, “Alex Porter”, time()+3600);
Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
You can also set the expiration time of the cookie in another way. It may be easier than using seconds.
setcookie(“user”, “Alex Porter”, $expire);
In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days).
How to Retrieve a Cookie Value?
The PHP $_COOKIE variable is used to retrieve a cookie value.
In the example below, we retrieve the value of the cookie named “user” and display it on a page:
// Print a cookie
// A way to view all cookies
In the following example we use the isset() function to find out if a cookie has been set:
echo “Welcome ” . $_COOKIE[“user”] . “!<br>”;
echo “Welcome guest!<br>”;
How to Delete a Cookie?
When deleting a cookie you should assure that the expiration date is in the past.
// set the expiration date to one hour ago
setcookie(“user”, “”, time()-3600);
The GET Method
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character.
- The GET method produces a long string that appears in your server logs, in the browser’s Location: box.
- The GET method is restricted to send upto 1024 characters only.
- Never use GET method if you have password or other sensitive information to be sent to the server.
- GET can’t be used to send binary data, like images or word documents, to the server.
- The data sent by GET method can be accessed using QUERY_STRING environment variable.
- The PHP provides $_GET associative array to access all the sent information using GET method.
The POST Method
The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING.
- The POST method does not have any restriction on data size to be sent.
- The POST method can be used to send ASCII as well as binary data.
- The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure.
- The PHP provides $_POST associative array to access all the sent information using POST method.
PHP implode() Function
The implode() function returns a string from the elements of an array.
Note: The implode() function accept its parameters in either order. However, for consistency with explode(), you should use the documented order of arguments.
Note: The separator parameter of implode() is optional. However, it is recommended to always use two parameters for backwards compatibility.
PHP explode() Function
The explode() function breaks a string into an array.
Note: The “separator” parameter cannot be an empty string.
Note: This function is binary-safe.
Posted By-: Vissicomp Technology Pvt. Ltd.
Website -: http://www.vissicomp.com
This entry was posted in Programming in Java and tagged cookies, Destroying a Session, How to Create a Cookie, How to Delete a Cookie, How to Retrieve a Cookie Value, Implode & Explode function, PHP Cookies, PHP explode() Function, PHP Session Variables, PHP Sessions, Session:, Starting a PHP Session, Storing a Session Variable, The GET Method, The POST Method.
JDBC Driver Types
JDBC driver is responsible for ensuring that an application has consistent and uniform access to the database. It receives the client applications request, translates it into a format that the database can understand and then presents the request to the database. The response is received by the JDBC driver, translated back into Java data format and presented to the client application.
The various types of JDBC drivers are as follows –
- JDBC-ODBC bridge plus ODBC driver(Type I): This driver provides JDBC access via ODBC drivers. Note that ODBC binary code, and in many cases database client code, must be loaded on each client machine that uses this driver. When used in the applications, the JDBC driver translates the request to an ODBC call which then translates the same call for the use with the database
i) This type of driver is cheaper.
ii) This kind of driver is most appropriate on a corporate network or in LANs where client installations are not a major problem, or for application server code written in Java in a three-tier architecture.
i) This driver is slower because of double translation (JDBC to ODBC, ODBC to DBMS)
ii) If the driver is downloaded as an applet, the security manager of applets will not allow access to local files. This means that the downloaded driver will not be able to access the ODBC driver files installed locally on the machine. For these situations, this driver is not a viable solution.
- Native-API partly-Java driver(Type II): This driver directly interacts with native driver. It is partly written in Java and partly in native code. The native code is known as Call Level Interface (CLI). The CLI libraries are responsible for the actual communications with the database server. This kind of driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.
i) This type of driver is faster than ODBC because there is no double translation.
i) It cannot be used with Applets.
ii) Requires client-side installations.
- JDBC-Net Pure Java Driver (Type III): This driver translates JDBC calls into a DBMS-independent net protocol, which are then translated to a DBMS protocol by a server. This net server middleware is able to connect its pure Java clients to different databases. In Type I and Type II drivers, the drivers are kept on the client side. In type III, the driver is divided into two parts – one part is kept on the client side and the other part is kept on the server side. The server side part contains the CLI libraries that actually interact with the database. The client part just converts the JDBC requests to driver specific network protocol. It then sends the request to a listener process (CLI) on the server. It is the responsibility of the server process to present the request to the DB server. So the communication between the applications and the DB server is 100% Java to Java.
i) It can be used with applets.
ii) It can be used in 3-tier architecture.
i) The clients use different types of network protocols. So the client part should send the JDBC calls through network specific protocol. As different clients use different types of network, the development of client part becomes tedious.
- Native-Protocol Pure Java Driver (Type IV): In this, JDBC itself is a native driver. This kind of driver converts JDBC calls directly into the network protocol used by DBMS. This allows a direct call from the client machine to the DBMS server and is an excellent solution for intranet access.
i) This is the fastest way of accessing databases using JDBC driver.
i) It is database specific.
Posted By-: Vissicomp Technology Pvt. Ltd.
Website -: http://www.vissicomp.com
Cookies VS Sessions
|1. Cookies are stored on client-side.||1. Sessions are stored on server-side.|
|2. Cookies are stored in files(Sec. storage device).||2. Sessions are stored in memory.|
|3. Since cookies are stored in files, the data is retained even if client disconnects from the server.||3. Since sessions are stored in memory, session objects are removed when client disconnects from server.|
|4. Cookies always store information in form of string.||4. Sessions can store any type of object.|
|5. Cookies are non-secure since they are stored in files on client-side.||5. Sessions are more secure because they are stored in server’s memory.|
ASP.NET state management
· Web pages rarely be stand alone. Web applications almost always need to track users who visit multiple pages, whether to provide personalization, store information about a user or to track usage for reporting purposes.
· State management is the process by which you maintain state and page information over multiple requests for the same or different pages.
· Whenever any request is sent, the interaction between the client and server can be either stateless or stateful.
Types of State Management
1) Client – Side State Management –view state, cookies, hidden fields, query string
2) Server – Side State Management –session state, application state
Client side State management Options:
i) Cookie: A cookie is a small piece of text stored on user’s computer. Usually, information is stored as name-value pairs. Cookies are used by websites to keep track of visitors. Every time a user visits a website, cookies are retrieved from user machine and help identify the user.
if (Request.Cookies[“UserId”] != null)
lbMessage.text = “Dear” + Request.Cookies[“UserId”].Value + “, Welcome to our website!”;
lbMessage.text = “Guest,welcome to our website!”;
If you want to store client’s information use the below code
- Cookies can be disabled on user browsers
- Cookies are transmitted for each HTTP request/response causing overhead on bandwidth
- Inappropriate for sensitive data
ii) Hidden fields:Hidden fields are used to store data at the page level. As its name says, these fields are not rendered by the browser. It’s just like a standard control for which you can set its properties. Whenever a page is submitted to server, hidden fields values are also posted to server along with other controls on the page. We can still use it to store insignificant data. We can use hidden fields in ASP.NET pages using following syntax
protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;
//to assign a value to Hidden field
Hidden1.Value=”Create hidden fields”;
//to retrieve a value
- Simple to implement for a page specific data
- Can store small amount of data so they take less size.
- Inappropriate for sensitive data
- Hidden field values can be intercepted(clearly visible) when passed over a network
iii)View State:View State can be used to store state information for a single user. View State is a built in feature in web controls to persist data between page post backs. You can set View State on/off for each control using EnableViewState property. By default, EnableViewState property will be set to true. View state mechanism poses performance overhead. View state information of all the controls on the page will be submitted to server on each post back. To reduce performance penalty, disable View State for all the controls for which you don’t need state. (Data grid usually doesn’t need to maintain state). You can also disable View State for the entire page by addingEnableViewState=false to @page directive. View state data is encoded as binary Base64 – encoded which add approximately 30% overhead. Care must be taken to ensure view state for a page is smaller in size. View State can be used using following syntax in an ASP.NET web page.
// Add item to ViewState
ViewState[“myviewstate”] = myValue;
//Reading items from ViewState
- Simple for page level data
- Can be set at the control level
- Overhead in encoding View State values
- Makes a page heavy
iv)Query strings:Query strings are usually used to send information from one page to another page. They are passed along with URL in clear text. Now that cross page posting feature is back in asp.net 2.0, Query strings seem to be redundant. Most browsers impose a limit of 255 characters on URL length. We can only pass smaller amounts of data using query strings. Since Query strings are sent in clear text, we can also encrypt query values. Also, keep in mind that characters that are not valid in a URL must be encoded using Server.UrlEncode.Let’s assume that we have a Data Grid with a list of products, and a hyperlink in the grid that goes to a product detail page, it would be an ideal use of the Query String to include the product ID in the Query String of the link to the product details page (for, productdetails.aspx?productid=4).
When product details page is being requested, the product information can be obtained by using the following codes:
- Simple to Implement
- Human Readable
- Client browser limit on URL length
- Cross paging functionality makes it redundant
- Easily modified by end user
Server Side State management:
As name implies, state information will be maintained on the server.
i)Application: Application State: ASP.NET allows you to save values using application state, a global storage mechanism that is accessible from all pages in the Web application. Application state is stored in the Application key/value dictionary. Once you add your application-specific information to application state, the server manages it, and it is never exposed to the client. Application state is a great place to store information that is not user-specific. By storing it in the application state, all pages can access data from a single location in memory, rather than keeping separate copies of the data. Data stored in the Application object is not permanent and is lost any time the application is restarted.
Application object is used to store data which is visible across entire application and shared across multiple user sessions. Data which needs to be persisted for entire life of application should be stored in application object.
ASP.NET provides three events that enable you to initialize Application variables (free resources when the application shuts down) and respond to Application errors:
a. Application_Start: Raised when the application starts. This is the perfect place to initialize Application variables.
b. Application_End: Raised when an application shuts down. Use this to free application resources and perform logging.
c. Application_Error: Raised when an unhandled error occurs. Use this to perform error logging.
· Variables and objects added to the application state are global to an Asp.net application. For example, we can create a variable called appvar with the value Hello and store it in the application state. To create appvar, we need to use the following statement:
· After the application in which you declared app var is executed, any page contained in the application can retrieve the value of the appvar. To read the value of the MyVariable, we need to use the following-
· Applications state is easy to use and is consistent with other .net framework classes.
· Storing information in application state involves maintaining only a single copy of the information.
· The data stored in application state is lost when the web server containing the application state fails due to server crash, upgrade or shut down.
· It requires server memory and can affect the performance of the server and the scalability of the web application.
ii) Session: Session object is used to store state specific information per client basis. It is specific to particular user. Session data persists for the duration of user session you can store session’s data on web server in different ways. Session state can be configured using the <session State> section in the application’s web.config file.
<sessionState mode = <“inproc” | “sqlserver” | “stateserver”>
cookieless = <“true” | “false”>
timeout = <positive integer indicating the session timeout in minutes>
sqlconnectionstring = <SQL connection string that is only used in the SQLServer mode>
server = <The server name that is only required when the mode is State Server>
port = <The port number that is only required when the mode is State Server>
Mode:This setting supports three options. They are InProc, SQLServer, and State Server
Cookie less:This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less one.
Timeout:This indicates the Session timeout vale in minutes. This is the duration for which a user’s session is active. Note that the session timeout is a sliding value; Default session timeout value is 20 minutes
SqlConnectionString:This identifies the database connection string that names the database used for mode SQLServer.
Server:In the out-of-process mode State Server, it names the server that is running the required Windows NT service: aspnet_state.
Port:This identifies the port number that corresponds to the server setting for mode State Server. Note that a port is an unsigned integer that uniquely identifies a process running over a network.You can disable session for a page using EnableSessionState attribute. You can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application.
sqlConnectionString=”data source=server;user id=freelance;password=freelance”
cookieless=”false” timeout=”20″ />
- Fastest mode
- Simple configuration
- Session data will be lost if the worker process or application domain recycles
- Not ideal for web gardens and web farms
This entry was posted in ASP.NET(C#), Programming in Java and tagged application state, Application: Application State, ASP.NET state management, Client – Side State Management –view state, Cookie, cookies, hidden fields, query string, Query strings, Server – Side State Management –session state, Session:, Types of State Management, View State.