php session

21
Sessions A session begins when a visiting client somehow identifies itself to the web server. The web server assigns the client a unique session id, which the client uses to re- identify itself as it moves from page to page on the website. Most of the time, these unique ids are stored in session cookies that expire after the client hasn't interacted with the server for some amount of time. The amount of time varies depending on the web application. For example, an online investment site might have very short sessions, so that if a user leaves her computer without logging out, another user who sits down at the same computer several minutes later cannot continue with the first user's session. Configuring Sessions In PHP, session management is configured in the php.ini file. To have a user's session start as soon as the user visits the website, the session.auto_start flag must be set to 1. The session length is also set in the php.ini file with the session.gc_maxlifetime variable. The default value is 1440 seconds (24 minutes).

Upload: argusacademy

Post on 07-Jul-2015

265 views

Category:

Education


0 download

DESCRIPTION

Php session

TRANSCRIPT

Page 1: Php session

SessionsA session begins when a visiting client somehow identifies itself to the web server.The web server assigns the client a unique session id, which the client uses to re-identify itself as it moves from page to page on the website. Most of the time, theseunique ids are stored in session cookies that expire after the client hasn't interactedwith the server for some amount of time. The amount of time varies depending onthe web application. For example, an online investment site might have very shortsessions, so that if a user leaves her computer without logging out, another user whosits down at the same computer several minutes later cannot continue with the firstuser's session.

Configuring SessionsIn PHP, session management is configured in the php.ini file. To have a user's sessionstart as soon as the user visits the website, the session.auto_start flag must be set to 1.The session length is also set in the php.ini file with the session.gc_maxlifetimevariable. The default value is 1440 seconds (24 minutes).

Page 2: Php session

Function Explanation

session_start()Starts new session if one does not exist. Continues current session if one exists.

session_unset() Unsets all session variables.

session_destroy() Kills session.

Session Functions

Ex 1. <?php//Begin a session and create a session variable in//the $_SESSION array.session_start();$_SESSION['Greeting'] = 'Hello world!';echo $_SESSION['Greeting'];?><hr><a href="Session2.php">Next page</a>

Page 3: Php session

Ex 2.<?php//Continue session, show that session variable still//exists and then unset the session variablesession_start();echo $_SESSION['Greeting'];unset($_SESSION['Greeting']);?><a href="Session3.php">Next page</a>

Ex 3.<?php//Continue session, show that session variable no longer//exists and then kill session.session_start();echo $_SESSION['Greeting'];session_unset();session_destroy();?>

Page 4: Php session

CookiesCookies are stored in text files that sit on the client machine. Web pages with theright permissions can read from and write to cookies. They are generally used totrack user information between visits.

In PHP, cookies are set with the setcookie() function, which can take severalparameters including:

The cookie's name (required).The cookie's value.The cookie's expiration date (if this isn't set, the cookie will expire when thebrowser window is closed).

The directory path on the server that can read the cookie.The domain name that can read the cookie.A flag indicating whether the cookie should only be read over https.

Page 5: Php session

Create a Cookie?The setcookie() function is used to set a cookie.Note: The setcookie() function must appear BEFORE the <html> tag. Syntaxsetcookie(name, value, expire, path, domain);

Example 1In 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:< ?phpsetcookie("user", "Alex Porter", time()+3600);?>

< html>.....Note: The value of the cookie is automatically URLencoded when sending thecookie, and automatically decoded when received (to prevent URLencoding, usesetrawcookie() instead).

Page 6: Php session

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:< ?php// Print a cookieecho $_COOKIE["user"];// A way to view all cookiesprint_r($_COOKIE);?>In the following example we use the isset() function to find out if a cookie has been set:< html>< body>< ?phpif (isset($_COOKIE["user"]))echo "Welcome " . $_COOKIE["user"] . "!<br>";elseecho "Welcome guest!<br>";?>< /body>< /html>

Page 7: Php session

PHP Simple E-Mail

The simplest way to send an email with PHP is to send a text email.In the example below we first declare the variables ($to, $subject, $message,$from, $headers), then we use the variables in the mail() function to send ane-mail:< ?php$to = "[email protected]";$subject = "Test mail";$message = "Hello! This is a simple email message.";$from = "[email protected]";$headers = "From:" . $from;mail($to,$subject,$message,$headers);echo "Mail Sent.";?>

Page 8: Php session

PHP Mail FormWith PHP, you can create a feedback-form on your website. The example below sends a text message to a specified e-mail address:< html>< body>

< ?phpif (isset($_REQUEST['email']))//if "email" is filled out, send email{//send email$email = $_REQUEST['email'] ;$subject = $_REQUEST['subject'] ;$message = $_REQUEST['message'] ;mail("[email protected]", $subject,$message, "From:" . $email);echo "Thank you for using our mail form";}

Page 9: Php session

else//if "email" is not filled out, display the form{echo "<form method='post' action='mailform.php'>Email: <input name='email' type='text'><br>Subject: <input name='subject' type='text'><br>Message:<br><textarea name='message' rows='15' cols='40'></textarea><br><input type='submit'></form>";}?>

< /body>< /html>

Page 10: Php session

What is an Exception

With PHP 5 came a new object oriented way of dealing with errors.Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.

