PHP

6,829 views

Published on

Published in: Education, Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
6,829
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
62
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

PHP

  1. 1. 1
  2. 2. Outline History of PHP PHP Introduction Running XAMPP Dreamweaver Site Setup PHP file, PHP workings, running PHP. Some useful PHP functions Basic PHP syntax variables, operators, if...else...and switch, for, while, do while,for, functions, Cookies and Sessions .By: Eng Mohammed Hussein 2
  3. 3. History of PHP PHP developed into full-featured, scripting language for server-sideprogramming. Rasmus Lerdorf has invented PHP/FI language (1994-1995) using Perllanguage. PHP/FI has developed to PHP/FI2 using C language (1997). PHP3 developed by (Rasmus Lerdorf, Zeev Suraski, Andi Gutmans) withsupport connect to Database (1998). PHP4 emerged with more properties to PHP3 such as: Object oriented , free, open-source More support to database Sessions XML and JavaScript supported … PHP5 Current version3By: Eng Mohammed Hussein
  4. 4. PHP Introduction What is PHP? PHP stands for PHP: Hypertext Preprocessor. PHP is a server-side scripting language, like ASP. PHP scripts are executed on the server. PHP supports many databases (MySQL, Informix, Oracle,Sybase, Solid, PostgreSQL, Generic ODBC, etc.) PHP is an open source software. PHP is free to download and use. PHP is similar to JavaScript, only on a server-side language. PHP code is embedded in HTML using tags.4By: Eng Mohammed Hussein
  5. 5. PHP Introduction What is a PHP File? PHP files can contain text, HTML tags and scripts PHP files are returned to the browser as plain HTML PHP files have a file extension of ".php", ".php3", or ".phtml" When a page was requested, the server recognizes PHPcontent via the file extension (.php). The server executes the PHP code, and the PHP page resultsis showing to the client as HTML page. the PHP code never appear to users, only the output in theHTML page.By: Eng Mohammed Hussein 5
  6. 6. What is MySQL? MySQL is a database server. MySQL is ideal for both small and large applications. MySQL supports standard SQL. MySQL compiles on a number of platforms. MySQL is free to download and use. PHP + MySQL PHP combined with MySQL are cross-platform (you can develop inWindows and serve on a Unix platform). Why PHP? PHP runs on different platforms (Windows, Linux, Unix, etc.) PHP is compatible with almost all servers used today (Apache, IIS, etc.) PHP is FREE to download from the official PHP resource: www.php.net PHP is easy to learn and runs efficiently on the server side6By: Eng Mohammed Hussein
  7. 7. Where to Start? What do you Need? If your server supports PHP you dont need to do anything. Just create some .php files in your web directory, and the server will parsethem for you. Because it is free, most web hosts offer PHP support. However, if your server does not support PHP, you must install PHP. Here is a link to a good tutorial from PHP.net on how to install PHP5:http://www.php.net/manual/en/install.php To get access to a web server with PHP support, you can: Install XAMPP Apache (or IIS) on your own server, install PHP, andMySQL Or find a web hosting plan with PHP and MySQL support. If you download and Install XAMPP Apache server, you will find PHP, andMySql already existed inside the XAMPP application. But if you want toinstall each one separately then follow these links: Download PHP for free here: http://www.php.net/downloads.php Download MySQL for free here: http://www.mysql.com/downloads/7By: Eng Mohammed Hussein
  8. 8. Running XAMPP8By: Eng Mohammed HusseinJust click on Admin then thedefault browser will appear.
  9. 9. Security settings Security console MySQL & XAMPP directory protectionBy: Eng Mohammed Hussein 9http://localhost/security/xamppsecurity.phpUser: rootpassword: root
  10. 10. MySQL database Use this link for accessing theMySQL database: http://localhost/phpmyadmin/By: Eng Mohammed Hussein 10
  11. 11. Running PHP Examples Write in the browser URL bar http://localhost Put your site folder into this path : C:xampphtdocsyour folder Then in the browser URL, write your folder name afterlocalhost as: http://localhost/your folder/ To run a.php file on local server, just add the name of the fileas the following example: http://localhost/php/a.php11By: Eng Mohammed Hussein
  12. 12. Dreamweaver –Site Setup The pictures below will show you the steps that used tosetup your site inside local server in order to run php filesusing Adobe Dreamweaver.12By: Eng Mohammed Hussein
  13. 13. Dreamweaver -Site13By: Eng Mohammed Hussein
  14. 14. Dreamweaver -Servers14By: Eng Mohammed HusseinHere, how to add, delete and edit the servers information
  15. 15. Dreamweaver -Servers15By: Eng Mohammed Hussein
  16. 16. Dreamweaver -Servers16By: Eng Mohammed Hussein
  17. 17. PHP Syntax PHP code is executed on the server, andthe plain HTML result is sent to thebrowser. Basic PHP Syntax A PHP scripting block always starts with<?php and ends with ?>. A PHPscripting block can be placed anywhere inthe document. On servers with shorthand supportenabled you can start a scripting blockwith <? and end with ?>. For maximum compatibility, werecommend that you use the standardform (<?php) rather than the shorthandform.<?php?>17By: Eng Mohammed HusseinExample 1
  18. 18. PHP Syntax A PHP file normally contains HTML tags, just like anHTML file, and some PHP scripting code. We have an example of a simple PHP script which sendsthe text "Hello World" to the browser. Each code line in PHP must end with a semicolon. Thesemicolon is a separator and is used to distinguish oneset of instructions from another. There are two basic statements to output text with PHP:echo and print. In the example we have used the echostatement to output the text "Hello World". Note: The file must have a .php extension. If the file hasa .html extension, the PHP code will not be executed.<html><body><?phpecho "Hello World";?></body></html>18By: Eng Mohammed Hussein
  19. 19. Comments in PHP In PHP, we use // to make a single-line comment or /* and */ to make a large comment block.<html><body><?php//This is a comment/* This isa commentblock */?></body></html>19By: Eng Mohammed Hussein
  20. 20. PHP Variables A variable is used to store information. Variables in PHP Variables are used for storing values, like text strings, numbers orarrays. When a variable is declared, it can be used over and over again inyour script. All variables in PHP start with a $ sign symbol. The correct way of declaring a variable in PHP$var_name = value;20By: Eng Mohammed Hussein
  21. 21. PHP Variables New PHP programmers often forget the $ sign at thebeginning of the variable. In that case it will not work. Lets try creating a variable containing a string, and a variablecontaining a number:<?php$txt="Hello World!";$x=16;echo $txt;echo "<br>";echo $x;?>21By: Eng Mohammed Hussein
  22. 22. PHP is a Loosely Typed Language In PHP, a variable does not need to be declared before adding a value to it. In theprevious slide example , you have seen that you do not have to tell PHP which datatype the variable is ? . PHP automatically converts the variable to the correct datatype, depending on its value. In an other programming language, you have to declare (define) the type and nameof the variable before using it. In PHP, the variable is declared automatically whenyou use it. Rules for Variables A variable name must start with a letter or an underscore "_" A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ ) A variable name should not contain spaces. If a variable name is more than oneword, it should be separated with an underscore ($my_string), or withcapitalization ($myString)22By: Eng Mohammed Hussein
  23. 23. PHP String VariablesA string variable is used to store and manipulate text. String Variables in PHP String variables are used for values that contain characters. In this slide we are going to look at the most commonfunctions and operators used to manipulate strings in PHP. After we create a string we can manipulate it. A string can beused directly in a function or it can be stored in a variable. Below, the PHP script assigns the text "Hello World" to astring variable called $txt.<?php$r = “This is”BAD”; // ‫خطأ‬$t = "This is „good"; // ‫صحيح‬?><?php$txt="Hello World";echo $txt;?>23By: Eng Mohammed Hussein
  24. 24. The Concatenation Operator There is only one string operator in PHP. The concatenation operator (.) is used to put two string valuestogether. To concatenate two string variables together, use the concatenationoperator<?php$txt1="Hello World!";$txt2="What a nice day!";echo $txt1 . " " . $txt2;?>If we look at the code above you see that we used the concatenationoperator two times. This is because we had to insert a third string (aspace character), to separate the two strings.24By: Eng Mohammed Hussein
  25. 25. PHP String functions The strlen() function The strlen() function is used to return the length of a string. Lets find the length of a string:<?phpecho strlen("Hello world!");?>The length of a string is often used in loops or other functions,when it is important to know when the string ends. (i.e. in a loop,we would want to stop the loop after the last character in thestring).25By: Eng Mohammed Hussein
  26. 26. PHP String functions The strpos() function The strpos() function is used to search for a character/text withina string. If a match is found, this function will return the character positionof the first match. If no match is found, it will return FALSE. Lets see if we can find the string "world" in our string:<?phpecho strpos("Hello world!","world");?>The position of the string "world" in the example above is6. The reason that it is 6 (and not 7), is that the firstcharacter position in the string is 0, and not 1.26By: Eng Mohammed Hussein
  27. 27. Complete PHP String ReferenceFunctions Description PHPecho() Outputs strings 3chr() Returns a character from a specified ASCII value 3fprintf() Writes a formatted string to a specified output stream 5substr_compare() Compares two strings from a specified start position(binary safe and optionally case-sensitive)5strip_tags() Strips HTML and PHP tags from a string 3str_split() Splits a string into an array 5print() Outputs a string 3ord() Returns the ASCII value of the first character of astring3number_format() Formats a number with grouped thousands 3htmlspecialchars_decode()Converts some predefined HTML entities to characters 5ereg_replace() filter everything but numbers and used for security27By: Eng Mohammed Hussein
  28. 28. PHP Operators Operators are used to operate on values.Operator Description Example Result+ Addition x=2  x+2 4- Subtraction x=2  5-x 3* Multiplication x=4  x*5 20/ Division 15/5 , 5/2 3 , 2.5% Modulus (division remainder) 5%210%810%2120++ Increment x=5  x++ x=6-- Decrement x=5  x-- x=428By: Eng Mohammed Hussein
  29. 29. PHP-Assignment OperatorsOperator Example Is The Same As= x=y x=y+= x+=y x=x+y-= x-=y x=x-y*= x*=y x=x*y/= x/=y x=x/y.= x.=y x=x.y%= x%=y x=x%y29By: Eng Mohammed Hussein
  30. 30. PHP-Comparison OperatorsOperator Description Example== is equal to 5==8 returns false!= is not equal 5!=8 returns true<> is not equal 5<>8 returns true> is greater than 5>8 returns false< is less than 5<8 returns true>= is greater thanor equal to5>=8 returns false<= is less than orequal to5<=8 returns true30By: Eng Mohammed Hussein
  31. 31. PHP-Logical OperatorsOperator Description Example&& and x=6y=3(x < 10 && y > 1) returns true|| or x=6y=3(x==5 || y==5) returns false! not x=6y=3!(x==y) returns true31By: Eng Mohammed Hussein
  32. 32. PHP If...Else Statements Conditional statements are used to perform different actions basedon different conditions. Conditional Statements Very often when you write code, you want to perform differentactions for different decisions. You can use conditional statements in your code to do this.In PHP we have the following conditional statements: if statement - use this statement to execute some code only if aspecified condition is true if...else statement - use this statement to execute some code if acondition is true and another code if the condition is false if...elseif....else statement - use this statement to select one of severalblocks of code to be executed switch statement - use this statement to select one of many blocks ofcode to be executed32By: Eng Mohammed Hussein
  33. 33. The if Statement Use the if statement to execute some code only if a specifiedcondition is true.<html><body><?php$d=date("D");if ($d=="Fri") echo "Have a niceweekend!";?></body></html>33By: Eng Mohammed Hussein
  34. 34. The if...else Statement Use the if....else statement to execute some code if a condition is trueand another code if a condition is false. if a condition is true/false, the output "Have a nice weekend!" if thecurrent day is Friday, otherwise it will output "Have a nice day!":<html><body><?php$d=date("D");if ($d=="Fri")echo "Have a nice weekend!";elseecho "Have a nice day!";?></body></html>34By: Eng Mohammed Hussein
  35. 35. The if...elseif....else StatementThe following example willoutput "Have a niceweekend!" if the current day isFriday, and "Have a niceSunday!" if the current day isSunday. Otherwise it willoutput "Have a nice day!":<html><body><?php$d=date("D");if ($d=="Fri")echo "Have a nice weekend!";elseif ($d=="Sun")echo "Have a nice Sunday!";elseecho "Have a nice day!";?></body></html>35By: Eng Mohammed Hussein
  36. 36. PHP Switch Statement Conditional statements are usedto perform different actions basedon different conditions. Use the switch statement to selectone of many blocks of code to beexecuted.<html><body><?phpswitch ($x){case 1:echo "Number 1";break;case 2:echo "Number 2";break;case 3:echo "Number 3";break;default:echo "No number between 1 and3";}?></body></html>36By: Eng Mohammed Hussein
  37. 37. PHP - For Loops For Loops Loops execute a block of code a specified number of times, or while aspecified condition is true. The for loop is used when you know in advance how many times thescript should run. The foreach Loop The foreach loop is used to loop through arrays.By: Eng Mohammed Hussein 37<?phpfor ($i=1; $i<=5; $i++){echo "The number is " . $i . "<br />";}?><?php$x=array("one","two","three");foreach ($x as $value){echo $value . "<br />";}?>
  38. 38. PHP – while The while Loop The while loop executes a block of code while a condition is true. The do...while Loop The do...while statement will always execute the block of codeonce, it will then check the condition, and repeat the loop whilethe condition is true.<?php$i=1;while($i<=5){echo "The number is " . $i . "<br />";$i++;}?><?php$i=1;do{$i++;echo "The number is " . $i . "<br />";}while ($i<=5);?>By: Eng Mohammed Hussein 38
  39. 39. PHP Arrays An array stores multiple values in one single variable. A variable is a storage area holding a number or text. Theproblem is, a variable will hold only one value. An array is a special variable, which can store multiplevalues in one single variable. In PHP, there are three kind of arrays: Numeric array - An array with a numeric index Associative array - An array where each ID key isassociated with a value Multidimensional array - An array containing one or morearrays39By: Eng Mohammed Hussein
  40. 40. PHP- Numeric Arrays A numeric array stores each array element with a numericindex. There are two methods to create a numeric array.<?php$cars[0]="Saab";$cars[1]="Volvo";$cars[2]="BMW";$cars[3]="Toyota";echo $cars[0] . " and " . $cars[1] . " are Swedishcars.";?><?php$cars=array("Saab","Volvo","BMW","Toyota");echo $cars[0] . " and " . $cars[1] . " are Swedishcars.";?>1. In the example theindex are automaticallyassigned (the indexstarts at 0):2. In the example weassign the indexmanually:40By: Eng Mohammed Hussein
  41. 41. Associative Arrays An associative array, each ID key is associated with a value. When storing data about specific named values, a numericalarray is not always the best way to do it. With associative arrays we can use the values as keys andassign values to them.$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);<?php$ages[Peter] = "32";$ages[Quagmire] = "30";$ages[Joe] = "34";echo "Peter is " . $ages[Peter] . " years old.";?>Example 1Example 241By: Eng Mohammed Hussein
  42. 42. Multidimensional Arrays In a multidimensional array, each element in the main array can alsobe an array. And each element in the sub-array can be an array, andso on.$families = array("Griffin"=>array( "Peter“, "Lois“, "Megan“ ),"Quagmire"=>array("Glenn"),"Brown"=>array("Cleveland","Loretta","Junior"));echo "Is " . $families[Griffin][2] ." a part of the Griffin family?";Example 2Example 142By: Eng Mohammed Hussein
  43. 43. PHP Include File Server Side Includes (SSI) You can insert the content of one PHP file into another PHP file beforethe server executes it, with the include() or require() function. The two functions are identical in every way, except how they handleerrors: include() generates a warning, but the script will continue execution require() generates a fatal error, and the script will stop These two functions are used to create functions, headers, footers, orelements that will be reused on multiple pages. Server side includes saves a lot of work. This means that you cancreate a standard header, footer, or menu file for all your web pages.When the header needs to be updated, you can only update theinclude file, or when you add a new page to your site, you cansimply change the menu file (instead of updating the links on allyour web pages).By: Eng Mohammed Hussein 43
  44. 44. PHP include() Function The include() function takes all the content in a specifiedfile and includes it in the current file. If an error occurs, the include() function generates awarning, but the script will continue execution.By: Eng Mohammed Hussein 44<html><body><? php include("header.php"); ?><h1>Welcome to my home page!</h1><p>Some text.</p></body></html><a href="/default.php">Home</a><a href="/tutorials.php">Tutorials</a><a href="/about.php">About Us</a><a href="/contact.php">Contact Us</a><div class="leftmenu"><?php include("menu.php"); ?></div>
  45. 45. PHP require() Function The require() function is identical to include(), except thatit handles errors differently. If an error occurs, the include() function generates awarning, but the script will continue execution. Therequire() generates a fatal error, and the script will stop.By: Eng Mohammed Hussein 45<html><body><?phpinclude("wrongFile.php");echo "Hello World!";?></body></html>Error Example include() Function Error Example require() Function<html><body><?phprequire("wrongFile.php");echo "Hello World!";?></body></html>
  46. 46. PHP Functions In PHP, there are more than 700built-in functions. A function will be executed by acall to the function. You may call a function fromanywhere within a page.By: Eng Mohammed Hussein 46<html><body><?phpfunction writeName(){echo “Mohammed Hussein";}echo "My name is ";writeName();?></body></html>
  47. 47. PHP Function examplesBy: Eng Mohammed Hussein 47<html><body><?phpfunction add($x,$y){$total=$x+$y;return $total;}echo "1 + 16 = " . add(1,16);?></body></html>PHP Functions - Return values<html><body><?phpfunction writeName($fname,$punctuation){echo $fname . " Hussein" . $punctuation ."<br />";}echo "My name is ";writeName(“Mohammed",".");echo "My Sons name is ";writeName(“Abdulkareem M","!");echo "My brothers name is ";writeName(“Ali","?");?></body></html>PHP Functions - Adding parameters
  48. 48. PHP Forms and User Input The PHP $_GET and $_POST variables are used to retrieveinformation from forms, like user input. The most important thing to notice when dealing with HTMLforms and PHP is that any form element in an HTML page willautomatically be available to your PHP scripts.By: Eng Mohammed Hussein 48<html><body><form action="welcome.php" method="post">Name: <input type="text" name="fname" />Age: <input type="text" name="age" /><input type="submit" /></form></body></html>
  49. 49. PHP Forms on submit button When a user fills out the form and click on the submit button,the form data is sent to a PHP file, called "welcome.php":By: Eng Mohammed Hussein 49<html><body>Welcome <?php echo $_POST["fname"]; ?>!<br />You are <?php echo $_POST["age"]; ?> years old.</body></html>
  50. 50. PHP $_GET In PHP, the predefined $_GET variable is used to collectvalues in a form with method="get". Information sent from a form with the GET method isvisible to everyone (it will be displayed in the browsersaddress bar) and has limits on the amount of informationto send.By: Eng Mohammed Hussein 50<form action="welcome.php" method="get">Name: <input type="text" name="fname" />Age: <input type="text" name="age" /><input type="submit" /></form>When the user clicks the "Submit" button, the URL sent to the servercould look something like this:http://localhost/php/ welcome.php?fname=Peter&age=37
  51. 51. PHP $_GET The "welcome.php" file can now use the $_GET variableto collect form data (the names of the form fields willautomatically be the keys in the $_GET array):By: Eng Mohammed Hussein 51Welcome <?php echo $_GET["fname"]; ?>.<br />You are <?php echo $_GET["age"]; ?> years old!When to use method="get"?When using method="get" in HTML forms, all variable names andvalues are displayed in the URL.Note: This method should not be used when sending passwords orother sensitive information. However, because the variables aredisplayed in the URL, it is possible to bookmark the page. This canbe useful in some cases.Note: The get method is not suitable for very large variable values.It should not be used with values exceeding 2000 characters.
  52. 52. PHP $_POST In PHP, the predefined $_POST variable is used to collectvalues in a form with method="post". Information sent from a form with the POST method isinvisible to others and has no limits on the amount ofinformation to send. Note: However, there is an 8 Mb max size for the POSTmethod, by default (can be changed by setting thepost_max_size in the php.ini file).By: Eng Mohammed Hussein 52<form action="welcome.php" method="post">Name: <input type="text" name="fname" />Age: <input type="text" name="age" /><input type="submit" /></form>
  53. 53. PHP $_POST When the user clicks the "Submit" button, the URL willlook like this: The "welcome.php" file can now use the $_POST variableto collect form data (the names of the form fields willautomatically be the keys in the $_POST array):By: Eng Mohammed Hussein 53http://localhost/php/ welcome.phpWelcome <?php echo $_POST["fname"]; ?>!<br />You are <?php echo $_POST["age"]; ?> years old.
  54. 54. PHP $_POST When to use method="post"? Information sent from a form with the POST method is invisible toothers and has no limits on the amount of information to send. However, because the variables are not displayed in the URL, it isnot possible to bookmark the page. The PHP $_REQUEST Variable The predefined $_REQUEST variable contains the contents of both$_GET, $_POST, and $_COOKIE. The $_REQUEST variable can be used to collect form data sent withboth the GET and POST methods.By: Eng Mohammed Hussein 54Welcome <?php echo $_REQUEST["fname"]; ?>!<br />You are <?php echo $_REQUEST["age"]; ?> years old.
  55. 55. PHP Cookies What is a Cookie? A cookie is often used to identify a user. A cookie is a small filethat the server embeds on the users computer. Each time thesame computer requests a page with a browser, it will send thecookie too. With PHP, you can both create and retrieve cookievalues. How to Create a Cookie? The setcookie() function is used to set a cookie. Note: The setcookie() function must appear BEFORE the<html> tag.By: Eng Mohammed Hussein 55setcookie(name, value, expire, path, domain);Syntax:
  56. 56. Cookie Example 1 In the example below, we will create a cookie named"user" and assign the value “Mohammed" to it. We alsospecify that the cookie should expire after one hour:By: Eng Mohammed Hussein 56<?phpsetcookie("user", “Mohammed", time()+3600);?><html>.....Note: The value of the cookie is automatically URLencodedwhen sending the cookie, and automatically decoded whenreceived (to prevent URLencoding, use setrawcookie() instead).
  57. 57. Cookie Example 2 In this example the expiration time is set to a month (60sec * 60 min * 24 hours * 30 days).By: Eng Mohammed Hussein 57<?php$expire=time()+60*60*24*30;setcookie("user", "Alex Porter", $expire);?><html>.....
  58. 58. How to Retrieve a Cookie Value?The PHP $_COOKIE variable is used to retrieve a cookie value.By: Eng Mohammed Hussein 58<?php// Print a cookieecho $_COOKIE["user"];// A way to view all cookiesprint_r($_COOKIE);?>In this example we use the isset()function to find out if a cookie hasbeen set:<html><body><?phpif (isset($_COOKIE["user"]))echo "Welcome " .$_COOKIE["user"] . "!<br />";elseecho "Welcome guest!<br />";?></body></html>
  59. 59. How to Delete a Cookie? When deleting a cookie you should assure that theexpiration date is in the past.By: Eng Mohammed Hussein 59<?php// set the expiration date to one hour agosetcookie("user", "", time()-3600);?>
  60. 60. PHP Sessions A PHP session variable is used to store information about, or changesettings for a user session. Session variables hold information about onesingle 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 changesand then you close it. This is much like a Session. The computer knows whoyou are. It knows when you start the application and when you end. But onthe internet there is one problem: the web server does not know who you areand what you do because the HTTP address doesnt maintain state. A PHP session solves this problem by allowing you to store userinformation on the server for later use (i.e. username, shopping items, etc).However, session information is temporary and will be deleted after the userhas left the website. If you need a permanent storage you may want to storethe data in a database.By: Eng Mohammed Hussein 60
  61. 61. Starting a PHP Session Sessions work by creating a unique id (UID) for each visitor and storevariables based on this UID. The UID is either stored in a cookie or ispropagated in the URL. Before you can store user information in your PHP session, you must firststart up the session.By: Eng Mohammed Hussein 61<?php session_start(); ?><html><body></body></html>The code will register the users session with the server, allow you to startsaving user information, and assign a UID for that users session.
  62. 62. Storing a Session Variable The correct way to store and retrieve session variables is touse the PHP $_SESSION variable:By: Eng Mohammed Hussein 62<?phpsession_start();// store session data$_SESSION[views]=1;?><html><body><?php//retrieve session dataecho "Pageviews=". $_SESSION[views];?></body></html>
  63. 63. Session example In the example below, we create a simple page-viewscounter. The isset() function checks if the "views" variablehas already been set. If "views" has been set, we canincrement our counter. If "views" doesnt exist, we create a"views" variable, and set it to 1:By: Eng Mohammed Hussein 63<?phpsession_start();if(isset($_SESSION[views]))$_SESSION[views]=$_SESSION[views]+1;else$_SESSION[views]=1;echo "Views=". $_SESSION[views];?>
  64. 64. Destroying a Session If you wish to delete some session data, you can use theunset() or the session_destroy() function. The unset() function is used to free the specified sessionvariable.By: Eng Mohammed Hussein 64<?phpunset($_SESSION[views]);?><?phpsession_destroy();?>You can also completely destroy the session by calling thesession_destroy() function.Note: session_destroy() will reset your session and you will lose allyour stored session data.
  65. 65. PHP Sessions<?phpsession_start();if(isset($_SESSION[views]))$_SESSION[views]=$_SESSION[views]+1;else$_SESSION[views]=1;echo "Views=". $_SESSION[views];?><html><body><br><?phpecho "This is inside PHP<br>";echo "Hello World!<br>";$q= "How Are You Every Body?";Echo $q;?></body></html>F5Google Chrome1265By: Eng Mohammed Hussein
  66. 66. References1) http://www.w3schools.com/php/php_ref_string.asp2) http://www.w3schools.com/php/php_looping.asp66By: Eng Mohammed Hussein

×