- Origins - Rasmus Lerdorf Developed to allow him to track visitors to his Web site

Similar documents
- Origins - Rasmus Lerdorf Developed to allow him to track visitors to his Web site

Lecture 12. PHP. cp476 PHP

Lecture 7 PHP Basics. Web Engineering CC 552

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Chapter 11 Introduction to PHP

URLs and web servers. Server side basics. URLs and web servers (cont.) URLs and web servers (cont.) Usually when you type a URL in your browser:

Advanced Web Design. Origins and Uses of PHP

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel

COMS 469: Interactive Media II

PHP by Pearson Education, Inc. All Rights Reserved.

PHP. Interactive Web Systems

15.1 Origins and Uses of Ruby

CSC Web Programming. Introduction to JavaScript

PHP INTERVIEW QUESTION-ANSWERS

Princeton University COS 333: Advanced Programming Techniques A Subset of PHP

Final Exam. IT 3203 Introduction to Web Development. Rescheduling Final Exams. PHP Arrays. Arrays as Hashes. Looping over Arrays

Server side basics CSC 210

CERTIFICATE IN WEB PROGRAMMING

Web Programming Step by Step

CS313D: ADVANCED PROGRAMMING LANGUAGE

Full file at C How to Program, 6/e Multiple Choice Test Bank

C-LANGUAGE CURRICULAM

Creating HTML files using Notepad

PHP: The Basics CISC 282. October 18, Approach Thus Far

What is PHP? [1] Figure 1 [1]

Server side basics CS380

B. V. Patel Institute of BMC & IT 2014

Chapter 7. Expressions and Assignment Statements ISBN

INTERNET PROGRAMMING. Software Engineering Branch / 4 th Class Computer Engineering Department University of Technology

Web Scripting using PHP

Chapter 7. Expressions and Assignment Statements

They grow as needed, and may be made to shrink. Officially, a Perl array is a variable whose value is a list.

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Chapter 6 part 1. Data Types. (updated based on 11th edition) ISBN