This is what normally happens when an exception is triggered:The current code state is savedThe code execution will switch to a predefined (custom) exception handler functionDepending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the codeWe will show different error handling methods:Basic use of ExceptionsCreating a custom exception handlerMultiple exceptionsRe-throwing an exceptionSetting a top level exception handler

Page 11: Php session

Use of ExceptionsWhen an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block.If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message.Lets try to throw an exception without catching it:< ?php//create function with an exceptionfunction checkNum($number){if($number>1){throw new Exception("Value must be 1 or below");}return true;}

//trigger exceptioncheckNum(2);?>

Page 12: Php session

Databases Connection

A database is a collection of information / data that is organized so that it caneasily be retrieved, administrated and updated. Databases thereby enable theopportunity to create dynamic websites with large amounts of information. Forexample, all data on members of argus.net and all posts in the forums are storedin databases.

There are many different databases: MySQL, MS Access, MS SQL Server, OracleSQL Server and many others. In this tutorial, we will use the MySQL database.MySQL is the natural place to start when you want to use databases in PHP.

If you have a hosted website with PHP, MySQL is probably already installed on the server.

If you use XAMPP MySQL is already installed and ready to use on your computer. Just make sure MySQL is running in the Control Panel:

Page 13: Php session

In the rest of this lesson, we will look more closely at how you connect to yourdatabase server, before we learn to create databases and retrieve and update datain the following sessions.

Page 14: Php session

Connection to database server

First, you need to have access to the server where your MySQL database is located. This is done with the function mysql_connect with the following syntax:

mysql_connect(server, username, password)

Example of a MySQL connection with XAMPP (default settings):mysql_connect("localhost", "root", "") or die (mysql_error());

Create database and tables with phpMyAdmin

It can be useful to be able to create databases and tables directly in PHP. Butoften, it will be easier to use phpMyAdmin (or any other MySQL administrationtool), which is standard on most web hosts and XAMPP. The screendumps belowshows how to create a database and tables in phpMyAdmin.

Start by logging onto phpMyAdmin. Often, the address will be the same as yourMySQL server (eg. "http://mysql.myhost.com") and with the same username andpassword. In XAMPP, the address is http://localhost/phpmyadmin/.

When you are logged on, simply type a name for the database and press thebutton "Create":

Page 15: Php session

At some hosts, it's possible the have already created a database, and you maynot have the rights to create more. If that is the case, you obviously just use theassigned database.

To create a table, click on the tab "Databases" and choose a database byclicking on it:

Page 16: Php session

Then there will be a box titled "Create new table in database", where you type the name of the table and the number of columns and press the button "Go":

Page 17: Php session

Then you can name the columns and set the data type, etc.,

Insert data using SQLYou use MySQL to insert data in a database in the same way that you can use SQL to create databases and tables. The syntax of the MySQL query is:

INSERT INTO TableName(column1, column2, ...) VALUES(value1, value2, ...)

Page 18: Php session

Get data from database

The MySQL query returns a result in the form of a series of records. These records are stored in a so-called recordset. A recordset can be described as a kind of table in the server's memory, containing rows of data (records), and each record is subdivided into individual fields (or columns).A recordset can be compared to a table where each record could be compared to a row in the table. In PHP, we can run through a recordset with a loop and the function mysql_fetch_array, which returns each row as an array.The code below shows how to use mysql_fetch_array to loop through a recordset:<html><head> <title>Retrieve data from database </title> </head><body> <?php// Connect to database servermysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());// Select database mysql_select_db("mydatabase") or die(mysql_error());// SQL query$strSQL = "SELECT * FROM people"; // Execute the query (the recordset $rs contains the result)$rs = mysql_query($strSQL);

Page 19: Php session

// Loop the recordset $rs// Each row will be made into an array ($row) using mysql_fetch_arraywhile($row = mysql_fetch_array($rs)) {// Write the value of the column FirstName (which is now in the array $row)echo $row['FirstName'] . "<br />";} // Close the database connectionmysql_close(); ?> </body></html>

Page 20: Php session

Delete a record

When deleting a record, you can use the unique AutoNumber field in thedatabase. In our database, it is the column named id. Using this uniqueidentifier ensures that you only delete one record. In the next example, we deletethe record where id has the value 24:<html><head> <title>Delete data in the database</title> </head> <body><?php// Connect to database servermysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ()); // Select databasemysql_select_db("mydatabase") or die(mysql_error()); // The SQL statement that deletes the record $strSQL = "DELETE FROM people WHERE id = 24";mysql_query($strSQL);// Close the database connection mysql_close(); ?><h1>Record is deleted!</h1></body> </html>

Page 21: Php session

Update cells in the table "people“

The code below updates Donald Duck's first name to D. and changes the phone number to 44444444. The other information (last name and birthdate) are not changed. You can try to change the other people's data by writing your own SQL statements.<html><head> <title>Update data in database</title> </head> <body><?php// Connect to database server mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());// Select databasemysql_select_db("mydatabase") or die(mysql_error()); // The SQL statement is built$strSQL = "Update people set ";$strSQL = $strSQL . "FirstName= 'D.', ";$strSQL = $strSQL . "Phone= '44444444' "; $strSQL = $strSQL . "Where id = 22";// The SQL statement is executedmysql_query($strSQL); // Close the database connectionmysql_close();?> <h1>The database is updated!</h1> </body> </html>