Presentation is loading. Please wait.

Presentation is loading. Please wait.

PHP Tutorial - Anas Jaghoub Chapter 2 Control Structures.

Similar presentations


Presentation on theme: "PHP Tutorial - Anas Jaghoub Chapter 2 Control Structures."— Presentation transcript:

1 PHP Tutorial - Anas Jaghoub Chapter 2 Control Structures

2 PHP Tutorial - Anas Jaghoub Cookies and Sessions Before starting control structures in php, am going to illustrate two important concepts in web applications area, Cookies and Sessions. What is a Cookie? a cookie is a file embedded from the server to the user's computer. Its purpose is identify a user.

3 PHP Tutorial - Anas Jaghoub Cookies and Sessions When you deal with web applications, actually you don’t know who the user that uses your application is. Unlike traditional or real-life applications, For example, if you work in a bank, and a user asks you to exchange him money from his bank account, you have some remarks that identifies these person, such as: his name, identification number, his picture, his signature, and more details that distinguishes him from others.

4 PHP Tutorial - Anas Jaghoub Cookies and Sessions If we want to apply this job online, we don’t know the user who deals with the application. So we make some procedures that help us distinguish one user from another. First thing is asking the user for a username, and password. Second thing is checking for compatibility with registered data in our database. Thirdly, if it is compatible then we’ll create a cookie that distinguishes the user from a guest. In some cases the user has privileges more than a guest. User could access data, where guest is not allowed. Otherwise the cookie will not be created, for one of two reasons, first one is the cookie file has already been set in the past, and its expiration date was not reached, or given username and password from the user are not compatible.

5 PHP Tutorial - Anas Jaghoub Cookies and Sessions How to create a cookie? To create a cookie in php we use a built-in function called setcookie that has three parameters. First parameter is cookie name, second one is cookie value, and last one is expiration time setcookie(“name”,value,expiration).

6 PHP Tutorial - Anas Jaghoub Cookies and Sessions Example: <?php $expiration = time() + 60 *60 * 1; // this cookie will expire after an hour. $value = “anas”; $name= “user”; setcookie(“$name”, “$value”, $expiration); /* this will set a cookie called user, its value anas, and will expire after an hour from executing this script */ ?>

7 PHP Tutorial - Anas Jaghoub Cookies and Sessions Notes: function time() returns value of current time as a Unix timestamp. $expiration value is the time when the cookie will be expired, in our example we need the cookie to expire after an hour from the execution, time() + 60*60*1 we use this format because function time deals with seconds, which means 60 seconds multiplied by 60 minutes gives an hour, we multiplied it with 1 to determine one hour. we could multiply it with any number of hours. $value is the value of the cookie we want to set. $name is the name of the cookie we want to set.

8 PHP Tutorial - Anas Jaghoub Cookies and Sessions How to retrieve a cookie? We might retrieve a cookie using an array called $_COOKIE, we’ll discuss arrays in more details in chapter 4. But, now we’ll use it by only telling you that this is an array, and how to use it in your script. To retrieve a cookie that has already been set do as followed:

9 PHP Tutorial - Anas Jaghoub Cookies and Sessions <?php echo $_COOKIE[“user”]; // will print cookie user value ?> Notes: We use $_COOKIE[“user”] to get value of a cookie called user, in our example we used $_COOKIE to print its value in the web page using echo.

10 PHP Tutorial - Anas Jaghoub Cookies and Sessions How to delete a cookie? In some cases we might want to delete a cookie before the expiration time has been reached. For example the user clicked on log out link in your page. When a user asks you to log him out from the page, it means that the user wants to delete information he entered, in another words he wants to delete the cookie file, but in fact, user doesn’t know what is a cookie, or in the best case he has minimum knowledge about cookies. So it is your responsible as a programmer to delete these cookies you had set before, and prevent your user information from being accessed by unauthorized users. To delete a cookie we use the same method to set a cookie, which means that we’ll use setcookie function again, but with expiration date in the past, for example $expiration = time() - 60*60; which means any time in the past. setcookie(“$name”, ”$value”, $expiration);

