1 Ivan Marsic Rutgers University LECTURE: PHP Scripting Language.

Slides:



Advertisements
Similar presentations
PHP I.
Advertisements

Lecture 2 Introduction to C Programming
Chapter 12 Introduction to PHP. © 2006 Pearson Addison-Wesley. All rights reserved Origins and Uses of PHP - Origins - Rasmus Lerdorf
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
PHP Server-side Programming. PHP  PHP stands for PHP: Hypertext Preprocessor  Originally Personal Home Page  PHP is interpreted  PHP code is embedded.
Guide To UNIX Using Linux Third Edition
PHP Server-side Programming. PHP  PHP stands for PHP: Hypertext Preprocessor  PHP is interpreted  PHP code is embedded into HTML code  interpreter.
Server side basics.
Server side basics CS URLs and web servers  Usually when you type a URL in your browser:  Your computer looks up the server's IP address using.
 2004 Prentice Hall, Inc. All rights reserved. Chapter 25 – Perl and CGI (Common Gateway Interface) Outline 25.1 Introduction 25.2 Perl 25.3 String Processing.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11 Introduction to PHP.
PHP: Hypertext Processor Fred Durao
PHP1-1 PHP Xingquan (Hill) Zhu
August Chapter 1 - Essential PHP spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology.
Chapter 11 Introduction to PHP. It is a Web development language written by and for Web developers PHP stands for PHP: Hypertext Preprocessor Originally.
Chapter 9 Using Perl for CGI Programming. Computation is required to support sophisticated web applications Computation can be done by the server or the.
PHP Overview CS PHP PHP = PHP: Hypertext Preprocessor Server-side scripting language that may be embedded into HTML One goal is to get PHP files.
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.
Chapter 9 © 2010 by Addison Wesley Longman, Inc Origins and Uses of PHP - Origins - Rasmus Lerdorf Developed to allow him to track visitors.
Copyright © Curt Hill PhP History and Introduction.
Chapter 4 – The Building Blocks Data Types Literals Variables Constants.
Lecture 12 PHP Basics Boriana Koleva Room: C54
MySQL in PHP – Page 1 of 17CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: MySQL in PHP Reading: Williams &
School of Computing and Information Systems CS 371 Web Application Programming PHP - Basics Serving up web pages.
Week 9 PHP Cookies and Session Introduction to JavaScript.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
IST 210: PHP BASICS IST 210: Organization of Data IST210 1.
USING PERL FOR CGI PROGRAMMING
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction.
Creating Dynamic Web Pages Using PHP and MySQL CS 320.
Introduction to PHP A user navigates in her browser to a page that ends with a.php extension The request is sent to a web server, which directs the request.
Web-Based Database Programming with PHP. Dept. of Computing Science, University of Aberdeen2 In this lecture you will learn PHP Basics PHP functions –To.
Web Database Programming Week 3 PHP (2). Functions Group related statements together to serve “a” specific purpose –Avoid duplicated code –Easy maintenance.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
CS320 Web and Internet Programming Introduction to PHP Chengyu Sun California State University, Los Angeles.
Just a Little PHP Programming PHP on the Server. Common Programming Language Features Comments Data Types Variable Declarations Expressions Flow of Control.
1Computer Sciences Department Princess Nourah bint Abdulrahman University.
Chapter 12 © 2003 by Addison Wesley Longman, Inc Origins and Uses of PHP - Origins - Rasmus Lerdorf Developed to allow him to track visitors.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP & MySQL.
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.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
CSE 154 LECTURE 5: INTRO TO PHP. URLs and web servers usually when you type a URL in your browser: your computer looks up the.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Chapter 9 © 2012 by Addison Wesley Longman, Inc Origins and Uses of PHP - Origins - Rasmus Lerdorf Developed to allow him to track visitors.
Just a Little PHP Programming PHP on the Server. Common Programming Language Features Comments Data Types Variable Declarations Expressions Flow of Control.
Basic Scripting & Variables Yasar Hussain Malik - NISTE.
1 PHP Intro PHP Introduction After this lecture, you should be able to: Know the fundamental concepts of Web Scripting Languages in general, PHP in particular.
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,
CSE 154 LECTURE 14: INTRO TO PHP. URLs and web servers usually when you type a URL in your browser: your computer looks up the.
11 – Introduction to PHP(1) Informatics Department Parahyangan Catholic University.
CGS 3066: Web Programming and Design Spring 2016 PHP.
IST 210: PHP Basics IST 210: Organization of Data IST2101.
PHP. What is PHP? PHP Hypertext Processor – Dynamic web development – Scripting language – Can be procedural or OOP(preferred) – PHP code can be embedded.
CHAPTER 9 INTRODUCTION TO PHP 1. ORIGINS AND USES OF PHP Origins –Rasmus Lerdorf – 1994 –Developed to allow him to track visitors to his Web site PHP.
PHP using MySQL Database for Web Development (part II)
12.1 Origins and Uses of PHP 12.2 Overview of PHP - Origins
CHAPTER 9 INTRODUCTION TO PHP
Session 2 Basics of PHP.
CS 371 Web Application Programming
9.1 Origins and Uses of PHP 9.2 Overview of PHP - Origins
PHP.
HYPERTEXT PREPROCESSOR BY : UMA KAKKAR
Lecture 5: Functions and Parameters
Chapter 12 Introduction to PHP.
9.1 Origins and Uses of PHP 9.2 Overview of PHP - Origins
PHP an introduction.
Presentation transcript:

1 Ivan Marsic Rutgers University LECTURE: PHP Scripting Language

2 Topics  Syntax, Variables, Types  Operators, Expressions, Math Functions  String Operations and Functions  PHP Processor Output  Control Statements  PHP in HTML  Arrays  User-Defined Functions  Pattern Matching  Form Handling  MySQL Database Access from PHP  Cookies and Session Tracking

3 What is PHP?  Originally an acronym for Personal Home Page that later became PHP: Hypertext Preprocessor  PHP is a server-side scripting language whose scripts are embedded in HTML documents –Alternatives: JSP, Ruby on Rails, Python, ASP.NET, etc. –The web server contains software that allows it to run those programs and send back their output (HTML documents) as responses to client requests  Server-side scripting languages are used for –HTML form handling –User authentication –File processing –Database access –Other services, e.g., , …

4 Lifecycle of a PHP Web Request  Browser requests a.html file (static content): server just sends that file  Browser requests a.php file (dynamic content): server reads it, runs any script code inside it, then sends result across the network –PHP script outputs an HTML document that is sent back  PHP file itself is never sent to the client/browser; only its output is Web Browser User’s Computer Server Computer Web Server <?php include('header.p if (isSet($_GET[‘ page = $_GET['p } else { <?php include('header.p if (isSet($_GET[‘ page = $_GET['p } else { <!DOCTYPE html PU <html xmlns="http Hello <!DOCTYPE html PU <html xmlns="http Hello Hello world! GET hello.php PHP Script Execute script HTML Output

5 Operating Modes  The PHP processor has two modes: –copy (HTML), and –interpret (PHP)  PHP syntax is similar to that of JavaScript  PHP is dynamically typed  PHP is purely interpreted

6 General Syntactic Characteristics  PHP code can be specified in an HTML document internally or externally:  Internally:  Externally: include ("myScript.inc") –The included file can have both PHP and HTML code –If the file has PHP, the PHP must appear between these endpoints, even if the include is already within  Comments — three different kinds (as in Java and C) //...single-line comment (like in Perl) #...single-line comment (like in Java or C++) /*... */multi-line comment (like in C or Java)  Compound statements are formed with braces {... }  Compound statements cannot be blocks

7 Variables  Variables –Every variable name begins with a $, on both declaration and usage Names are case sensitive; use an underscore (‘_’) or camelCase to separate multiple words –There are no type declarations The type of a variable is dynamically declared by value assignment (type is not written, but implicit) –If a variable is created without a value (unassigned or “unbound”), it is automatically assigned a value of NULL The unset function sets a variable to NULL The IsSet() function is used to determine whether a variable is NULL  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 in a script by calling phpinfo()

8 Primitive Types  There are eight basic/primitive types: –Four scalar types: boolean, integer (or, int ), float (or, double ), and string –Two compound types: array and object –Two special types: resource and NULL  Integer & float are like those of other languages  Boolean — values are true and false (case insensitive) –0 and "" and "0" are false ;others are true  PHP converts between types automatically in many cases: –string → int auto-conversion on + –int → float auto-conversion on /

9 Primitive Types — Strings  Strings: –Characters are single bytes –String literals use single or double quotes –Strings can span multiple lines — the newline is part of the string  Single-quoted string literals: –Embedded variables are NOT interpolated (i.e., expanded) –Embedded “escape” sequences (using backslash) are NOT recognized  Double-quoted string literals: –Embedded variables ARE interpolated –If there is a variable name in a double-quoted string but you do not want it interpolated, it must be preceded by backslash ( \ ) — an “escape” character –Embedded escape sequences ARE recognized  For both single- and double-quoted literal strings, embedded delimiters must be backslashed

10 Arithmetic Operators, Expressions and Math Functions  Arithmetic Operators and Expressions –Usual operators in a programming language + – * / % ++ –– = += –= *= /= %= == != > = <= && || ! –Two more operators: === !== == just checks value: ( "5.0" == 5 is TRUE) === also checks type: ( "5.0" === 5 is FALSE) –If the result of integer division is not an integer, a float is returned –Any integer operation that results in overflow produces a float –The modulus operator ( % ) coerces its operands to integer, if necessary –When a float is rounded to an integer, the rounding is always towards zero  Math Functions  Math constants absceilcosfloorloglog10max minpowrandroundsinsqrttan M_PIM_EM_LN2

11 String Operations and Functions  The only string operator is period (. ), for catenation (or, concatenation) — not +, like in Java! –Example: 5 + "2 things" === 7 5. "2 things" === "52 things"  Zero-based indexing using bracket notation –Example: $str{3} is the fourth character  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()

12 Scalar Type Conversions  Implicit (coercions) –String to numeric –If the string contains an e or an E, it is converted to float ; otherwise to integer –If the string does not begin with a sign or a digit, zero is used  Explicit conversions — casts –e.g., (int)$total or intval($total) or settype($total, "integer")  The type of a variable can be determined with: –gettype() function; returns a variable’s type as a string –is_ type () functions, such as is_string($var)  gettype($total) — it may return "unknown"  is_integer($total) — a predicate function

13 PHP Processor Output  Output from a PHP script is HTML that is sent to the browser  HTML is sent to the browser through standard output  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 much fun "; print 72;  printf is exactly as in C printf(literal_string, param1, param2, …)  PHP code is placed in the body of an HTML document Trivial php example <?php print "Welcome to my Web site!"; ?>   SHOW today.php and display

14 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 a –switch — as in C The switch expression type must be integer, float, or string –while — just like C –do-while — just like C –for — just like C –foreach — described later –break — in any for, foreach, while, do-while, or switch –continue — in any loop  Alternative compound delimiters — more readability if (...):... endif;   SHOW powers.php

15 PHP in HTML  HTML can be mixed with PHP script <?php $a = 7; $b = 7; if ($a == $b) { $a = 3 * $a; ?> At this point, $a and $b are equal So, we change $a to three times $a <?php } ?>

16 PHP Arrays (1)  PHP arrays are a mixture of regular arrays in other programming language and hash-maps (similar to Java hash-maps and Python Dictonaries+Lists) –A PHP array is a generalization of the arrays of other languages — “associative arrays” –A PHP array is really a mapping of keys to values, where the keys can be numbers (to get a regular 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 (indexed by numbers)

17 PHP Arrays (2) –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 is repeated, the new associated 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');

18 Accessing Array Elements  Use brackets to access array elements $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

19 Functions on Arrays  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 "); while ($color = next($colors)) print ("$color ");

20 Sorting Arrays  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 sort($list, SORT_NUMERIC);  asort() –To sort the values of an array, but keeping the key/value relationships — intended for hashes  Also see rsort(), ksort(), and krsort()

21 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 (no overloading!) –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

22 User-Defined Functions: 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-by-reference semantics

23 User-Defined Functions Return Values, Scope & Lifetime of Variables  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

24 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

25 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

26 PHP/MySQL Interface mysql_connect(host, username, password, new_link) –establishes a connection with MySQL server on host –includes authentication information –reuses existing link by default (unless new_link is true ) –all arguments have defaults (coming from php.ini ) mysql_select_db(database, link) –selects database (makes it "active") –similar to MySQL USE command –link is optional, needed for multiple connections mysql_query(query, link) –makes an SQL query, query, on open connection –returns a "handle" for result table –consider mysq_unbuffered_query for large results –use mysql_num_rows() for count of result rows ( SELECT ) –use mysql_affected_rows() for rows affected by operation ( DELETE, INSERT, REPLACE, UPDATE ) mysql_fetch_array(result_handle, result_type) –returns next row of result table ( result_handle ) as an array –possible result_type values: MYSQL_ASSOC, MYSQL_NUM, and MYSQL_BOTH Using MYSQL_ASSOC, you only get associative indices Using MYSQL_NUM, you only get number indices

27 Typical MySQL Session <?php // Connecting, selecting database $link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password') or die('Could not connect: '. mysql_error()); echo 'Connected successfully'; mysql_select_db('my_database') or die('Could not select database'); // Performing SQL query $query = 'SELECT * FROM my_table'; $result = mysql_query($query) or die('Query failed: '. mysql_error()); // Printing results in HTML echo " \n"; while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "\t \n"; foreach ($line as $col_value) { echo "\t\t $col_value \n"; } echo "\t \n"; } echo " \n"; Also see: MySQLi — MySQL Improved Extension // Free resultset mysql_free_result($result); // Closing connection mysql_close($link); ?>

28 Cookies (1)  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() );  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 obtained, using the $_COOKIES array

29 Cookies (2)   Cookies are marked as to the web addresses they come from — the browser only sends back cookies that were originally set by the same web server

30 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, using the array $_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: To 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 "); $page_number++; $session_register("page_number");