PHP. Interactive Web Systems

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

CSC Web Programming. Introduction to JavaScript

PHP 5 Introduction. What You Should Already Know. What is PHP? What is a PHP File? What Can PHP Do? Why PHP?

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

CGS 3066: Spring 2015 JavaScript Reference

Full file at

B. V. Patel Institute of BMC & IT 2014

Lecture 12. PHP. cp476 PHP

Variables and literals

PHP by Pearson Education, Inc. All Rights Reserved.

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

Visual C# Instructor s Manual Table of Contents

Variables, Constants, and Data Types

Lecture 7 PHP Basics. Web Engineering CC 552

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

PHP and MySQL for Dynamic Web Sites. Intro Ed Crowley

Operators. Java operators are classified into three categories:

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

Server side basics CS380

PHP Reference. To access MySQL manually, run the following command on the machine, called Sources, where MySQL and PhP have been installed:

PHPoC Language Reference > Overview. Overview

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

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:

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

PHP Hypertext Preprocessor

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

Chapter 17. Fundamental Concepts Expressed in JavaScript

PHPoC vs PHP > Overview. Overview

SECTION II: LANGUAGE BASICS

CSCI 1061U Programming Workshop 2. C++ Basics

COMP 2718: Shell Scripts: Part 1. By: Dr. Andrew Vardy

Web Scripting using PHP

PHPoC. PHPoC vs PHP. Version 1.1. Sollae Systems Co., Ttd. PHPoC Forum: Homepage:

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

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++

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

COMS 469: Interactive Media II

JavaScript: Introduction, Types

Course Outline. Introduction to java

Java Basic Programming Constructs

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

Important Points about PHP:

Objectives. In this chapter, you will:

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

CS4120/4121/5120/5121 Spring 2016 Xi Language Specification Cornell University Version of May 11, 2016

JME Language Reference Manual

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

Language Reference Manual

Chapter 2. Lexical Elements & Operators

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

Creating HTML files using Notepad

Fundamental of Programming (C)

PHP 1. Introduction Temasek Polytechnic

4 Programming Fundamentals. Introduction to Programming 1 1

Decaf Language Reference Manual

1 Lexical Considerations

JavaScript Functions, Objects and Array

2 rd class Department of Programming. OOP with Java Programming

Web Engineering (Lecture 08) WAMP

VLC : Language Reference Manual

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

Chapter 2: Using Data

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Key Differences Between Python and Java

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

egrapher Language Reference Manual

Crayon (.cry) Language Reference Manual. Naman Agrawal (na2603) Vaidehi Dalmia (vd2302) Ganesh Ravichandran (gr2483) David Smart (ds3361)

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

CS50 Supersection (for those less comfortable)

Java+- Language Reference Manual

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

COMS 469: Interactive Media II

3 The Building Blocks: Data Types, Literals, and Variables

IDM 232. Scripting for Interactive Digital Media II. IDM 232: Scripting for IDM II 1

Programming with C++ as a Second Language

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

JavaScript CS 4640 Programming Languages for Web Applications

Java Bytecode (binary file)

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

Lexical Considerations

BEGINNER PHP Table of Contents

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

Web Scripting using PHP

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

Computer Programming : C++

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

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

JScript Reference. Contents

Decaf Language Reference

JavaScript I Language Basics

Programming for the Web with PHP

ISA 563 : Fundamentals of Systems Programming

Princess Nourah bint Abdulrahman University. Computer Sciences Department

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Your Secrets to Coding Fast

Client-Side Web Technologies. JavaScript Part I

Transcription:

PHP Interactive Web Systems

PHP PHP is an open-source server side scripting language. PHP stands for PHP: Hypertext Preprocessor One of the most popular server side languages Second most popular on GitHub (after Python) Supported by basically all non-iis web servers Very active development community Tons of learning resources

About PHP PHP has a syntax very similar to most other languages, including Java, which you should have some familiarity with: if (true) { print "Something!"; }

Using PHP PHP only works with a PHP Processor (generally on a server) Opening a PHP file in a web browser will not give an expected result Browsers don't "know" php Files must be place in a server directory Anywhere in your Cloud 9 workspace SECS Server: login.secs.oakland.edu Directory: ~/public_html

Using PHP PHP files use the.php extension Files without PHP will not have the code processed, and will be sent to the client All output from PHP is "text" in nature PHP does not have a direct user interface Even images are "text" behind the scenes PHP code must be placed within PHP tags <?php and?> Anything not within PHP tags is treated as a literal Meaning it is output directly

PHP Example PHP File: <!doctype html> <html> <title>my PHP</title> <body> <?php echo date('r');?> </body> </html> HTML Output to Client: <!doctype html> <html> <title>my PHP</title> <body> Tue, 10 Feb 2015 12:23:21 </body> </html>

PHP BASICS

Comments in PHP To comment in php, you add //. Anything from there to the end of the line will be commented out echo Hello World"; //Output To comment out an entire block, start with /* and end with */ /* Everything in here is a "comment" print "even code"; */

