COMP 205 - Week 5 Dr. Chunbo Chu. Agenda 1. Brief History of PHP 2. Basics 3. Advanced.

Slides:



Advertisements
Similar presentations
PHP I.
Advertisements

Introduction to PHP MIS 3501, Fall 2014 Jeremy Shafer
PHP – An Introduction.
PHP – An Introduction Albert Morita – UCR Libraries Systems Dept. December 9, 2004 Version 2.0.
SWU, Computer systems and technologies. The Objective of This Lecture To give you a very high-level overview of some of the tools for Web Programming.
XAMPP: Cross – Apache, MySQL, Php, Perl + FileZilla, Tomcat NetBeans: IDE PHP Installation.
PHP By Dr. Syed Noman Hasany. PHP PHP was originally created by Rasmus Lerdorf in PHP stands for PHP: Hypertext Preprocessor (a recursive acronym).
PHP PHP: Hypertext Preprocessing. What is PHP? PHP is a server-side scripting language designed specifically for the Web. An open source language PHP.
Introduction to PHP. PHP PHP is the Hypertext Pre-processor –Script language –Embedded into HTML –Runs as Apache module –Can use DB (MySQL, Oracle, Microsoft.
04/09/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
Advance Database Management Systems Lab no. 5 PHP Web Pages.
Introduction to PHP and Server Side Technology. Slide 2 PHP History Created in 1995 PHP 5.0 is the current version It’s been around since 2004.
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
PHP Tutorial By RAY BALIKI && ROY GHORAYEB. DEFINITION PHP is a powerful server-side scripting language for creating dynamic and interactive websites.
INTRODUCTION TO PHP Basic concept of PHP and Much More Prepared By: Farhan Nisar(7 th Semester) University of Peshawar.
PHP Forms and User Input The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input.
INTERNET APPLICATION DEVELOPMENT For More visit:
ITD 3194 Web Application Development Chapter 4: Web Programming Language.
PHP - Hypertext Preprocessor. Introduction PHP is a powerful server-side scripting language for creating dynamic and interactive websites. PHP is a powerful.
SCV1223 PHP - Hypertext Preprocessor. Introduction PHP is a powerful server-side scripting language for creating dynamic and interactive websites. PHP.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Cookies & Sessions.
PHP was created by Rasmus Lerdorf in It was initially server-side, traffic tracking script. PHP 2 (1995) Added database support, file uploads, regular.
INTERNET APPLICATION DEVELOPMENT For More visit:
PHP Tutorial - Anas Jaghoub Chapter 2 Control Structures.
PHP PHP: Hypertext Preprocessing Preston Brinks and Sean McKenzie.
Nael Alian Introduction to PHP
Open Source Software Unit – 3 Presented By Mr. R.Aravindhan.
PHP OVERVIEW. C ONTENT Introduction of PHP History and development Basics of PHP programming.
PHP2. PHP Form Handling The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input. Name: Age:
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
PHP. 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.
Julian Springer Room 42 Joe Slovo.  W3 schools recommend that you have a basic understanding of HTML and of JavaScript before attempting to grasp PHP.
Introduction to PHP Advanced Database System Lab no.1.
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.
WEB DEVELOPMENT WITH PHP/MYSQL. WEB DEVELOPMENT COURSE HAS DIFFERENT NAME IN DIFFERENT INSITUTES, THIS IS A CORE COURSE FOR BS/MS STUDENTS. THIS IS ALSO.
Introduction to PHP.
8 th Semester, Batch 2008 Department Of Computer Science SSUET.
Yasar Hussain Malik - NISTE. PHP Origins Rasmus Lerdorf PHP originally abbreviation for ‘Personal Home Pages’, now ‘PHP Hypertext Processor’ Other key.
IT ELECTIVE 2.  Web server Can refer to either the hardware (the computer) or the software (the computer application) that helps to deliver content that.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
SESSIONS 27/2/12 Lecture 8. ? Operator Similar to the if statement but returns a value derived from one of two expressions by a colon. Syntax: (expression)
Since you’ll need a place for the user to enter a search query. Every form must have these basic components: – The submission type defined with the method.
8 th Semester, Batch 2009 Department Of Computer Science SSUET.
Company LOGO In the Name of Allah,The Most Gracious, The Most Merciful King Khalid University College of Computer and Information System Web pages Development.
Web Page Designing With Dreamweaver MX\Session 1\1 of 9 Session 3 PHP Advanced.
Unit-6 Handling Sessions and Cookies. Concept of Session Session values are store in server side not in user’s machine. A session is available as long.
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
Session 11: Cookies, Sessions ans Security iNET Academy Open Source Web Development.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
CGS 3066: Web Programming and Design Spring 2016 PHP.
Unit 4 Working with data. Form Element HTML forms are used to pass data to a server. A form can contain input elements like text fields, checkboxes, radio-buttons,
PHP. 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.
1 Server Side scripting PHP. 2 What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are.
A pache M ySQL P hp Robert Mudge Reference:
Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.
PHP using MySQL Database for Web Development (part II)
Albert Morita – UCR Libraries Systems Dept.
Session 2 Basics of PHP.
Introduction to PHP “PHP is a server-side scripting language designed specifically for the Web. Within an HTML page, you can embed PHP code that will be.
* Lecture # 7 Instructor: Rida Noor Department of Computer Science
Introduction to PHP “PHP is a server-side scripting language designed specifically for the Web. Within an HTML page, you can embed PHP code that will be.
Albert Morita – UCR Libraries Systems Dept.
8th Semester, Batch 2008 Department of Computer Science SSUET.
PHP Introduction.
PHP.
HYPERTEXT PREPROCESSOR BY : UMA KAKKAR
PHP an introduction.
PHP-II.
SEEM 4540 Tutorial 4 Basic PHP based on w3Schools
Presentation transcript:

COMP 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 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, 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. 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". Example

echo is the common method in outputting data. Since it is a language construct, echo doesn’t require parenthesis like print(). Output Text Usage: // prints out Hello World Output the value of a PHP variable: // prints out the number of hits Echo has a shortcut syntax, but it only works with the “short open tag” configuration enabled on the server. How to output using PHP

Examples 3. Other uses with echo Automatically generate the year on your pages. This will print out ©2009 UC Riverside. © UC Riverside You will need to escape any quotation marks with a backslash.

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.

Server-side Script User-agent (web browser) requests a web page http request Server detects PHP code in page, executes the code, and sends the output to the user http response Web page (with PHP Output) sent to PC User never sees the PHP, only the output Cannot affect the browser or client 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. PHP CODE HTML

Start your Virtual Machine

Getting Started 2. Simple HTML Page with PHP The following is a basic example to output text using PHP. 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 ) Semicolons are must!

