COMP 205 - Week 5 Dr. Chunbo Chu Agenda 1. Brief History of PHP 2. Basics 3. Advanced Brief History of PHP PHP (PHP: Hypertext Preprocessor) was created by Rasmus Lerdorf in 1994. It was initially developed for HTTP usage logging and server-side form generation in Unix. PHP 2 (1995) transformed the language into a Server-side embedded scripting language. Added database support, file uploads, variables, arrays, recursive functions, conditionals, iteration, regular expressions, etc. PHP 3 (1998) added support for ODBC data sources, multiple platform support, email protocols (SNMP,IMAP), and new parser written by Zeev Suraski and Andi Gutmans . PHP 4 (2000) became an independent component of the web server for added efficiency. The parser was renamed the Zend Engine. Many security features were added. PHP 5 (2004) adds Zend Engine II with object oriented programming, robust XML support using the libxml2 library, SOAP extension for interoperability with Web Services, SQLite has been bundled with PHP Brief History of PHP As of July 2007, PHP is used on 20,917,850 domains, 1,224,183 IP addresses. http://www.php.net/usage.php Source: Netcraft Why is PHP used? 1. Easy to Use Code is embedded into HTML. The PHP code is enclosed in special start and end tags that allow you to jump into and out of "PHP mode". <html> <head> <title>Example</title> </head> <body> <?php echo "Hi, I'm a PHP script!"; ?> </body> </html> How to output using PHP echo is the common method in outputting data. Since it is a language construct, echo doesn’t require parenthesis like print(). Output Text Usage: Output the value of a PHP variable: Echo has a shortcut syntax, but it only works with the “short open tag” configuration enabled on the server. <?php echo “Hello World”; World <?php echo “$hits”; ?> of hits <?= $hits ?> ?> // prints out Hello // prints out the number Examples 3. Other uses with echo Automatically generate the year on your pages. This will print out ©2009 UC Riverside. ©<?php echo date(“Y”); ?> UC Riverside You will need to escape any quotation marks with a backslash. <?php echo “I said \”She sells sea shells\” ”; ?> Why is PHP used? 2. Cross Platform Runs on almost any Web server on several operating systems. One of the strongest features is the wide range of supported databases Web Servers: Apache, Microsoft IIS, Caudium, Netscape Enterprise Server Operating Systems: UNIX (HP-UX,OpenBSD,Solaris,Linux), Mac OSX, Windows NT/98/2000/XP/2003 Supported Databases: Adabas D, dBase,Empress, FilePro (read-only), Hyperwave,IBM DB2, Informix, Ingres, InterBase, FrontBase, mSQL, Direct MS-SQL, MySQL, ODBC, Oracle (OCI7 and OCI8), Ovrimos, PostgreSQL, SQLite, Solid, Sybase, Velocis,Unix dbm Why is PHP used? 3. Cost Benefits PHP is free. Open source code means that the entire PHP community will contribute towards bug fixes. There are several add-on technologies (libraries) for PHP that are also free. PHP Software Free Platform Free (Linux) Development Tools Free PHP Coder, jEdit Server-side Script User-agent (web browser) requests a web page • User never sees the PHP, only the output http request • Cannot affect the browser or client PC • http response Server detects PHP code in page, executes the code, and sends the output to the user • Web page (with PHP Output) sent to PC Getting Started 1. How to escape from HTML and enter PHP mode PHP parses a file by looking for one of the special tags that tells it to start interpreting the text as PHP code. The parser then executes all of the code it finds until it runs into a PHP closing tag. HTML PHP CODE HTML <?php echo “Hello World”; ?> Starting tag Ending tag Notes <?php ?> Preferred method as it allows the use of PHP with XHTML <? ?> Not recommended. Easier to type, but has to be enabled and may conflict with XML <script language="php"> ?> Always available, best if used when FrontPage is the HTML editor <% %> Not recommended. ASP tags support was added in 3.0.4 Start your Virtual Machine Getting Started 2. Simple HTML Page with PHP The following is a basic example to output text using PHP. <html><head> <title>My First PHP Page</title> Semicolons are must! </head> <body> <?php echo "Hello World!"; ?> </body></html> •Copy the code onto your web server and save it as “hello.php”. •Notice that the semicolon is used at the end of each line of PHP code to signify a line break. Like HTML, PHP ignores whitespace between lines of code. (An HTML equivalent is <BR>) Variables All variables in PHP start with a $ sign symbol. $var_name = value; <?php $txt="Hello World!"; $x=16; ?> PHP: Loosely Typed A variable does not need to be declared before adding a value to it. Do not have to tell PHP which data type the variable is PHP automatically converts the variable to the correct data type, depending on its value. Compared to a strongly typed programming language.. Naming 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 one word, it should be separated with an underscore ($my_string), or with capitalization ($myString) PHP String Variables String variables are used for values that contains characters. A string can be used directly in a function or it can be stored in a variable. Below, the PHP script assigns the text "Hello World" to a string variable called $txt: <?php $txt="Hello World"; echo $txt; ?> PHP String Variables The Concatenation Operator There is only one string operator in PHP. The concatenation operator (.) is used to put two string values together. To concatenate two string variables together, use the concatenation operator: <?php $txt1="Hello World!"; $txt2="What a nice day!"; echo $txt1 . " " . $txt2; ?> The output: Hello World! What a nice day! PHP String Variables The strlen() function is used to return the length of a string. <?php echo strlen("Hello world!"); ?> The output: 12 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 the string). PHP String Variables The strpos() function is used to search for character within a string. If a match is found, this function will return the position of the first match. If no match is found, it will return FALSE. <?php echo strpos("Hello world!","world"); ?> The output: 6 The position of the string "world" in our string is position 6. The reason that it is 6 (and not 7), is that the first position in the string is 0, and not 1 PHP Operators Arithmetic Operators 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%2 10%8 10%2 1 2 0 ++ Increment x=5 x++ x=6 -- Decrement x=5 x-- x=4 PHP Operators Assignment Operators Operator 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%y PHP Operators Comparison Operators Operator Description == is equal to Example 5==8 returns false != > < >= is not equal is greater than is less than is greater than or equal to 5!=8 returns true 5>8 returns false 5<8 returns true 5>=8 returns false <= is less than or equal to 5<=8 returns true PHP Operators Logical Operators Operator Description && and Example x=6 y=3 (x < 10 && y > 1) returns true || or x=6 y=3 (x==5 || y==5) returns false ! not x=6 y=3 !(x==y) returns true Conditional Statements Conditional statements are very useful for displaying specific content to the user. The if Statement Use the if statement to execute some code only if a specified condition is true. if (condition) code to be executed if condition is true; <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; ?> </body> </html> Conditional Statements The if...else Statement if (condition) code to be executed if condition is true; else code to be executed if condition is false; <html> <body> <?php $d=date("D"); if ($d=="Fri") { echo "Hello!<br />"; echo "Have a nice weekend!"; echo "See you on Monday!"; } ?> </body> </html> <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; elseif ($d=="Sun") echo "Have a nice Sunday!"; else echo "Have a nice day!"; ?> </body> </html> Switch Statement switch (n) { case label1: code to be executed if n=label1; Don’t forget break! break; case label2: code to be executed if n=label2; break; default: code to be executed if n is different from both label1 and label2; } <html> <body> <?php switch ($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 and 3"; } ?> </body> </html> Array An array is a special variable, which can hold more than one value, at a time. $cars1="Saab"; $cars2="Volvo"; $cars3="BMW"; An array can hold all your variable values under a single name Three kinds of arrays: Numeric array - An array with a numeric index Associative array - An array where each ID key is associated with a value Multidimensional array - An array containing one or more arrays Numeric Arrays Numeric index $cars=array("Saab","Volvo","BMW","Toyota"); $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota"; echo $cars[0] . " and " . $cars[1] . " are Swedish cars." Associative Arrays When storing data about specific named values, a numerical array is not always the best way to do it. Each ID key is associated with a value. We can use the values as keys and assign values to them. $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); A different way <?php $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; echo "Peter is " . $ages['Peter'] . " years old."; ?> Multidimensional Arrays Each element in the main array can also be an array. Each element in the sub-array can be an array, and so 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?"; The code above will output: Is Megan a part of the Griffin family? Looping The same block of code to run over and over again Looping statements: while - loops through a block of code while a specified condition is true do...while - loops through a block of code once, and then repeats the loop as long as a specified condition is true for - loops through a block of code a specified number of times foreach - loops through a block of code for each element in an array while <html> <body> <?php $i=1; while($i<=5) { echo "The number is " . $i . "<br />"; $i++; } ?> </body> </html> do...while <html> <body> <?php $i=1; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<=5); ?> </body> </html> for for (init; condition; increment) { code to be executed; } Parameters: init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop) condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. increment: Mostly used to increment a counter (but can be any code to be executed at the end of the loop) for <html> <body> <?php for ($i=1; $i<=5; $i++) { echo "The number is " . $i . "<br />"; } ?> </body> </html> foreach <html> <body> <?php $x=array("one","two","three"); foreach ($x as $value) { echo $value . "<br />"; } ?> </body> </html> Activity Implement the following table in a multi-dimensional array "student“: Name ID Tom 0001 Grade 98 John Jane 81 70 0005 0006 Output the student table in form of a table. <html> <body> <?php $student=array( array("Tom","001", "98"), array("John","002", "81"), array("Jane", "003", "67") ); echo "<table border=1> <tr> <th>Name</th> <th>ID</th> <th>Score</th></tr>"; foreach ($student as $person) { echo "<tr>"; foreach ($person as $x) echo "<td>". $x."</td>"; echo "</tr>"; } echo "</table>"; ?> </body> Functions The real power of PHP: more than 700 built-in functions. To keep the browser from executing a script when the page loads, you can put your script into a function. A function will be executed by a call to the function. You may call a function from anywhere within a page. Create a PHP Function A function will be executed by a call to the function. function functionName() { code to be executed; } Adding parameters <html> <body> <?php function writeName($fname) { echo $fname . " Refsnes.<br />"; } echo "My name is "; writeName("Kai Jim"); echo "My sister's name is "; writeName("Hege"); echo "My brother's name is "; writeName("Stale"); ?> </body> </html> Return values <html> <body> <?php function add($x,$y) { $total=$x+$y; return $total; } echo "1 + 16 = " . add(1,16); ?> </body> </html> Activity Implement the following functions for the student table: A “grade($score)" function that convert a numeric score into a letter grade: $score >=90 A $score >=80 B $score >=70 C $score >=60 D $score <60 F Call grade($score) function and output the table with the letter grade Forms and User Input Any form element in an HTML page will automatically be available to your PHP scripts. <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> welcome.php <html> <body> Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old. </body> </html> •Browser validation is faster and reduces the server load. •Consider server validation if the user input will be inserted into a database $_GET Function Built-in $_GET function is used to collect values in a form with method="get". GET method Information is visible to everyone (it will be displayed in the browser's address bar) Has limits on the amount of information to send (max. 100 characters). Example <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 server could look something like this: http://www.w3schools.com/welcome.php?fname=Peter&age=37 The "welcome.php" file can now use the $_GET function to collect form data (the names of the form fields will automatically be the keys in the $_GET array): Welcome <?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 and values are displayed in the URL. Note: This method should not be used when sending passwords or other sensitive information! However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. Note: The get method is not suitable for large variable values; the value cannot exceed 100 characters. $_POST Function Built-in $_POST function is used to collect values from a form sent with method="post". POST method Information sent from a form is invisible to others Has no limits on the amount of information to send Example <form action="welcome.php" method="post"> 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 will look like this: http://www.w3schools.com/welcome.php The "welcome.php" file can now use the $_POST function to collect form data (the names of the form fields will automatically be the keys in the $_POST array): Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old. When to use method="post"? Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. However, because the variables are not displayed in the URL, it is not possible to bookmark the page. The PHP $_REQUEST Function The PHP built-in $_REQUEST function contains the contents of both $_GET, $_POST, and $_COOKIE. The $_REQUEST function can be used to collect form data sent with both the GET and POST methods. Example Welcome <?php echo $_REQUEST["fname"]; ?>!<br /> You are <?php echo $_REQUEST["age"]; ?> years old. Advanced features Server Side Includes (SSI) You can insert the content of one PHP file into another PHP file before the server executes it, with the include() or require() function. The two functions are identical in every way, except how they handle errors: 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, or elements that will be reused on multiple pages. Server side includes saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. When the header needs to be updated, you can only update the include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all your web pages). Example To implement templates on your website. Examples Step 1: Universal header and footer in a single file Create a file called header.php. This file will have all of the header HTML code. You can use Aptana/Dreamweaver to create the header, but remember to remove the closing </body> and </html> tags. <html><head> <title>UCR Webmaster Support Group</title> <link rel="stylesheet" type="text/css" href=“mycssfile.css"> </head> <body> <table width=80% height=30> <tr><td> <div align=center> Page Title </div> </td></tr></table> Examples Step 2: Universal header and footer in a single file Next, create a file called footer.php. This file will have all of the footer HTML code. <table width=80% height=30> <tr><td> <div align=center> UC Riverside Department<BR> <a href=mailto:someuser@ucr.edu>someuser@ucr.edu</a> </div> </td></tr></table> </body> </html> Examples Step 3: Universal header and footer in a single file This is the basic template that you will use on all of the pages. Make sure you name the files with a .php extension so that the server will process the PHP code. In this example, we assume the header and footer files are located in the same directory. <?php // header include(“header.php”); ?> Insert content here! <?php // footer include(“footer.php”); ?> Examples Benefits: - Any changes to header or footer only require editing of a single file. This reduces the amount of work necessary for site maintenance and redesign. - Helps separate the content and design for easier maintenance. Header Page 1 Content Page 2 Content Page 3 Content Footer Page 4 Content Page 5 Content File Handling fopen() function <html> <body> <?php $file=fopen("welcome.txt","r"); ?> </body> </html> Returns 0 (false) if unable to open the specified file. File open modes Modes Description r Read only. Starts at the beginning of the file r+ Read/Write. Starts at the beginning of the file w Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist a Append. Opens and writes to the end of the file or creates a new file if it doesn't exist a+ Read/Append. Preserves file content by writing to the end of the file x Write only. Creates a new file. Returns FALSE and an error if file already exists x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists Closing a File <?php $file = fopen("test.txt","r"); //some code to be executed fclose($file); ?> Check End-of-file if (feof($file)) echo "End of file"; Note: You cannot read from files opened in w, a, and x mode! Reading a File Line by Line echo fgets($file); Reading a File Character by Character echo fgetc($file); Examples To implement a simple page counter Examples <?php $COUNTER_FILE = “webcounter.txt"; if (file_exists($COUNTER_FILE)) { $fp = fopen("$COUNTER_FILE", "r+"); flock($fp, 1); $hits = fgets($fp, 4096); $hits += 1; fseek($fp,0); fputs($fp, $hits); flock($fp, 3); fclose($fp); } ?> Examples Next, output the counter value using PHP. Copy this line after the main block of code. This page has been viewed <?php echo“$hits”; ?> times. • That’s it! The result should look something similar to: Examples You can change the text around the <?php echo“$hits”; ?> tags to your liking. <?php echo“$hits”; ?> visitors. File Upload Create an Upload-File Form <html> <body> <form action="upload_file.php" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html> specifies which contenttype (binary input should data). be processed as a file. upload_file.php <?php if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; } ?> Exercise Write an HTML form and a PHP script that: Allow user to upload only JPG image files. Hint: For IE to recognize jpg files the type must be pjpeg, for FireFox it must be jpeg. When a JPG is uploaded, display it in the browser. Cookies A cookie is often used to identify a user. 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. To Create a Cookie setcookie(name, value, expire, path, domain); <?php setcookie("user", "Alex Porter", time()+3600); ?> <html> .... Note: The setcookie() function must appear BEFORE the <html> tag. Retrieve a Cookie Value The PHP $_COOKIE variable is used to retrieve a cookie value <html> <body> <?php if (isset($_COOKIE["user"])) echo "Welcome " . $_COOKIE["user"] . "!<br />"; else echo "Welcome guest!<br />"; ?> </body> </html> How to Delete a Cookie? When deleting a cookie you should assure that the expiration date is in the past. <?php // set the expiration date to one hour ago setcookie("user", "", time()-3600); ?> Sessions A PHP session allows 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(); ?> <html> <body> </body> </html> Storing a Session Variable The correct way to store and retrieve session variables is to use the PHP $_SESSION variable: <?php session_start(); // store session data $_SESSION['views']=1; ?> <html> <body> <?php //retrieve session data echo "Pageviews=". $_SESSION['views']; ?> </body> </html> The isset() function checks if the "views" variable has already been set <?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views']=$_SESSION['views']+1; else $_SESSION['views']=1; echo "Views=". $_SESSION['views']; ?> Destroying a Session The unset() function is used to free the specified session variable: <?php unset($_SESSION['views']); ?> Completely destroy the session by calling the session_destroy() function: <?php session_destroy(); ?> Additional Resources PHP Manual http://docs.php.net/ PHP Tutorial http://academ.hvcc.edu/~kantopet/php/index.php PHP Coder http://www.phpide.de/ JEdit http://www.jedit.org/ PHP's creator offers his thoughts on the PHP phenomenon, what has shaped and motivated the language, and where the PHP movement is heading http://www.oracle.com/technology/pub/articles/php_experts/rasmus_php.html Hotscripts – A large number of PHP scripts can be found at: http://hotscripts.com/PHP/Scripts_and_Programs/index.html Additional Information Some of the new functions added in version 5: Arrays: array_combine() - Creates an array by using one array for keys and another for its values array_walk_recursive() - Apply a user function recursively to every member of an array Date and Time Related: idate() - Format a local time/date as integer date_sunset() - Time of sunset for a given day and location date_sunrise() - Time of sunrise for a given day and location time_nanosleep() - Delay for a number of seconds and nano seconds Strings: str_split() - Convert a string to an array strpbrk() - Search a string for any of a set of characters substr_compare() - Binary safe optionally case insensitive comparison of two strings from an offset, up to length characters Other: php_check_syntax() - Check the syntax of the specified file php_strip_whitespace() - Return source with stripped comments and whitespace