CSE 154 Lecture 15: MORE PHP.

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

Java Script Session1 INTRODUCTION.
Ruby (on Rails) CSE 190M, Spring 2009 Week 3. Web Programming in Ruby Ruby can be used to write dynamic web pages Similar to PHP, chunks of Ruby begins.
Arrays Strings and regular expressions Basic PHP Syntax CS380 1.
1 CSC 551: Web Programming Spring 2004 client-side programming with JavaScript  scripts vs. programs  JavaScript vs. JScript vs. VBScript  common tasks.
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.
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.
CSE 154 LECTURE 9: FORMS. Web data most interesting web pages revolve around data examples: Google, IMDB, Digg, Facebook, YouTube, Rotten Tomatoes can.
August Chapter 1 - Essential PHP spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology.
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 9 JavaServer Pages (JSP) (Based on Møller.
More on PHP: Arrays, Functions and 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.
INTERNET APPLICATION DEVELOPMENT For More visit:
Lecture 6 – Form processing (Part 1) SFDV3011 – Advanced Web Development 1.
CSE 154 LECTURE 6: EMBEDDED PHP. PHP syntax template HTML content HTML content HTML content... PHP any contents of.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
® IBM Software Group © 2007 IBM Corporation JSP Expression Language
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
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.
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
Server-Side Scripting with PHP ISYS 475. PHP Manual Website
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
AJAX. Ajax  $.get  $.post  $.getJSON  $.ajax  json and xml  Looping over data results, success and error callbacks.
JavaScript. JavaScript Introduction JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers,
NMD202 Web Scripting Week2. Web site
Arrays Strings and regular expressions Basic PHP Syntax CS380 1.
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,
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.
Web Services Essentials. What is a web service? web service: software functionality that can be invoked through the internet using common protocols like.
CSE 154 LECTURE 18: FORMS AND UPLOADING FILES. Exercise: Baby name web service JSON Modify our babynames.php service to produce its output as JSON. For.
CSE 154 LECTURE 15: EMBEDDED PHP. PHP syntax template HTML content HTML content HTML content... PHP any contents of.
PHP. What is PHP? PHP Hypertext Processor – Dynamic web development – Scripting language – Can be procedural or OOP(preferred) – PHP code can be embedded.
CSE 154 LECTURE 16: FILE I/O; FUNCTIONS. Query strings and parameters URL?name=value&name=value...
Introduction to JavaScript MIS 3502, Fall 2016 Jeremy Shafer Department of MIS Fox School of Business Temple University 9/29/2016.
PHP using MySQL Database for Web Development (part II)
Lecture 16: File I/O; Functions
Session 2 Basics of PHP.
PHP (Session 1) INFO 257 Supplement.
PHP for Server-Side Programming
Introduction to Dynamic Web Programming
Tutorial 10 Programming with JavaScript
CS 371 Web Application Programming
DBW - PHP DBW2017.
PHP Functions Besides the built-in PHP functions, we can create our own functions. A function is a block of statements that can be used repeatedly in.
19.10 Using Cookies A cookie is a piece of information that’s stored by a server in a text file on a client’s computer to maintain information about.
Chapter 19 PHP Part III Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
* Lecture # 7 Instructor: Rida Noor Department of Computer Science
4. Javascript Pemrograman Web I Program Studi Teknik Informatika
CSE 154 Lecture 24: JSON.
PHP Introduction.
Intro to PHP & Variables
JavaScript an introduction.
Web Systems Development (CSC-215)
PHP.
HYPERTEXT PREPROCESSOR BY : UMA KAKKAR
Lecture 5: Functions and Parameters
Intro to PHP.
JavaScript CS 4640 Programming Languages for Web Applications
Lecture 14: JSON and Web SERVICES
PHP an introduction.
Lecture 03 & 04 Method and Arrays Jaeki Song.
PHP-II.
SEEM 4540 Tutorial 4 Basic PHP based on w3Schools
JavaScript CS 4640 Programming Languages for Web Applications
Presentation transcript:

CSE 154 Lecture 15: MORE PHP

Arrays to append, use bracket notation without specifying an index $name = array(); # create $name = array(value0, value1, ..., valueN); $name[index] # get element value $name[index] = value; # set element value $name[] = value; # append PHP $a = array(); # empty array (length 0) $a[0] = 23; # stores 23 at index 0 (length 1) $a2 = array("some", "strings", "in", "an", "array"); $a2[] = "Ooh!"; # add string to end (at index 5) PHP to append, use bracket notation without specifying an index element type is not specified; can mix types

Array functions function name(s) description count number of elements in the array print_r print array's contents array_pop, array_push,  array_shift, array_unshift using array as a stack/queue in_array, array_search, array_reverse,  sort, rsort, shuffle searching and reordering array_fill, array_merge, array_intersect,  array_diff, array_slice, range creating, filling, filtering array_sum, array_product, array_unique,  array_filter, array_reduce processing elements

Array function example $tas = array("MD", "BH", "KK", "HM", "JP"); for ($i = 0; $i < count($tas); $i++) { $tas[$i] = strtolower($tas[$i]); } # ("md", "bh", "kk", "hm", "jp") $morgan = array_shift($tas); # ("bh", "kk", "hm", "jp") array_pop($tas); # ("bh", "kk", "hm") array_push($tas, "ms"); # ("bh", "kk", "hm", "ms") array_reverse($tas); # ("ms", "hm", "kk", "bh") sort($tas); # ("bh", "hm", "kk", "ms") $best = array_slice($tas, 1, 2); # ("hm", "kk") the array in PHP replaces many other collections in Java list, stack, queue, set, map, ...

The foreach loop foreach ($array as $variableName) { ... } PHP $stooges = array("Larry", "Moe", "Curly", "Shemp"); for ($i = 0; $i < count($stooges); $i++) { print "Moe slaps {$stooges[$i]}\n"; } foreach ($stooges as $stooge) { print "Moe slaps $stooge\n"; # even himself! a convenient way to loop over each element of an array without indexes

Math operations $a = 3; $b = 4; $c = sqrt(pow($a, 2) + pow($b, 2)); PHP abs ceil cos floor log log10 max min pow rand round sin sqrt tan math functions M_PI M_E M_LN2 math constants the syntax for method calls, parameters, returns is the same as Java

NULL a variable is NULL if $name = "Victoria"; $name = NULL; if (isset($name)) { print "This line isn't going to be reached.\n"; } a variable is NULL if it has not been set to any value (undefined variables) it has been assigned the constant NULL it has been deleted using the unset function can test if a variable is NULL using the isset function NULL prints as an empty string (no output)

Functions parameter types and return types are not written function name(parameterName, ..., parameterName) { statements; } PHP function bmi($weight, $height) { $result = 703 * $weight / $height / $height; return $result; } PHP parameter types and return types are not written a function with no return statements is implicitly "void" can be declared in any PHP block, at start/end/middle of code

Calling functions name(expression, ..., expression); PHP $w = 163; # pounds $h = 70; # inches $my_bmi = bmi($w, $h); PHP if the wrong number of parameters are passed, it's an error

Variable scope: global and local vars $school = "UW"; # global ... function downgrade() { global $school; $suffix = "(Wisconsin)"; # local $school = "$school $suffix"; print "$school\n"; } PHP variables declared in a function are local to that function; others are global if a function wants to use a global variable, it must have a global statement but don't abuse this; mostly you should use parameters

Default parameter values function name(parameterName = value, ..., parameterName = value) { statements; } PHP function print_separated($str, $separator = ", ") { if (strlen($str) > 0) { print $str[0]; for ($i = 1; $i < strlen($str); $i++) { print $separator . $str[$i]; } } PHP print_separated("hello"); # h, e, l, l, o print_separated("hello", "-"); # h-e-l-l-o PHP if no value is passed, the default will be used (defaults must come last)

Web Services web service: software functionality that can be invoked through the internet using common protocols like a remote function(s) you can call by contacting a program on a web server many web services accept parameters and produce results can be written in PHP and contacted by the browser in HTML and/or Ajax code service's output might be HTML but could be text, XML, JSON or other content

Setting content type with header header("Content-type: type/subtype"); PHP header("Content-type: text/plain"); print "This output will appear as plain text now!\n"; PHP by default, a PHP file's output is assumed to be HTML (text/html) However, in our class we aren’t using PHP to generate HTML So, we use the header function to specify non-HTML output must appear before any other output generated by the script (doesn’t have to be the first line of code, though)

Recall: Content ("MIME") types related file extension text/plain .txt text/html .html, .htm, ... text/xml .xml application/json .json text/css .css text/javascript .js image/gif .gif Lists of MIME types: by type, by extension

Query strings and parameters URL?name=value&name=value... http://www.google.com/search?q=Romney http://example.com/student_login.php?username=obourn&id=1234567 query string: a set of parameters passed from a browser to a web server often passed by placing name/value pairs at the end of a URL above, parameter username has value obourn, and sid has value 1234567 PHP code on the server can examine and utilize the value of parameters a way for PHP code to produce different output based on values passed by the user

Query parameters: $_GET, $_POST $user_name = $_GET["username"]; $id_number = (int) $_GET["id"]; $eats_meat = FALSE; if (isset($_GET["meat"])) { $eats_meat = TRUE; } PHP $_GET["parameter name"] or $_POST["parameter name"] returns a GET/POST parameter's value as a string parameters specified as http://....?name=value&name=value are GET parameters test whether a given parameter was passed with isset

Query parameters: $_POST $username = $_POST["username"]; $password = $_POST["password"]; $users_pw_hash = db_lookup_hashed_pw($username); if (password_hash($password) == $users_pw_hash) { print(“Successfully logged in!”); } POST parameters come in through the body of the request, not through the URL. However, on the server, we get access to them the same way we use the GET params, but with a different array: $_POST This means that client side POST requests look different than GET requests, but server-side POST-request handling looks similar to GET-request handling

Example: Exponent web service Write a web service that accepts a base and exponent and outputs base raised to the exponent power. For example, the following query should output 81 : http://example.com/exponent.php?base=3&exponent=4 solution: <?php header("Content-type: text/plain"); $base = (int) $_GET["base"]; $exp = (int) $_GET["exponent"]; $result = pow($base, $exp); print $result; ?> PHP

Embedded PHP Embedded PHP is a strategy for generating HTML pages on the server side using PHP. The textbook assumes that we’re using PHP in this way, but we don’t. This quarter, we are focusing on using PHP for data generation. The next couple slides are about embedded PHP if you are interested in learning a little bit more about it

Embedded PHP syntax template HTML content <?php PHP code ?> HTML content ... PHP any contents of a .php file between <?php and ?> are executed as PHP code all other contents are output as pure HTML

Printing HTML tags in PHP = bad style print "<!DOCTYPE html>\n"; print "<html>\n"; print " <head>\n"; print " <title>Geneva's web page</title>\n"; ... for ($i = 1; $i <= 10; $i++) { print "<p class=\"count\"> I can count to $i! </p>\n"; } ?> PHP printing HTML tags with print statements is bad style and error-prone: must quote the HTML and escape special characters, e.g. \" but without print, how do we insert dynamic content into the page?

PHP expression blocks The answer is 42 output <?= expression ?> PHP <h2> The answer is <?= 6 * 7 ?> </h2> PHP The answer is 42 output PHP expression block: evaluates and embeds an expression's value into HTML <?= expr ?> is equivalent to <?php print expr; ?>

Expression block example <!DOCTYPE html> <html> <head><title>CSE 154: Embedded PHP</title></head> <body> <?php for ($i = 99; $i >= 1; $i--) { ?> <p> <?= $i ?> bottles of beer on the wall, <br /> <?= $i ?> bottles of beer. <br /> Take one down, pass it around, <br /> <?= $i - 1 ?> bottles of beer on the wall. </p> <?php } ?> </body> </html> PHP

Complex expression blocks <body> <?php for ($i = 1; $i <= 3; $i++) { ?> <h<?= $i ?>>This is a level <?= $i ?> heading.</h<?= $i ?>> <?php } ?> </body> PHP This is a level 1 heading. This is a level 2 heading. This is a level 3 heading. output expression blocks can even go inside HTML tags and attributes

Common errors: unclosed braces, missing = sign <body> <p>Watch how high I can count: <?php for ($i = 1; $i <= 10; $i++) { ?> <? $i ?> </p> </body> </html> PHP </body> and </html> above are inside the for loop, which is never closed if you forget to close your braces, you'll see an error about 'unexpected $end‘ if you forget = in <?=, the expression does not produce any output