Variables All variables in PHP start with a $ sign symbol. $var_name = value;

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 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: The output: Hello World! What a nice day!

PHP String Variables The strlen() function is used to return the length of a string. 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. 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

PHP Operators Assignment Operators

PHP Operators Comparison Operators

PHP Operators Logical Operators

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;

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; "; echo "Have a nice weekend!"; echo "See you on Monday!"; } ?>

Switch Statement switch (n) { case label1: code to be executed if n=label1; 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; } Don’t forget break!

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

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 "; $i++; } ?>

do...while "; } while ($i

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 "; } ?>

foreach "; } ?>

Activity Implement the following table in a multi-dimensional array "student“: Output the student table in form of a table. NameIDGrade Tom John Jane000670

<?php $student=array( array("Tom","001", "98"), array("John","002", "81"), array("Jane", "003", "67") ); echo " Name ID Score "; foreach ($student as $person) { echo " "; foreach ($person as $x) echo " ". $x." "; echo " "; } echo " "; ?>

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 "; } echo "My name is "; writeName("Kai Jim"); echo "My sister's name is "; writeName("Hege"); echo "My brother's name is "; writeName("Stale"); ?>

Return values

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. Name: Age:

welcome.php Welcome ! You are years old. 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 Name: Age: When the user clicks the "Submit" button, the URL sent to the server could look something like this: 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. You are 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 Name: Age: When the user clicks the "Submit" button, the URL will look like this: 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 ! You are 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 ! You are 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 and tags. UCR Webmaster Support Group Page Title

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. UC Riverside Department

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. Page 1 Content Page 5 Content Page 3 Content Page 2 Content Page 4 Content Header Footer

File Handling fopen() function Returns 0 (false) if unable to open the specified file.

File open modes

Closing a 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

Next, output the counter value using PHP. Copy this line after the main block of code. This page has been viewed times. That’s it! The result should look something similar to:

Examples You can change the text around the tags to your liking. visitors.

File Upload Create an Upload-File Form Filename: specifies which content- type (binary data). input should be processed as a file.

upload_file.php 0) { echo "Error: ". $_FILES["file"]["error"]. " "; } else { echo "Upload: ". $_FILES["file"]["name"]. " "; echo "Type: ". $_FILES["file"]["type"]. " "; echo "Size: ". ($_FILES["file"]["size"] / 1024). " Kb "; 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);.... Note: The setcookie() function must appear BEFORE the tag.

Retrieve a Cookie Value The PHP $_COOKIE variable is used to retrieve a cookie value "; else echo "Welcome guest! "; ?>

How to Delete a Cookie? When deleting a cookie you should assure that the expiration date is in the past.

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 tag:

Storing a Session Variable The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:

The isset() function checks if the "views" variable has already been set

Destroying a Session The unset() function is used to free the specified session variable: Completely destroy the session by calling the session_destroy() function:

Additional Resources PHP Manual PHP Tutorial PHP Coder JEdit PHP's creator offers his thoughts on the PHP phenomenon, what has shaped and motivated the language, and where the PHP movement is heading Hotscripts – A large number of PHP scripts can be found at:

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_combine() array_walk_recursive() - Apply a user function recursively to every member of an array array_walk_recursive() Date and Time Related: idate() - Format a local time/date as integer idate() date_sunset() - Time of sunset for a given day and location date_sunset() date_sunrise() - Time of sunrise for a given day and location date_sunrise() time_nanosleep() - Delay for a number of seconds and nano seconds time_nanosleep() Strings: str_split() - Convert a string to an array str_split() strpbrk() - Search a string for any of a set of characters strpbrk() substr_compare() - Binary safe optionally case insensitive comparison of two strings from an offset, up to length characters substr_compare() Other: php_check_syntax() - Check the syntax of the specified file php_check_syntax() php_strip_whitespace() - Return source with stripped comments and whitespace php_strip_whitespace()