Variables Used to store values for future use All variables must start with a $ Followed by a _ or letter, then combination of letters, numbers, and underscores Can only contain A-z, 0-9, and _ $myvar - Good $1var - Bad Case sensitive $myvar is not the same as $myvar

Variables PHP variables are loosely typed Their type is not declared, and may change over time Type is based on what you put into the variable Variables are declared implicitly You do not have to explicitly declare the variable, simply putting something into a variable creates it if it does not exist $username = john'; // string $points = 234; // integer $cost = 45.87; // float $response = true; // boolean

PHP Variable Types int, integer float, double, real string bool, boolean array resource NULL object

echo and print echo and print are used to output content such as strings and numbers (which will output as a string). The are basically identical Both may be used with or without () echo "Something"; echo("something"); print "Something"; print("something");

Arithmetic Order of Operations - Standard Parentheses ** (exponent) *, /, % (modulus), in left-to-right order +, -, in left-to-right order Use parentheses!!

Increment / Decrement Shorthand for increasing or decreasing a variable by one $a++ Post-increment $a-- Post-decrement Return $a then increment $a by one Return $a then decrement $a by one ++$a Pre-increment Increment $a by one, then return $a --$a Pre-decrement Decrement $a by one, then return $a $a = 8; echo $a++; 8 echo $a; 9 echo ++$a; 10 echo $a; 10

Concatenation Used to append strings together PHP uses the dot operator (. ) $new = $string1. $string2;

Assignment = assigns a value into a variable Shorthand assignment $a += $b is the same as $a = $a + $b +=, -=, *=, /=, %=,.=, **=

Comparison Operators Comparison operators apply the appropriate comparison to the items to the left and right, and "return" either true or false <, <= >, >= ==, === - Equality!=,!== - Not equality Not '='!

== vs === Two different equality operators == compares equality in value, but not necessarily type Ignores the distinction between: Integers, floating point numbers, and strings containing the same numeric value will return true Non-zero numbers and boolean TRUE Zero and boolean FALSE An Empty string or the string "0" and the boolean FALSE Any other non-empty string and boolean TRUE === compares equality in both value and type

Logical Operators $a && $b Logical And - True if $a and $b are True $a and $b Logical And $a $b Logical Or - True if either $a or $b are True $a or $b Logical Or $a xor $b Logical Xor - True if either $a or $b are True, but not both!$a Logical Not - True is $a is not True The difference between && and and (as well as and or) is that and and or have lower precedence than && and

Logical Operators - Short-circuiting All PHP logical operators skip evaluations if they can" false && never_runs() Never evaluates because && can now never return anything but false true never_runs() Never evaluates because can now never return anything but true

Operator ** Right ++ -- Right! Right * / % Left + -. Left Associativity < <= > >= Non- Associative && Left Left = += -= *= **= / =.= %= and xor or Right Left Left Left ==!= ===!== <> Non- Associative Order of Operations

Order of Operations - Associativity When there are multiple operators of the same precedence, they are grouped based on their associativity: Left: $a + $b + $c is executed as ($a + $b) + $c Right: $a = $b = $c is executed as $a = ($b = $c) Non-Associative This means they cannot be used next to each other 0 < $a < 10 is not allowed in PHP

gettype() gettype() takes a variable and returns the name of the type $foo = "bar"; print gettype($foo); // Prints "string"

settype() settype() allows you to change the type of a variable: $foo = "3.14"; settype($foo, "int"); // $foo is now the integer 3

Converting Variable Types Casting $var = "3"; // String; $var2 = (int)$var; // Integer

STRINGS

Single and Double Quotes Single quotes - $str = 'My String'; Taken (almost) completely literally Does not replace variables or most escape sequences Double quotes - $str = "My String"; Processes string, looking for variable names Replaces standard escape sequences

Single and Double Quotes When a string is started by one type, only the same type can end it echo 'This is a string"; Parse error: syntax error, unexpected ''This is a string";' (T_ENCAPSED_AND_WHITESPACE) in /Users/merrill/test.php on line 3 echo 'This is a "quote"'; This is a "quote"

Escape Sequences Start with a \ - The next characters shows what to do: \n Replace with the newline character \r Replace with the return character \t Replace with a tab \\ Replace with a backslash \' Replace with a, not breaking the string \" Replace with a ", not breaking the string Single quote strings only replace \\ and \'

Escape Sequences print "This is\na new line"; This is a new line print 'This is\na new line'; This is\na new line

Escape Sequences echo "This is a "quote" of someone"; Parse error: syntax error, unexpected 'quote' (T_STRING), expecting ',' or ';' in /Users/merrill/test.php on line 3 echo "This is a \"quote\" of someone"; This is a "quote" of someone

Variable Replacement Searches double quote string for known variable and replaces them $type = "Dog"; print "This is a $type"; This is a Dog

Variable Replacement Use curly braces {} to make it less ambiguous $type = "Dog"; print "There are many $types"; Notice: Undefined variable: types in /Users/merrill/test.php on line 5 There are many $type = "Dog"; print "There are many {$type}s"; There are many Dogs