Chapter 2: Basic Elements of C++

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Course Syllabus. Course Title. Who should attend? Course Description. PHP ( Level 1 (

Software II: Principles of Programming Languages. Why Expressions?

Web Scripting using PHP

Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types

PHP and MySQL for Dynamic Web Sites. Intro Ed Crowley

Server-side computing

COSC252: Programming Languages: Basic Semantics: Data Types. Jeremy Bolton, PhD Asst Teaching Professor

Full file at

PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37)

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

The Warhol Language Reference Manual

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

Expressions & Assignment Statements

PHP 1. Introduction Temasek Polytechnic

Govt. of Karnataka, Department of Technical Education Diploma in Computer Science & Engineering. Fifth Semester. Subject: Web Programming

Chapter 8 Statement-Level Control Structures

Course Outline. Introduction to java

Chapter 6. Data Types ISBN

PHP Hypertext Preprocessor

Client-Side Web Technologies. JavaScript Part I

13Holzner_index.qxd 3/23/05 1:51 PM Page 331. Index

The PHP language. Teaching you everything about PHP? Not exactly Goal: teach you how to interact with a database via web

Pace University. Fundamental Concepts of CS121 1

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Objectives. In this chapter, you will:

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Language Reference Manual simplicity

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010

Model Viva Questions for Programming in C lab

CMPT 125: Lecture 3 Data and Expressions

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Absolute C++ Walter Savitch

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

COMP284 Scripting Languages Lecture 9: PHP (Part 1) Handouts

Python Class-Lesson1 Instructor: Yao

CSE 452: Programming Languages. Outline of Today s Lecture. Expressions. Expressions and Control Flow

CS111: PROGRAMMING LANGUAGE II

Introduction. Primitive Data Types: Integer. Primitive Data Types. ICOM 4036 Programming Languages

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

The PCAT Programming Language Reference Manual

Programming Language Basics

egrapher Language Reference Manual

And Parallelism. Parallelism in Prolog. OR Parallelism

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Programming for Engineers Introduction to C

COMP284 Scripting Languages Lecture 10: PHP (Part 2) Handouts

RTL Reference 1. JVM. 2. Lexical Conventions

Chapter 6. Data Types

Let's Look Back. We talked about how to create a form in HTML. Forms are one way to interact with users

CSCB20 Week 8. Introduction to Database and Web Application Programming. Anna Bretscher* Winter 2017

JavaScript CS 4640 Programming Languages for Web Applications

PHP 7.1 and SQL 5.7. Section Subject Page

UNIT- 3 Introduction to C++

Language Fundamentals Summary

JavaScript CS 4640 Programming Languages for Web Applications

Introduction to Computer Science and Business

Introduction to Databases. Key Concepts. Calling a PHP Script 5/17/2012 PHP I

ECE 2400 Computer Systems Programming Fall 2018 Topic 1: Introduction to C

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Such JavaScript Very Wow

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Transcription:

9.1 Origins and Uses of PHP - Origins - Rasmus Lerdorf - 1994 - Developed to allow him to track visitors to his Web site - PHP was originally an acronym for Personal Home Page, but later it became PHP: Hypertext Preprocessor - PHP is used for form handling, file processing, and database access 9.2 Overview of PHP - PHP is a server-side scripting language whose scripts are embedded in HTML documents - PHP is an alternative to ASP.NET and JSP - The PHP processor has two modes: copy (HTML) and interpret (PHP) Chapter 9 2014 by Pearson Education 1

9.2 Overview of PHP (continued) - PHP syntax is similar to that of JavaScript - PHP is dynamically typed - PHP is purely interpreted 9.3 General Syntactic Characteristics - PHP code can be specified in an HTML document internally or externally: Internally: <?php...?> Externally: include ("myscript.inc") - the file can have both PHP and HTML - If the file has PHP, the PHP must be in <?php..?>, even if the include is already in <?php..?> - Every variable name begin with a $ Chapter 9 2014 by Pearson Education 2

9.3 General Syntactic Characteristics (continued) - Comments - three different kinds (Java and C) //... #... /*... */ - Compound statements are formed with braces - Compound statements cannot be blocks 9.4 Primitives, Operations, and Expressions - Variables - There are no type declarations - An unassigned (unbound) variable has the value, NULL - The unset function sets a variable to NULL - The IsSet function is used to determine whether a variable is NULL Chapter 9 2014 by Pearson Education 3

9.4 Primitives, Operations, and Expressions (continued) - error_reporting(15); - prevents PHP from using unbound variables - PHP has many predefined variables, including the environment variables of the host operating system - You can get a list of the predefined variables by calling phpinfo() in a script - There are eight primitive types: - Four scalar types: Boolean, integer, double, and string - Two compound types: array and object - Two special types: resource and NULL - Integer & double are like those of other languages - Strings - Characters are single bytes - String literals use single or double quotes Chapter 9 2014 by Pearson Education 4

9.4 Primitives, Operations, and Expressions (continued) - Single-quoted string literals - Embedded variables are NOT interpolated - Embedded escape sequences are NOT recognized - Double-quoted string literals - Embedded variables ARE interpolated - If there is a variable name in a doublequoted string but you don t want it interpolated, it must be backslashed - Embedded escape sequences ARE recognized - For both single- and double-quoted literal strings, embedded delimiters must be backslashed - Boolean - values are true and false (case insensitive) - 0 and "" and "0" are false; others are true Chapter 9 2014 by Pearson Education 5

9.4 Primitives, Operations, and Expressions (continued) - Arithmetic Operators and Expressions - Usual operators - If the result of integer division is not an integer, a double is returned - Any integer operation that results in overflow produces a double - The modulus operator (%) coerces its operands to integer, if necessary - When a double is rounded to an integer, the rounding is always towards zero - Arithmetic functions - floor, ceil, round, abs, min, max, rand, etc. - String Operations and Functions - The only operator is period, for catenation - Indexing - $str{3} is the fourth character Chapter 9 2014 by Pearson Education 6

9.4 Primitives, Operations, and Expressions (continued) - String Operations and Functions (continued) strlen, strcmp, strpos, substr, as in C chop remove whitespace from the right end trim remove whitespace from both ends ltrim remove whitespace from the left end strtolower, strtoupper - Scalar Type Conversions - Implicit (coercions) - String to numeric - If the string contains an e or an E, it is converted to double; otherwise to integer - If the string does not begin with a sign or a digit, zero is used Chapter 9 2014 by Pearson Education 7

9.4 Primitives, Operations, and Expressions (continued) - Scalar Type Conversions (continued) - Explicit conversions casts - e.g., (int)$total or intval($total) or settype($total, "integer") - The type of a variable can be determined with gettype or is_type gettype($total) - it may return "unknown" is_integer($total) a predicate function 9.5 Output - Output from a PHP script is HTML that is sent to the browser - HTML is sent to the browser through standard output Chapter 9 2014 by Pearson Education 8

9.5 Output (continued) - There are two ways to produce output: print and printf - print takes a string, but will coerce other values to strings print "This is too <br /> much fun <br />"; print 72; - printf is exactly as in C printf(literal_string, param1, param2, ) - PHP code is placed in the body of an HTML document <html> <head><title> Trivial php example </title> </head> <body> <?php print "Welcome to my Web site!";?> </body> </html> SHOW today.php and display Chapter 9 2014 by Pearson Education 9

9.6 Control Statements - Control Expressions - Relational operators - same as JavaScript, (including === and!==) - Boolean operators - same as C (two sets, && and and, etc.) - Selection statements - if, if-else, elseif - switch - as in C - The switch expression type must be integer, double, or string - while - just like C - do-while - just like C - for - just like C - foreach - discussed later Chapter 9 2014 by Pearson Education 10

9.6 Control Statements (continued) - break - in any for, foreach, while, do-while, or switch - continue - in any loop - Alternative compound delimiters more readability if(...):... endif; SHOW powers.php - HTML can be intermingled with PHP script <?php $a = 7; $b = 7; if ($a == $b) { $a = 3 * $a;?> <br /> At this point, $a and $b are equal <br /> So, we change $a to three times $a <?php }?> Chapter 9 2014 by Pearson Education 11

9.7 Arrays - Not like the arrays of any other programming language - A PHP array is a generalization of the arrays of other languages - A PHP array is really a mapping of keys to values, where the keys can be numbers (to get a traditional array) or strings (to get a hash) - Array creation - Use the array() construct, which takes one or more key => value pairs as parameters and returns an array of them - The keys are non-negative integer literals or string literals - The values can be anything e.g., $list = array(0 => "apples", 1 => "oranges", 2 => "grapes") - This is a regular array of strings Chapter 9 2014 by Pearson Education 12

9.7 Arrays (continued) - If a key is omitted and there have been integer keys, the default key will be the largest current key + 1 - If a key is omitted and there have been no integer keys, 0 is the default key - If a key appears that has already appeared, the new value will overwrite the old one - Arrays can have mixed kinds of elements - e.g., $list = array("make" => "Cessna", "model" => "C210", "year" => 1960, 3 => "sold"); $list = array(1, 3, 5, 7, 9); $list = array(5, 3 => 7, 5 => 10, "month" => "May"); $colors = array('red', 'blue', 'green', 'yellow'); Chapter 9 2014 by Pearson Education 13

9.7 Arrays (continued) - Accessing array elements use brackets $list[4] = 7; $list["day"] = "Tuesday"; $list[] = 17; - If an element with the specified key does not exist, it is created - If the array does not exist, the array is created - The keys or values can be extracted from an array $highs = array("mon" => 74, "Tue" => 70, "Wed" => 67, "Thu" => 62, "Fri" => 65); $days = array_keys($highs); $temps = array_values($highs); - Testing whether an element exists if (array_key_exists("wed", $highs)) - An array can be deleted with unset unset($list); unset($list[4]); # Deletes index 4 element Chapter 9 2014 by Pearson Education 14

9.7 Arrays (continued) - is_array($list) returns true if $list is an array - in_array(17, $list) returns true if 17 is an element of $list - sizeof(an_array) returns the number of elements - explode(" ", $str) creates an array with the values of the words from $str, split on a space - implode(" ", $list) creates a string of the elements from $list, separated by a space SHOW Figure 9.3 - Sequential access to array elements - current and next $colors = array("blue", "red", "green", "yellow"); $color = current($colors); print("$color <br />"); while ($color = next($colors)) print ("$color <br />"); Chapter 9 2014 by Pearson Education 15

9.7 Arrays (continued) - This does not always work for example, if the value in the array happens to be FALSE - Alternative: each, instead of next while ($element = each($colors)) { print ("$element['value'] <br />"); } - The prev function moves current backwards - array_push($list, $element) and array_pop($list) - Used to implement stacks in arrays - foreach (array_name as scalar_name) {... } foreach ($colors as $color) { print "Is $color your favorite color?<br />"; } Is red your favorite color? Is blue your favorite color? Is green your favorite color? Is yellow your favorite color? Chapter 9 2014 by Pearson Education 16

9.7 Arrays (continued) - foreach can iterate through both keys and values: foreach ($colors as $key => $color) { } - Inside the compound statement, both $key and $color are defined $ages = array("bob" => 42, "Mary" => 43); foreach ($ages as $name => $age) print("$name is $age years old <br />"); Chapter 9 2014 by Pearson Education 17

9.7 Arrays (continued) - sort - To sort the values of an array, leaving the keys in their present order - intended for traditional arrays e.g., sort($list); - The sort function does not return anything - Works for both strings and numbers, even mixed strings and numbers $list = ('h', 100, 'c', 20, 'a'); sort($list); // Produces ('a', 'c', 'h, 20, 100) - In PHP 4, the sort function can take a second parameter, which specifies a particular kind of sort - asort sort($list, SORT_NUMERIC); - To sort the values of an array, but keeping the key/value relationships - intended for hashes Chapter 9 2014 by Pearson Education 18

9.7 Arrays (continued) - rsort - To sort the values of an array into reverse order - ksort - To sort the elements of an array by the keys, maintaining the key/value relationships e.g., $list("fred" => 17, "Mary" => 21, "Bob" => 49, "Jill" => 28); ksort($list); // $list is now ("Bob" => 49, // "Fred" => 17, "Jill" => 28, "Mary" => 21) - krsort - To sort the elements of an array by the keys into reverse order SHOW sorting.php Chapter 9 2014 by Pearson Education 19

9.8 User-Defined Functions - Syntactic form: function function_name(formal_parameters) { } - General Characteristics - Functions need not be defined before they are called - If you try to redefine a function, it is an error - Functions can have a variable number of parameters - Default parameter values are supported - Function definitions can be nested - Function names are NOT case sensitive - The return function is used to return a value; If there is no return, there is no returned value Chapter 9 2014 by Pearson Education 20

9.8 User-Defined Functions (continued) - Parameters - If the caller sends too many actual parameters, the subprogram ignores the extra ones - If the caller does not send enough parameters, the unmatched formal parameters are unbound - The default parameter passing method is pass by value (one-way communication) - To specify pass-by-reference, prepend an ampersand to the formal parameter function set_max(&$max, $first, $second) { if ($first >= $second) $max = $first; else $max = $second; } - If the function does not specify its parameter to be pass by reference, you can prepend an ampersand to the actual parameter and still get pass-byreference semantics Chapter 9 2014 by Pearson Education 21

9.8 User-Defined Functions (continued) - Return Values - Any type may be returned, including objects and arrays, using the return - If a function returns a reference, the name of the function must have a prepended ampersand function &newarray($x) { } - The Scope of Variables - An undeclared variable in a function has the scope of the function - To access a nonlocal variable, it must be declared to be global, as in global $sum; - The Lifetime of Variables - Normally, the lifetime of a variable in a function is from its first appearance to the end of the function s execution static $sum = 0; # $sum is static Chapter 9 2014 by Pearson Education 22

9.9 Pattern Matching - PHP has two kinds: POSIX and Perl-compatible preg_match(regex, str) - Returns a Boolean value preg_split(regex, str) - Returns an array of the substrings SHOW word_table.php 9.10 Form Handling - Forms could be handled by the same document that creates the form, but that may be confusing - PHP particulars: - It does not matter whether GET or POST method is used to transmit the form data - PHP builds an array of the form values ($_GET for the GET method and $_POST for the POST method subscripts are the widget names) SHOW popcorn3.html & popcorn3.php Chapter 9 2014 by Pearson Education 23

9.11 Cookies - Recall that the HTTP protocol is stateless; however, there are several reasons why it is useful for a server to relate a request to earlier requests - Targeted advertising - Shopping baskets - A cookie is a name/value pair that is passed between a browser and a server in the HTTP header - In PHP, cookies are created with setcookie setcookie(cookie_name, cookie_value, lifetime) e.g., setcookie("voted", "true", time() + 86400); - Cookies are implicitly deleted when their lifetimes are over - Cookies must be created before any other HTML is created by the script - Cookies are obtained in a script the same way form values are gotten, using the $_COOKIES array Chapter 9 2014 by Pearson Education 24

9.13 Session Tracking - A session is the time span during which a browser interacts with a particular server - For session tracking, PHP creates and maintains a session tracking id - Create the id with a call to session_start with no parameters - Subsequent calls to session_start retrieves any session variables that were previously registered in the session - To create a session variable, use session_register - The only parameter is a string literal of the name of the session variable (without the dollar sign) - Example: count number of pages visited - Put the following code in all documents session_start(); if (!IsSet($page_number)) $page_number = 1; print("you have now visited $page_number"); print(" pages <br />"); $page_number++; $session_register("page_number"); Chapter 9 2014 by Pearson Education 25