11 PHP Tutorial - Anas Jaghoub Cookies and Sessions What is a session? Php session is a variable used to store information about single user. Sessions are available to all pages in one application. Sessions are stored on the server for later use, unlike cookies that are stored on user computer. Session information is temporarily and will be deleted after the user has left the website.

12 PHP Tutorial - Anas Jaghoub Cookies and Sessions How do sessions work? 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 with the URL.

13 PHP Tutorial - Anas Jaghoub Cookies and Sessions How to start a session? To start a session simply call function session_start(); which will start your session. This function call must be before the tag.

14 PHP Tutorial - Anas Jaghoub Cookies and Sessions How to store a session variable? As we said before sessions have many advantages such as, it is being stored on the server, deleted after user navigates from your site, has UID, and more. One of the applications that you might use session in it, is getting online users and guests.

15 PHP Tutorial - Anas Jaghoub Cookies and Sessions To store a session we use built-in array called $_SESSION[]; Below an example for starting a session called views, which tells the visitor of your application, how many pages he had visited, we’ll now only put the structures for this application, and it will be improved and developed after taking a deep look at control structures.

16 PHP Tutorial - Anas Jaghoub Cookies and Sessions <?php // Page views // programmer Anas Jaghoub // created at 11/oct/2009 session_start(); $_SESSION[‘views’] = 1; // this starts a session called views // and stored temporarily at server. ?> You have visited pages at this visit to my site

17 PHP Tutorial - Anas Jaghoub Cookies and Sessions How to destroy a session? In order to destroy a session in php you could use one of these two built-in functions, unset(session name) or session_destroy(); Each function has advantages and times to use, depending on its properties, for example unset($_SESSION[‘views’]); this function call will reset $_SESSION[‘views’] and return it to the beginning status which is 1. Where calling session_destroy(); will completely delete your session and you will loose all your stored data.

18 PHP Tutorial - Anas Jaghoub Control Structures Control structures in php are same as many of programming languages, its syntax is most similar to c/c++ and perl. Nevertheless, PHP has one special control structure, distinguishes it from other programming languages.

19 PHP Tutorial - Anas Jaghoub Control Structures If Statement: if(condition) statement; If … else Statement if(condition) statement; else statement; If … elseif … else statement if(condition) statement; elseif(condition) statement; else statement;

20 PHP Tutorial - Anas Jaghoub Control Structures If Statement used to execute some statements if condition became true; for example if($x < 3) echo “Try again”; At this example if $x has value less than 3 then the condition is true, so Try again will be echo-ed on the web page. Otherwise it will not.

21 PHP Tutorial - Anas Jaghoub Control Structures If… else Statement, used to execute some action if condition became true. Or do something else if condition is false; for example if($x <=3) echo “Try Again”; else echo “You don’t have permission”; At this example if $x has value less than or equal to 3 then Try Again will be echo-ed. else You don’t have permission will be echo-ed. As a result one of the two blocks will be executed depending on the condition.

22 PHP Tutorial - Anas Jaghoub Control Structures If … elseif … else Statement used to execute some statements if condition is meeting some rules, if not you might do some actions to deal with another condition, or do general case. Example: <?php $x = 1; If($x <3) echo { “Try again”; $x++; } elseif($x == 3) echo { “Last chance”; $x++; } else echo “You don’t have permissions”; ?>

23 PHP Tutorial - Anas Jaghoub Control Structures Notes: In the previous script, suppose that $x has a value of two then first block will be executed, which means Try again will be echo-ed, and $x will be incremented by 1. If $x has a value of 3 then second block will be executed. Or last block will be executed if $x greater than 3.

24 PHP Tutorial - Anas Jaghoub Control Structures Switch Statement: Used to execute some statements depending on one case or more. Syntax: switch(x) { case label1: executed when x == label 1; break; case label2: executed when x==label2; break; default: executed when x did not match any label; }