Aside - PHP Function Names Built in PHP functions do not follow a consistent naming scheme as you will see Frequently have to look up function name Good hinting text editor is very handy

Various String Functions strlen() Returns the number of characters in a string. str_word_count() Returns the number of words in a string. strrev() Returns a reversed version of the string

Various String Functions strpos() Returns the zero indexed position of the search item strpos("this is my string", "my"); //Returns 8 str_replace() Replace all instances of search with replacement in a string str_replace("re", "Dis", "Replace"); // Returns "Displace"

CONTROL STRUCTURES

if if (condition) { // Do something } else if (condition2) { // Do something } else { // Do something }

Ternary Operator PHP has a special conditional operator called the Ternary Operator: (condition)? (result 1) : (result 2) If the condition is true, then the operator evaluates to result 1 if the condition is false. then the operator evaluates to result 2 Very hard to read. I recommend against using it in general.

Ternary Operator $a = 6; echo $a > 5? "$a is >5" : "$a is <=5"; 6 is >5 A special note - the ternary operator is an expression which evaluates to a value, not a variable, this means: The results must be representable as a number or string If you assign the result of the expression into a variable, that variable will hold a copy of the value, not a reference to the selected variable

switch switch ($var) { case 1: // Do something break; case "b": // Do something break; default: // Do something }

Loops while: while (expression) { // Do something } for: for ($i = 0; $i < 10; $i++) { // Do something } do...while do { // Do something } while (expression);

ARRAYS

Aside - print_r() Used to output a variable in a human readable format, regardless of content. Mainly used for debugging $arr = array(); $arr[] = "0"; $arr[] = 0; $arr[] = false; $arr[] = null; print_r($arr); Array ( [0] => 0 [1] => 0 [2] => [3] => )

Aside - var_dump() Very similar to print_r(), but also includes information about the type and size of information within each variable $arr = array(); $arr[] = "0"; $arr[] = 0; $arr[] = false; $arr[] = null; var_dump($arr); array(4) { [0]=> string(1) "0" [1]=> int(0) [2]=> bool(false) [3]=> NULL }

Arrays Used to store many values Unlike Java, their size is not fixed, you can add and remove elements at any time Elements may be addressed by an integer or by string When a key is a number, it is an index When a key is a string, it is a name An array may have both index keys and name keys An array with key names is generally known as an Associative Array

Arrays - Creation All are valid: $arr1 = array(); $arr2 = array("val1", "val2", "val3"); $arr3 = array("key1" => "val1", $arr4[] = "val1"; "key2" => "val2"); $arr5 = ["val1", "val2", "val3"]; $arr6 = ["key1" => "val1", "key2" => "val2"];

Arrays - Appending Just assigning to $array[] will add the value to the end of the array, giving it a index one larger than the largest previously used number: $arr = array(); $arr[] = "val1"; $arr[5] = "val2"; $arr[] = "val3"; print_r($arr); Array ( [0] => val1 [5] => val2 [6] => val3 )

Arrays - Associative Use a string key instead of a index number: $arr = array(); $arr["key1"] = "val1"; $arr["key2"] = "val2"; print_r($arr); Array ( [key1] => val1 [key2] => val2 )

Arrays - foreach Loops through all the elements in an array: foreach ($arr as $element) { // Do something } Or foreach ($arr as $key => $element) { // Do something }

Arrays - Sorting sort() Sort array in ascending order rsort() Sort array in descending order asort() Sort associative array in ascending order by value ksort() Sort associative array in ascending order by key arsort() Sort associative array in descending order by value krsort() Sort associative array in descending order by key

Arrays - Sorting They sort "in place": $arr = array(5, 1, 2,6); sort($arr); print_r($arr); Array ( 0 => 1 1 => 2 2 => 5 3 => 6 )

FUNCTIONS

Functions Defined much like most other languages: function myfunction1() { // Do something } Name can start with an underscore or a letter (not a number Unlike variable names, function names are not case sensitive

Arguments When functions are defined with arguments (also known as parameters), those variables will exist in the function, with the values passed: function myfunction($param1, $param2) { echo $param1; echo $param2; } myfunction("one", "Two"); Arguments are pass OneTwo

Arguments Arguments are passed in the calling order, and have nothing to do with the names given: $var1 = "A"; $var2 = "B"; myfunction($var2, $var1); "B" "A" function myfunction($var1, $var2) { echo $var1; echo $var2; BA }

Default Argument Values You can define what will be used if the argument is not supplied: function myfunction($param1 = "One") { echo $param1; } myfunction(); One

Default Argument Values If a default is not defined, the argument is required! function myfunction($param1) { echo $param1; } myfunction(); Warning: Missing argument 1 for myfunction(), called in /Users/merrill/test.php on line 6 and defined in /Users/merrill/test.php on line 3

return Terminates the current function are "returns" control back to the calling function. If followed by a value, that value is returned to the location the function was called function myfunction() { return "Bob"; } print "My name is ". myfunction(); My name is Bob