IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 3: Working with PHP Rob Gleasure R.Gleasure@ucc.ie www.robgleasure.com IS2803 Today’s lecture PHP variable types Conditional statements Loops Functions Comments PHP variable types As mentioned last week, PHP scripts are embedded within HTML between a <?php opening tag and ?> closing tag E.g., here is simple 'Hello World' page <html> <head><title>Hello PHP</title> </head> <body> <?php echo "Hello World!"; ?> </body> </html> PHP variable types We also spoke about variable scope <html> <head><title>String Concatenation</title> </head> <body> <?php $x = 0; // this variable is created outside any functions, i.e. is 'global' function functionName () { $x = 1; /* this makes a new $x, as the $x already created is out of scope */ } functionName(); echo "X is ".$x; // this will print out 0 ?> </body> </html> PHP variable types The global keyword lets a function know a variable exists globally <html> <head><title>String Concatenation</title> </head> <body> <?php $x = 0; // this variable is created outside any functions, i.e. is 'global' function functionName(){ global $x; /* now $x is the same as outside the function*/ $x = 1; } functionName(); echo "X is ".$x; // this will now print out 2 ?> </body> </html> PHP variable types Variables created within a function are destroyed when that function ends <html> <head><title>String Concatenation</title> </head> <body> <?php $x = 0; // this variable is created outside any functions, i.e. is 'global' function functionName(){ global $x; /* now $x is the same as outside the function*/ $x = 1; $y = 2; } functionName(); echo "X is ".$x; // this will print out 2 echo "<br>"; echo "Y is ".$y; // this will create a new null reference $y and print that ?> </body> </html> PHP variable types The static keyword stops variables being destroyed <html> <head><title>String Concatenation</title> </head> <body> <?php $x = 0; // this variable is created outside any functions, i.e. is 'global' function functionName(){ global $x; /* now $x is the same as outside the function*/ $x = 1; static $y; $y = $y+2; } functionName(); echo "X is ".$x; // this will print out 2 echo "<br>"; echo "Y is ".$y; // this still won't work, as $y can still only be accessed in functionName() ?> </body> </html> PHP variable types When we want to export these static variables, our best way is by returning them <html> <head><title>String Concatenation</title> </head> <body> <?php $x = 0; // this variable is created outside any functions, i.e. is 'global' function functionName(){ global $x; /* now $x is the same as outside the function*/ $x = 1; static $y; $y = $y+2; return $y; } echo "Y is ".functionName(); // this will print out 2 echo "<br>"; echo "X is ".$x; echo "<br>"; // this will print out 2 echo "Y is ".functionName(); // now this will print out 4 ?> </body> </html> PHP variable types PHP variables are Loosely Typed this means you do not need to declare a variable type. To store a value as a string, it is simply provided in, whilst numbers are provided without quotes e.g. <?php $txt = 'Hello'; $x = 16; ?> //this is stored as a string //this is stored as an integer PHP strings The most common form of manipulation is concatenation, where multiple strings are combined into one. This is done in PHP simply by putting a full-stop between each string segment, e.g. <html> <head><title>String Concatenation</title> </head> <body> <?php $txt1 = 'Another beautiful day… '; $txt2 = 'Writing code.'; $txt3 = $txt1.$txt2; echo $txt3; ?> </body> </html> PHP strings There are also numerous other functions, which search for the existence of substrings, check the length of a string, replace parts of strings, etc. A complete set of string-related functions can be found at http://www.w3schools.com/php/php_ref_string.asp PHP numeric variables Numeric variables in PHP have basically 3 kinds of operators Arithmetic operators Commonly we use: +, -, *, /, %, ++, and – Assignment operators Commonly we use: =, +=, and -= Comparison operators Commonly we use: ==, !=, >, <, >=, and <= PHP arrays In addition to numeric and string variables, PHP also allows for arrays As we saw already in JavaScript, arrays are basically a way to store a collection of related variables Each value stored in an array is contained at a specific index, beginning with the index 0 You can find a complete reference of array-related PHP functions at http://www.w3schools.com/php/php_ref_array.asp PHP arrays There are two ways to declare an array, e.g. if we wanted to make an array called $names to store the three string values ‘Enda’, ‘Eamon’, and ‘Micheal’, we would write it in one line $names=array('Enda','Eamon','Micheal'); Or we could assign the index manually $names[0] = 'Enda'; $names[1] = 'Eamon'; $names[2] = 'Micheal'; If we later wanted to print out the value of the first value in $names, we could write echo $names[0] ; // this will print out 'Enda' PHP arrays Try out the following code <html> <head><title>Arrays</title> </head> <body> <?php $namesA = array('Stan','Kyle'); $namesB[0] = 'Brian'; $namesB[1] = 'Meg'; echo $namesA[1]; echo "<br>"; echo $namesB[1]; ?> </body> </html> PHP arrays Note: if you don’t want a strictly ordered array, you can also use values as array keys in what are termed associative arrays e.g. <html> <head><title>Arrays</title> </head> <body> <?php $food_order["Max"] = 'Pizza'; $food_order["Jane"] = 'Salad'; $food_order["Alex"] = 'Crab'; echo "Max wants: ".$food_order["Max"]."<br />"; echo "Jane wants: ".$food_order["Jane"]."<br />"; echo "Alex wants: ".$food_order["Alex"]; ?> </body> </html> Conditional statements in PHP The same logical operators exist for both string and numeric variables in PHP as JavaScript, facilitating the same conditional statements Commonly we use: &&, ||, and !, in combination with comparison operators for numeric variables, or comparison functions for string variables In this way, we can check to see if certain conditions are met before deciding whether to execute some piece of code or loop If-Else Loops in PHP Our if-else statements look much the same, e.g. if ($var == 0 && strlen($var2) > 1) { //do something elseif ($var == 5 && strlen($var2) > 10) { //do something else }else{ //do default thing } Remember, only one piece of code will be executed, then the rest of the if-else statements will be skipped. This means if numerous if conditions are true, only the code in the first if loop will be executed. If-Else Loops in PHP Try out the following code <html> <head><title>Arrays</title> </head> <body> <?php $cat_has_funny_face = 'true'; if ($cat_has_funny_face == 'true'){ echo "This cat can have cheeseburgers. "; }else{ echo "This cat may not have cheeseburgers, that's ridiculous. "; } ?> </body> </html> While loops in PHP Our while loops are also much the same in PHP e.g. while ($my_var == ‘false’) { /* This piece of code will keep executing until something changes the value of $my_var to be something other than ‘false’ */ } As are for-loops e.g. for ($num = 0; $num < 10; $num ++){ //do this code; } Functions in PHP Functions also work in much the same way as JavaScript New functions are created using the function keyword, followed by the name and parentheses describing any arguments The block of code contained within a function is surrounded by curly brackets, i.e. { …. } Every function returns a value in one of two ways 1) By using the keyword return 2) If no return statement is present, then a default value of null is returned PHP function names must begin with a letter or underscore (although unlike PHP variables, function names don’t begin with a dollar sign) Functions in PHP Once we have created a function, we can then reference it elsewhere e.g. Note that arguments’ <html> <head><title>PHP Functions</title> </head> <body> <?php function squareValue ($value) { return $value*$value; } echo squareValue(4); ?> </body> </html> names in PHP are also preceded by $ Comments in PHP We also still use // to make a single-line comment or /* and */ to make a large comment block. e.g. <html> <body> <?php // This is a comment on one line /* This is a block of commented text, which can continue over several lines */ ?> </body> </html> HTML forms and PHP When we discussed HTML inputs in lecture 20, we didn't really discuss the fact they are often wrapped in a <form> tag e.g. <form> First name: <input type="text" name="firstname"><br> Last name: <input type="text" name="lastname"> <input type="submit" value="submit details"> </form> However the <form> tag and its functionality becomes much more useful once we start using PHP A common use of PHP is to have HTML forms gather information, then send it to a PHP script on the server for processing HTML forms and PHP Forms come with two special attributes surrounding this ability to gather information and send it to a script The action attribute specifies the URL to send the data The method attribute specifies how to send this data e.g. <form action="myScript.php" method="post"> First name: <input type="text" name="firstname"><br> Last name: <input type="text" name="lastname"> <input type="submit" value="submit details"> </form> HTML forms and PHP Save the following code as lecture3.php <html> <head> <script type="text/javascript"> function formSubmit() { document.getElementById("myForm").submit();} </script> </head> <body> <p>Enter your details and press the "Submit form" button to submit the form.</p> <form id="myForm" action="form1.php" method="get"> First name: <input type="text" name="firstName" /><br /> Last name: <input type="text" name="lastName" /><br /> Home address: <input type="text" name="homeAddress" /><br /> Email address: <input type="text" name="emailAddress" /><br /> <input type="button" onclick="formSubmit()" value="Submit form" /> </form> </body> </html> HTML forms and PHP Save the following code as form1.php <html> <body> <?php $fname = $_GET["firstName"]; $lname = $_GET["lastName"]; $home = $_GET["homeAddress"]; $email = $_GET["emailAddress"]; $subject = "Hi!"; $body = "Your name is ".$fname." ".$lname.".<br> Your email is ".$email.", and you live at ".$home; echo $body."<br><br>"; echo "Incidentally, check out the URL in the header."; ?> </body> </html> HTML forms and PHP So how did form1.php handle the data that we sent it? Method = 'get' The predefined $_GET variable is used to collect values from a form sent with method='get' $_GET is essentially an associative array, so you need to specify which input field you wish to obtain data from $fname = $_GET["firstName"]; Note that this means it is crucial that the page containing the form provides input fields with a name attribute Method = 'post' We could also have sent the data from the form with method = 'post', in which case we would use the predefined $_POST variable <form id="myForm" action= “form1.php" method="post"> Like $_GET, $_POST is essentially an associative array, so you need to specify which input field you wish to obtain data from $fname = $_POST["firstName"]; Again, it is crucial that the page containing the form provides input fields with a name attribute Get vs. Post The difference is that 'get' sends the data in the URL header, whereas 'post' hides the data is the http request This means 'get' requests are less private but more efficient and easy to bookmark and/or re-execute However 'post' data is better when information is private or when large quantities are being provided HTML forms and PHP Try out the following code in lecture3.php <html> <head> <script type="text/javascript"> function formSubmit() { document.getElementById("myForm").submit();} </script> </head> <body> <p>Enter your details and press the "Submit form" button to submit the form.</p> <form id="myForm" action="form1.php" method="post"> First name: <input type="text" name="firstName" /><br /> Last name: <input type="text" name="lastName" /><br /> Home address: <input type="text" name="homeAddress" /><br /> Email address: <input type="text" name="emailAddress" /><br /> <input type="button" onclick="formSubmit()" value="Submit form" /> </form> </body> </html> HTML forms and PHP Then save this in form1.php <html> <body> <?php $fname = $_POST["firstName"]; $lname = $_POST["lastName"]; $home = $_POST["homeAddress"]; $email = $_POST["emailAddress"]; $subject = "Hi!"; $body = "Your name is ".$fname." ".$lname.".<br> Your email is ".$email.", and you live at ".$home; echo $body."<br><br>"; echo "Look at the difference in the URL."; ?> </body> </html> PHP and Cookies As we saw earlier in the year, 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. The setcookie() function is used to set a cookie. It commonly takes three arguments The name of the cookie The value of the cookie The expiration date of the cookie (in seconds). Note that if no time is set (or '0'), the cookie will expire when the browser closes e.g. setcookie ('car', 'toyota', '3600') //expires in an hour PHP and Cookies Similar to our $_GET and $_POST variables, cookies can be retrieved using a special associative array, i.e. $_COOKIE[] $my_var = $_COOKIE['car'] // $my_var will contain the string 'toyota' We can check if a cookie is set by using the isset function if(isset($_COOKIE['car'])) { echo $_ COOKIE['car'] } We delete cookies simply by setting the expiration date to be in the past setcookie ('car", '"", '-3600') PHP and Cookies Try out the following code <html> <head> <script type="text/javascript"> function formSubmit() { document.getElementById("myForm").submit();} </script> </head> <body> <?php if (isset($_COOKIE["username"])){ echo "Hi there ".$_COOKIE["username"]; } ?> <p>Enter your details and press the "Submit form" button to submit the form.</p> <form id="myForm" action="http://corvus2.ucc.ie/phd/rgleasure/is4428/php_files/cookie2.php" method="post"> First name: <input type="text" name="firstName" /><br /> Last name: <input type="text" name="lastName" /><br /> <input type="button" onclick="formSubmit()" value="Submit form" /> </form> </body> </html> PHP and Cookies Then copy this into form1.php <html> <body> <?php $fname = $_POST["firstName"]; $lname = $_POST["lastName"]; // create a cookie called 'username' to store the combined first and last name sent setcookie ('username', $fname." ".$lname); // redirect back to cookie1.php header( 'Location: http://corvus2.ucc.ie/phd/rgleasure/is4428/php_files/cookie1.php' ) ; ?> </body> </html> PHP and Session Variables Session variables are almost identical to cookies, except they store the information on the server, rather than the browser Session variables hold information on the server about one single user, and are available to all pages in one application 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 (don't worry about this for now). PHP and Session Variables The first thing we must do is start up the session <?php session_start(); ?> We may then store and retrieve session variables using another dedicated associative array, i.e. $_SESSION[] $_SESSION['my_session_var'] = 'Hello World!'; echo $_SESSION['my_session_var']; PHP and Session Variables To check whether a session variable is set, we can use the isset() function if(isset($_SESSION['my_session_var'])) { echo $_SESSION['my_session_var'];} When we wish to remove the session variables for a user, we can either remove a specific session variables with unset() unset($_SESSION['my_session_var']); Or all session variables for that user session_destroy(); HTML forms and PHP Try out this code in lecture3.php <html> <head> <script type="text/javascript"> function formSubmit() { document.getElementById("myForm").submit();} </script> </head> <body> <?php session_start(); if (isset($_SESSION["username"])){ echo "Hi there ".$_SESSION["username"]; } ?> <p>Enter your details and press the "Submit form" button to submit the form.</p> <form id="myForm" action= "form1.php" method="post"> First name: <input type="text" name="firstName" /><br /> Last name: <input type="text" name="lastName" /><br /> <input type="button" onclick="formSubmit()" value="Submit form" /> </form> </body> </html> HTML forms and PHP And this code in form1.php <html> <body> <?php $fname = $_POST["firstName"]; $lname = $_POST["lastName"]; //start the session session_start(); // create a session variable called 'username' to store name $_SESSION['username'] = $fname." ".$lname; // redirect back to cookie1.php header( 'Location: lecture3.php' ) ; ?> </body> </html> Exercise Add the following text to a new page in your folder in htdocs and save it as lecture3a.php <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-5"> <title>Lecture 3 main page</title> </head> <body> <h2> Welcome to lecture 3</h2> <form> Enter Login name <input type="text" > Enter password <input type="password" > <input type="submit" value ="login"> </form> </body> </html> Exercise Now add the following text to another new page in your folder in htdocs and save it as lecture3b.php <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-5"> <title>Lecture 3 login handler</title> </head> <body> <?php // create a variable called $username and set it to store the value posted as 'login_name' //start the session // create a session variable called 'username' to store the user's name // redirect back to cookie1.php ?> </body> </html> Exercise Add ‘send’ functionality to the form in lecture3a.php. This will require Set the name attribute of the login textfield to 'login_name' Set the name attribute of the password textfield to 'pword' Adding an action attribute to the form which specifies the relative URL of lecture3b.php Specifying a communication method (go for post) Exercise Next add the missing lines in lecture3b.php, i.e. Create a variable called $username and set it to store the value posted as 'login_name' Start the session Create a session variable called 'username' to store the user's name Redirect back to lecture3a.php Exercise Lastly, see if you can figure out how you can add PHP to lecture3a.php such that the form only displays when a user has not already entered a name and password and submitted that information. If the user has already entered a name, it should instead display "Hello " and the person's name, e.g. "Hello Tod" This requires that you: Start the session Check if $_SESSION[‘username'] is set If yes, display Hello " and the person's name If no, then use the echo command to output each whole line of HTML as a string Want to read more? Links and references Some PHP tutorials http://www.php.net/ http://www.tizag.com/phpT/ http://www.w3schools.com/php