25 PHP Tutorial - Anas Jaghoub Control Structures Notes: Switch statement sometimes called multiple selection statement, that’s because you might execute multiple blocks depending on your case. Unlike if statement. Domain of switch statement is first appearance of break keyword. Which means, your code will be executed until first break stops it. Default case does not need break label, because, often it is the last thing to be executed whether no labels matched your selection.

26 PHP Tutorial - Anas Jaghoub Control Structures Enhancement for Page views Script <?php session_start(); if(isset($_SESSION[‘views’])) $_SESSION[‘views’]++; else { $_SESSION[‘views’] = 1; } ?> you have visited this page times

27 PHP Tutorial - Anas Jaghoub Control Structures Notes: At previous script, we called a new built-in function called isset(). This function returns true or false depending on the given parameter. Its job is determining the given parameter has value or not. If given parameter has value and is not null, then it will return true; else it will return false. In our application we started a session by calling session_start(); this function call depends not on session value. It is only sets the server to store a session. Next, we checked for a session called views, using function isset(). This function will tell us that session views has been set before or not.

28 PHP Tutorial - Anas Jaghoub Control Structures Depending on the returned value of function isset, we’ll take our action, or in other words, do the purpose of the script which is telling the visitor how many pages he had visited from the time he opened the site. As we explained before, sessions are available to all pages in one application. Which means that any page you want to track user hits on it simply include this script to it. We’ll illustrate how to include scripts in your script, next.

29 PHP Tutorial - Anas Jaghoub Control Structure Suppose that function isset returned true, this will mean that, there is an exist session called views, this means that it is not the first page user had viewed at this visit. So the suitable action to be performed is incrementing number of views by one, $_SESSION[‘views’]++; If isset returned false, this means that session views is not exist, so we had to initialize it. By starting the counter from one. $_SESSION[‘views’] = 1; Remember that sessions has UID, and each visitor has his own session. Last thing is printing value of session views.

30 PHP Tutorial - Anas Jaghoub Server Side Includes (SSI) In order to organize your work, and be a professional programmer, simplify your code. There are many things you could do, to organize your code, and facilitate development acceleration to your application. Here I’ll put some advices to you as a programmer, that might help you in your job. First thing, simplify, and simplify… Make it easy. Your script should do only one job. this will facilitate handling errors. Second thing, it is not preferred that your function has more than three parameters to finish its job, this means that you can simplify it more. Use Loops only when needed. Don’t repeat your code. Divide your script in directories, and group codes that complete each other in the same directory. Use available (OPEN SOURCE Libraries) rather than build it yourself. This will save your time, and give your application more qualities. Remember “ Don’t re-invent the wheels”. Finally, think of simplest and shortest ways to do your mission. Of course it should be legal methods.

31 PHP Tutorial - Anas Jaghoub Server Side Includes (SSI) Suppose that in your application, there is a menu, that you need to be showed in more than one page. of course, you have not to copy and paste the menu in every page. What about if you want to add a new item to your menu? Shall you add to all pages copying and pasting!! It is not a programming idea. The best, and logical thing is put your menu in a file, and call this file where needed.

32 PHP Tutorial - Anas Jaghoub Server Side Includes (SSI) How to accomplish this? Save your menu in a file. For example “menu.php”. At each page you need your menu to appear, call the file by using one of these two functions include() or require(). Both functions are identical in their job, but, they differs in handling errors. include function will search for your file, if found it then will be included in your page, and so require. But if not found. If you used include, your script will continue working, and will not stop. Where require will show an error and your script completely will not work.

33 PHP Tutorial - Anas Jaghoub Server Side Includes (SSI) Example <?php require(“menu.php”); include(“wrong.php”); ?> If menu is found, the script will continue working, but wrong file will not stop working your script. Where to use? If your script depends completely on the included file, then use require. else use include. In my opinion, I prefer require.

34 PHP Tutorial - Anas Jaghoub Control Structures End Of Chapter 2


Download ppt "PHP Tutorial - Anas Jaghoub Chapter 2 Control Structures."

Similar presentations


Ads by Google