PHP Final
PHP Final
PHP Workshop
PHP Workshop
PHP Workshop
Client-Side Definition
Scripts are run by the viewing web browser, usually in JavaScript. Do not have access to information located on the computer running the client-side script.
PHP Workshop
Server-Side Definition
Request is fulfilled by running a script (preprocessor) directly on the web server to generate dynamic HTML pages. Used to provide interactive web sites that interface to databases or other data stores. Advantage is the ability to highly customize the response based on the user's requirements, access rights, or queries into data stores.
PHP Workshop
Server-side v Client-side
Client-side Internet TCP IP DNS HTML VBScript Javascript CSS Java Applets ActiveX Flash ActionScript XML CGI ASP PHP JSP PERL .NET SQL Cold Fusion COM (VB, C#, C++) Java HTTP FTP Server-side
PHP Workshop
Integration
PHP Workshop
PHP
Version Improvements 4.0.5 Largely performance-related, thanks to the Zend engine which can pre-compile scripts (verus run-time script interpretation of PHP 3.x). A number of features have also been added to the core API. You can read more about specific engine improvements at Zend's What's New site. Free PHP is fairly easy to get started with, and their superb support site provides lots of guidance and sample code to get you through complex issues. Even for large tasks, I would consider PHP to be only moderately complex to use. Take advantage of user support and discussions on USENET, accessible via Google Groups.
Cost
Complexity
Popularity
PHP is most likely behind CGI/Perl in users, but it is clear that PHP's popularity is continually growing. This is largely thanks to easy integration with Apache, a powerful language and an abundance of free/cheap hosting services with PHP abilities.
Cost, support sites, simplicity, powerful feature set, easy integration with Apache, excellent API to free databases such as MySQL and PostgreSQL. Missing enterprise features necessary for 24-by-7 sites, Web focus of language reduces its use outside of the Web (unlike Perl). Small to mid-sized Web sites. #
PHP Workshop
PHP PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML.
PHP Workshop #
PHP Workshop
PHP Workshop
Structure
PHP Workshop
PHP Workshop
HTML Documents
Client
HTTP (Hypertext Text Transfer Protocol) Using HTTP, Client/Server can talk with each others about how to transport HTML documents. ( HTML HyperText Markup Language)
Server
PHP Workshop
The Outline
PHP File Components: HTML, PHP Tag, PHP Statements, Whitespace, Comments
. PHP Statements; .
?>
Syntax for PHP Statements: Variables: Submitted form variables, declaration, Operators: Arithmetic, String, Assignment, Reference, Control Structure: if, else, elseif, for, while
PHP Workshop #
What is PHP?
PHP is a server-side language designed specially for the web.
Conceived in 1994 by Rasmus Lerdorf PHP originally stands for Personal Home Page, now stands for PHP Hypertext Preprocessor Open source product
PHP code
Embed into an HTML page Be Interpreted by the web server to generate HTML or other output
What is PHP?
Server-side, scripting language Event based
Designed for use with HTML File Name .php Provide more flexibility than HTML alone Syntax is similar to C, Java, Perl
PHP Workshop #
PHP History
PHP succeeds an older product, named PHP/FI. PHP/FI was created by Rasmus Lerdorf in 1995. Personal Home Page/ Forms Interpreter - First Public release Version 3: 1997 PHP: Hypertext Preprocessor created by Andi Gutmans and Zeev Suraski Version 4: 2000 - Zend, full feature Actively supported by updates Version 4.4.6 on March 1, 2007 Version 5: 2004 New improved, Object Oriented & database connectivity The latest version Version 5.2.1 Stable
PHP Workshop
PHP Workshop
What is it?
PHP is a scripting language commonly used on web servers.
Stands for PHP: Hypertext Preprocessor Open source Embedded code Comparable with ASP Multiple operating systems/web servers
PHP Workshop
What is PHP?
PHP (recursive acronym for "PHP: Hypertext Preprocessor") is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. <? echo HI!; ?>
PHP Workshop #
What is PHP?
Compared to others like: Java Sun, compiled and interpreted (jsp) Perl Open Source, scripting .NET MS, opposite of Java ColdFusion Now Adobe, the original Javascript Netscape, client-side PHP Open Source, server-side
PHP Workshop #
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.
HTML
PHP CODE
HTML
Starting tag
<?php <? <script language="php">
<%
%>
PHP Workshop
Getting Started
2. Simple HTML Page with PHP The following is a basic example to output text using PHP.
<html><head> <title>My First PHP Page</title> </head> <body> <?php echo "Hello World!"; ?> </body></html> Copy the code onto your web server and save it as test.php. You should see Hello World! displayed. 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 <BR>)
PHP Workshop #
Getting Started
3.
<?php $today_dayofweek = date(w); if ($today_dayofweek == 4){ echo Today is Thursday!; } else{ echo Today is not Thursday.; } ?>
PHP Workshop
Getting Started
3.
PHP Workshop
Getting Started
3. Using conditional statements
If we run the script on a Thursday, we should see: Today is Thursday. On days other than Thursday, we will see: Today is not Thursday.
<?php $today_dayofweek = date(w); if ($today_dayofweek == 4){ echo Today is Thursday!; } else{ echo Today is not Thursday.; } ?>
PHP Workshop
Examples
PHP is a great way to implement templates on your website. How to implement a simple page counter
PHP Workshop
Examples
<html><head> <title>UCR Webmaster Support Group</title> <link rel="stylesheet" type="text/css" href=mycssfile.css"> </head> <body> <table width=80% height=30> <tr><td> <div align=center> Page Title </div> </td></tr></table>
PHP Workshop
Examples
<table width=80% height=30> <tr><td> <div align=center> UC Riverside Department<BR> <a href=mailto:[email protected]>[email protected]</a> </div> </td></tr></table> </body> </html>
PHP Workshop
Examples
<?php // header include(header.php); ?> Insert content here! <?php // footer include(footer.php); ?>
PHP Workshop #
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
Header
Page 1 Content
Page 2 Content
Page 3 Content
Page 4 Content
Page 5 Content
Footer
PHP Workshop #
Examples
Step 1: Simple Page Counter
Download the counter file webcounter.txt onto your machine Upload the webcounter.txt file onto your web server (via FTP, WinSCP, etc) Change the file permissions of the webcounter.txt file to 777 to allow the counter file to be updated.
PHP Workshop
Examples
Step 2: Simple Page Counter
Copy this code into a page where you want a counter.
<?php $COUNTER_FILE = webcounter.txt"; if (file_exists($COUNTER_FILE)) { $fp = fopen("$COUNTER_FILE", "r+"); flock($fp, 1); $hits = fgets($fp, 4096); $hits += 1; fseek($fp,0); fputs($fp, $hits); flock($fp, 3); fclose($fp); } ?>
PHP Workshop #
Examples
Step 3: Simple Page Counter
Next, output the counter value using PHP. Copy this line after the main block of code.
PHP Workshop
Examples
Step 3: Simple Page Counter You can change the text around the <?php echo$hits; ?> tags to your liking.
This example shows 1. How to escape from HTML and enter PHP mode 2. How to output variables onto the screen using PHP
PHP Workshop
Examples
2. How to output variables using PHP
Echo is the common method in outputting data. Since it is a language construct, echo doesnt require parenthesis like print(). Output Text Usage: <?php echo Hello World; ?> // prints out Hello World
Output the value of a PHP variable: <?php echo $hits; ?> // 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. <?= $hits ?>
PHP Workshop
Examples
3. Other uses with echo()
Automatically generate the year on your pages. This will print out 2004 UC Riverside. <?php echo date(Y); ?> UC Riverside
You will need to escape any quotation marks with a backslash. <?php echo I said \She sells sea shells\ ; ?>
PHP Workshop
processorder.php <html> <head> <title>Bobs Auto Parts Order Results </title> </head> <body> <h1>Bobs Auto Parts </h1> <h2>Order Results </h2> <?php echo <p>Order proceed.</p>; ?> </body> Ex </html>
PHP Workshop #
<body> <h1>Bobs Auto Parts </h1> <h2>Order Results </h2> <?php echo <p>Order proceed.</p>; ?> </body> </html>
PHP Workshop
The main reason for using server-side script is to be able to provide dynamic content to a sites users.
Content changes according to users needs or over time Attract visitors coming back
PHP Workshop
How it works
PHP is installed on web server Our web server is Apache (just an FYI) Server parses files based on extensions Returns plain HTML, no code
PHP Workshop
PHP Workshop
Windows Installation
PHP requires: Windows 98/Me or Windows NT/2000/XP/2003 Apache: http://httpd.apache.org/ PHP: http://www.php.net MySQL: Dev.mysql.com
PHP Workshop
WAMP:
www.wampserver.com/en/index.php
XAMPP:
www.apachefriends.org
PHP Workshop
Text Editor
Dreamweaver, Zend Studio, NotePad Word processors are not good for PHP editing PHP designer Best editors have:
Syntax coloring/highlights Syntax hinting PHP Workshop
#
Dreamweaver
Since we will be using Dreamweaver as our IDE, let us spend some time on its basics.
1)Creation of a new site 2)Syntax highlighting
PHP Workshop
PHP Workshop
Ill be using:
XAMPP 1.6.6a
Apache HTTPD 2.2.8 + Openssl 0.9.8g MySQL 5.0.51a PHP 5.2.5 PHP 4.4.8 phpMyAdmin 2.11.4
Fundamentals
PHP is embedded within xhtml pages within the tags: <?php ?> The short version of these tags can also be used: <? ?> Each line of PHP is terminated, like MySQL, with a semi-colon.
PHP Workshop
PHP Programming
<?php ?>
Short syntax
PHP Workshop
Hello World!
<html> <head> <title>PHP Test</title> </head> <body> <?php echo <p>Hello World!</p>; ?> </body> </html>
PHP Workshop
PHP Workshop
Literals..
All strings must be enclosed in single of double quotes: Hello or Hello. Numbers are not in enclosed in quotes: 1 or 45 or 34.564 Booleans (true/flase) can be written directly as true or false.
PHP Workshop
Comments
// This is a comment # This is also a comment /* This is a comment that is spread over multiple lines */ Do not nest multi-line comments // recommended over #
PHP Workshop #
Comments
It is good practice to enter comments
//single-line comments are like this #or like this /* Multiple line comments*/
PHP Workshop
Comments
<?php // this is a comment echo Hello World!; /* another multi-line comment */ ?>
PHP Workshop #
Displaying Data
There are two language constructs available to display data: print() and echo(). They can be used with or without brackets. Note that the data displayed by PHP is actually parsed by your browser as HTML. View source to see actual output.
PHP Workshop
Displaying data
<?php echo Hello World!<br />; echo(Hello World!<br />); print Hello World!<br />; print(Hello World!<br />); ?>
PHP Workshop #
Escaping Characters
Some characters are considered special Escape these with a backslash \ Special characters will be flagged when they arise, for example a double or single quote belong in this group
PHP Workshop
Escaping Characters
<?php
// Claire OReilly said Hello.
PHP Workshop
PHP Variables
1. 2. 3. 4. 5. 6. 7. <?php $utterance = "I love you!"; echo ("I want to say: . $utterance); echo ("<p>"); $utterance = "I will smite you!"; echo ("I want to say: . $utterance); ?>
Line 1 tells the browser: "Start PHP code here". Line 2 creates the variable $utterance and sets it to "I love you!". Line 3 prints a phrase that draws on the variable $utterance. Line 4 creates a <p> tag in HTML Line 5 RE-SETS the variable $utterance to "I will smite you!". Line 6 prints a new phrase with the rest variable $utterance. Line 7 tells browser : PHP code ends here.
PHP Workshop
Variables Names
In PHP variable starts with a $ Followed by letter or underscore Can contain letters, numbers, underscores, or dashes No spaces Case-sensitive and $Student are different as it is case sensitive
$student
Global variable global $student Superglobals Automatically available throughout all program $_GET $_POST $_Request $_COOKIES $_SESSION
PHP Workshop
PHP Workshop
PHP Workshop
PHP Workshop
User-Declared Variables
No need to declare variables before using them. A variable is created when we first assign a value to it. Variable Types: Integer, Float, String, Boolean, Array, Object, NULL(for unassigned variable) and resource (for database)
PHP is a very weakly typed language.
The type of a variable is determined by the value assigned to it. Strangely, the variable type will changed according to what is stored in it at any given time. For example, $total = 0; //Integer $total = 0.00; //Float $total = Hello; //String # PHP Workshop
PHP Workshop
Test if a variable exists and has nonempty, nonzero value: boolean empty(mixed var);
PHP Workshop #
Variables in PHP
Assign value to a variable using =, e.g. $total = 0; $total_amount = 0.00; $total_amount = $total; Type Casting: $total_amount = (float) $total; Variable Variables: $varname = total; $$varname = 5; is equivalent to $total = 5; Useful to operate a list of variables in loops.
PHP Workshop #
Variables
Variables are like a cup The same cup can hold lots of different things Same with variables
PHP Workshop
Variables
In PHP, you create a variable with a dollar sign and some text. Usually the text will be something descriptive of what it is going to hold. $name = Patrick Laverty; $dept = CIS; $campus_addr = Box 1885;
PHP Workshop #
Variables
There are many different kinds of variables in PHP Scalar Array Object
PHP Workshop
Scalar Variables
Hold single values String/text Numbers $name = Josiah; $dob = 1/1/23; $age = 84; $waist_size = 36;
PHP Workshop #
Array Variables
Hold multiple values All in one step example: $kids = Array(Tom,Dick,Harry); Multiple steps example: $kids = Array(); $kids[0] = Tom; $kids[1] = Dick; $kids[2] = Harry; Individual array values are just a scalar
PHP Workshop #
Array Variables
Associative Arrays may be easier to find stuff $teams = Array(bos=>Red Sox, nyy=>Yankees, bal=>Orioles); The two-step way works the same: $teams = Array(); $teams[bos] = Red Sox;
PHP Workshop #
Array
Note: arrays.php
PHP Workshop #
Object Variables
Well talk about these later.
Were in no rush
PHP Workshop #
Note: boolean.php
PHP Workshop #
Variables: Naming
$ followed by variable name
Case sensitive
$variable differs from $Variable Stick to lower-case to be sure!
Variables: example
<?php $name = Phil; $age = 23; echo $name; echo is ; echo $age; // Phil is 23 ?>
PHP Workshop #
Constants
Constants (unchangeable variables) can also be defined. Each constant is given a name (note no preceding dollar is applied here). By convention, constant names are usually in UPPERCASE.
PHP Workshop
PHP Workshop
Constants
<?php define(NAME,Phil); define(AGE,23); echo NAME; echo is ; echo AGE; // Phil is 23 ?>
PHP Workshop #
Constants
Note: constant.php
PHP Workshop #
or ?
There is a difference between strings written in single and double quotes. In a double-quoted string any variable names are expanded to their values. In a single-quoted string, no variable expansion takes place.
PHP Workshop
or ? <?php $name = Phil; $age = 23; echo $name is $age; // Phil is 23 ?>
PHP Workshop #
or ? <?php $name = Phil; $age = 23; echo $name is $age; // $name is $age ?>
PHP Workshop #
Hello World
helloworld.php <html> <body> <? echo Hello World!; ?> </body> </html>
PHP Workshop #
Strings:
PHP Workshop
Strings concatenate:
Note: strings.php
PHP Workshop #
Strings function:
Note: strings2.php
PHP Workshop #
PHP Workshop
Assignment Operators
= means set to. $tireqty = 1; //$tireqty is set to 1 Combination Assignment Operators
Operators Use Equivalent To
+= -= *= /= %= .=
PHP Workshop
$a = $a + $b $a = $a -$b $a = $a * $b $a = $a / $b $a = $a % $b $a = $a . $b
#
Comparison Operators
Comparison operators are use to compare two values, and it will return true/false,e.g. $a==$b will test if $a and $b have the same values. $a=5; $b=1; if( $a==$b ) and if ($a=$b) Operator Name Use == Equal $a==$b e.g. 0==0 true === Identical $a===$b e.g. 0===0 false != Not equal $a != $b !== Not identical $a !== $b <> Not equal $a <> $b < Less than $a < $b > Greater than $a > $b <= Less than or equal to $a <= $b >= Greater than or equal to $a >= $b
PHP Workshop #
Logical Operator
Operator ! && || and or Name Use Results NOT !$b Return true if $b is false and vice versa AND $a&&$b Return true if both $a and $b are true, otherwise false OR $a || $b Return true if either $a or $b are true, otherwise false. AND $a and $b Same with && but with lower precedence OR $a or $b Same with || , but with lower precedence
PHP Workshop
Bitwise Operator
Name Bitwise AND Bitwise OR Bitwise NOT Bitwise XOR Left shift Right shift
PHP Workshop
Array Operator
Operators Name Use + Union $a+$b == === != <> !==
PHP Workshop
Result Return an array containing everything in $a and $b Equal $a== $b Return true if $a and $b have the same elements Identical $a===$b Return true if $a and $b have the same elements with the same order Inequal $a != $b Return true if $a and $b are not equal Inequal $a <> $b Return true if $a and $b are not equal Non-indentity $a != = $b Return true if $a and $b are not identical
#
Other Operators
Object: new, ->, instanceof Ternary Operator: ?:
condition ? Value_if_ture : Value_if_false $grade >=50 ? Passed : Failed
Error suppression operator: $a = @(57/0) // Suppress error warning Without @, generate divide-by-zero warning Execution Operator: a pair of backticks (`xxx`)
$out = `ls l`; //The content in the backticks is executed as //a command at the servers command line.
PHP Workshop #
Control Structure
if statement else statement elseif statement switch statement Repeating actions through iteration
while Loops for and foreach Loops do .. while Loops
PHP Workshop
switch statements
Example: switch($find) { case a: echo <p>Regular Customer.</p>; break; case b: echo <p> Referred by TV. </p>; break; default: echo <p> Dont know how the customer found</p>; break; } PHP Workshop
while loops
Example: $num = 1; while ( $num < 5) { echo $num.<br />; $num ++; }
PHP Workshop #
for loops
Example:
for ($i= 1; $i <= 250; $i++) { $temp = i; echo $$temp.<br />; }
#
PHP Workshop
do .. while loops
Example:
$num = 100; do { echo $num.<br />; }while ($num > 100);
PHP Workshop
IF statement
If (expression)
Statement;
If($a>$b) {
Note: ifstatement.php
PHP Workshop
While Loop:
While (expression)
Statement;
While ($count<=10) {
Echo $count; $count++; Note: while.php }
#
PHP Workshop
Note: for.php
PHP Workshop #
Foreach Loop:
Foreach ($array as $value) Statement;
Note: foreach.php
PHP Workshop #
Note: continue.php
PHP Workshop #
Functions
Getting PHP to do some action for you echo() or print() phpinfo() (phpinfo.php)
PHP Workshop
Note: function.php
PHP Workshop #
Function arguments
PHP Workshop
Predefined Function
Note: prefunction.php
PHP Workshop #
PHP Workshop
Functions
Be lazy. Its a good thing. If youre going to do the same action more than once, write a function. sayhello.php function sayHello($toWhom) { echo Hello $toWhom; }
PHP Workshop
Functions
Lots have already been written for you: http://php.net/manual/en If you know the function: http://php.net/echo
PHP Workshop #
PHP GET
Built-in functions to get data from pages $_GET function collects values from a form sent with method = get HTML Page: <form action="welcome.php" method="get"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> PHP Response: Welcome <?php echo $_GET["fname"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old!
PHP Workshop #
PHP POST
Get is limited to 100 characters
Not awesome
PHP Workshop
PHP Post
HTML Page: <form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> PHP Response: Welcome <?php echo $_POST["fname"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old!
PHP Workshop #
Outline
This Lecture
File: Open, Read, Write, Lock, Array: Define, Access, Operate, Sort, String: Trim, Join, Split, Compare, Function: Include, Name, Parameter, Scope,
PHP Basics: History, Current Trend, File structure, PHP Tag, Syntax (variables, operators, Control structure)
PHP Workshop
Last Lecture
PHP Workshop
Files
Files can be used to store/retrieve data Basic steps for read/write a file (similar to C)
1. Open the file 2. Read/write data from/to the file 3. Close the file
PHP Workshop #
(In our server (www2.comp.polyu.edu.hk), we do not have enough permission to create a file on the # PHP Workshop directory pointed by
File Modes
Make three choices using mode when opening a file: 1. Open a file for reading only, writing only, or for reading+writing 2. If writing to a file, overwrite existing contents of a file or append new data to the end of the file. 3. If a file system differentiates binary and text files (like windows), you need to specify it.
PHP Workshop
Name
Read Read write
Meaning
a+
b
t
PHP Workshop
Open for reading, beginning from the start of the file. Open for reading/writing, beginning from the start of the file. Open for writing, beginning from the start of the file. If the file already exists, delete its contents; otherwise, create it. write Open for reading/writing, beginning from the start of the file. If the file already exists, delete its contents; otherwise, create it. Cautious write Open for writing, beginning from the start of the file. If the file already exists, do not open it and return false Cautious write Open for reading/writing, beginning from the start of the file. If the file already exists, do not open it and return false Append Open for appending (writing) only, starting from the end of the existing contents. If it does not exist, try to create it Append Open for appending (writing) only, starting from the end of the existing contents. If it does not exist, try to create it Binary Used in conjunction with one of other modes. Default mode. Under unix file system, no difference for binary/text files; windows has. Text Used in conjunction with one of other modes. An option only for # windows.
Gracefully terminate:
@ $fp = fopen("../phpfile/orders.txt", 'ab'); if (!$fp) { echo '<p><strong> Your order could not be processed at this time. .'Please try again later. </strong> </p> </body> </html>'; exit; }
PHP Workshop #
Write to a file
After a file is successfully opened, we can use fwrite() to write contents to it: fwrite($fp, $out_put_string) or fputs($fp, $out_put_string)
Another file write function without need to open a file:
int file_put_contents (string file_name, string data [, int flags [, resource context ] ] )
PHP Workshop
String Format
When putting delimiters such as tab, new line, , use \t, \n, An example: $out_put_string = $date.\t. $tireqty . tires \t. $address.\n;
PHP Workshop
PHP Workshop
Example
<?
?>
PHP Workshop
Arrays
In the previous lecture, we learn the scalar variable, a named location in which to store a value. An array is a named place to store a set of value, allowing you to group scalars. Element & Key (Index) The value stored in an array are called array elements; Each array element is associated with an index (also called key) in order to access the element. key value
Arrays
Numerically indexed Associatively indexed (maps) Multidimensional (combination of one or any of the above) Create an array with $var_name = array(); Index with $var_name[0] = assignment; or $var_name[$other_var] = assignment;
PHP Workshop #
PHP Workshop
Print Arrays
Use echo, e.g.: echo $product[0].' '.$product[1].' '.$product[2]; Use for with echo, e.g.:
for ($i=0; $i<3; $i++) echo $product[i]. ;
PHP Workshop
Print Arrays
Use echo: echo $price[Tire]. .$price[Oil]; Use foreach: foreach( $price as $key => $value ) echo $key.=>.$value.<br />; Use each: while ( $element = each ($price) ) echo $element[ key]..$element[value].<br />;
PHP Workshop #
Array Operator
Operators Name Use + Union $a+$b Result The array $b is appended to $a, but any key clashed are not added. == Equal $a== $b Return true if $a and $b have the same elements === Identical $a===$b Return true if $a and $b have the same elements with the same order != Unequal $a != $b Return true if $a and $b are not equal <> Unequal $a <> $b Return true if $a and $b are not equal !== Non-identical $a != = $b Return true if $a and $b are not identical
PHP Workshop #
Multi-dimensional Arrays
Initialize: $product = array (array ( T, Tire, 100), array (O, Oil, 10), array (S, Spark Plug, 4) ); Access & Display: echo $product[0][1].-. $product[0][2].<br />;
PHP Workshop
Sorting Arrays
sort( ): $product = array(Tire, Oil, Spark Plug); sort($product); Now the order in $product is Oil, Spark Plug, Tire.
For an array with descriptive keys, use asort() Sort it according to the value of each element ksort() Sort it according to the key of each element Reverse Sort: sort(), asort(), ksort() sort an array into ascending order rsort(), rasort(), rksort() sort an array into descending order
PHP Workshop
User-Defined Sorts
Use usort() you can define your own sorting Write your own compare function to tell PHP how to compare: function compare ($x, $y) { } usort( $product, compare);
PHP Workshop
PHP Workshop
PHP Workshop
Format Strings
trim( ), ltrim( ), rtrim( ): trim( ): Strip whitespace from the start and end of a string ltrim( )/rtrim( ): strip whitespace from the start / from the end. printf( ): printf(Total amount %.2f, $total);
PHP Workshop #
ucfirst( )
ucwords( )
PHP Workshop
PHP Workshop
PHP Workshop
Comparing Strings
int strcmp( string str1, string str2) equal return 0 greater (lexicographic order) a number > 0 less (lexicographic order) a number < 0 int strcasecmp( ): not case sensitive
PHP Workshop
PHP Workshop
Replace Substrings
mixed str_replace(mixed needle, mixed new_needle, mixed haystack [,int &count] ) ); Replace all instances of needle in haystack with new_needle.
string substr_replace( string str, string replacement, int start [, int length]); Replace the part of the string with replacement
PHP Workshop
PHP Workshop
PHP Workshop
A Basic Form
How we do things now: eform.cgi <form method=POST action=http://www.brown.edu/cgilocal/eform.cgi> <input type=text name=name> <input type=text name=age> <input type=submit> </form>
PHP Workshop
In PHP, all variables start with $. We can access each form fields as a PHP variable related to the name of the form field. Three ways: $tireqty //short style $_POST[tirety] //medium style. Recommend!!! $HTTP_POST_VARS[tireqty] //long style
PHP Workshop #
The GET method, access data using $_GET[field_name] ,e.g., $_GET[tireqty] In both cases, we can use $_REQUEST[field_name]. e.g. $_REQUEST[tireqty]
PHP Workshop #
A Basic Form
How we do things with PHP: basicform.html <form method=POST action=output.php> <input type=text name=name> <input type=text name=age> <input type=submit> </form>
PHP Workshop #
A Basic Form
Capturing the data in output.php Variables:
$_POST[name] $_POST[age]
A Basic Form
Weave HTML and PHP output.php
<html><body> <? $name = $_POST[name]; $age = $_POST[age]; echo My name is $name and I am $age years old; ?> </body></html> # PHP Workshop
Data Validation
PHP Workshop
A Basic Form
Outputting to the screen is nice, but boring We could email the results Lets store data in a database
PHP Workshop
Layers of a Database
Server Database Tables Fields/Columns Records Data
PHP Workshop
PHP Workshop
PHP Workshop
phpMyAdmin
phpMyAdmin is a graphical view of your database Very easy Lets take a look (http://brown.edu/phpMyAdmin)
PHP Workshop
?>
PHP Workshop #
PHP Workshop
Database Table
Table named info has two fields, name and age Use a SQL INSERT statement:
PHP Workshop
Database Table
Send it to the Database: mysql_query($sql,$conn);
PHP Workshop
?> <html><body> Thank you, your name and age were received. </body></html>
PHP Workshop
PHP Workshop
PHP Workshop
PHP Workshop
PHP Workshop
I Hate Objects!
If you dont like using mysql_fetch_object:
mysql_fetch_array($result) mysql_fetch_assoc($result)
PHP Workshop
mysql_fetch_array()
Access the columns by numbers: while($array = mysql_fetch_array($result)) { echo $array[0]; echo $array[1]; }
PHP Workshop #
mysql_fetch_assoc()
Access the columns by column names: while($array = mysql_fetch_assoc($result)) { echo $array[name]; echo $array[age]; }
PHP Workshop #
PHP Workshop
Data Validation
Very Important! Without it, your site and all others can be hacked! PHP makes it easier
PHP Workshop
Data Validation
Cut down on XSS with htmlentities() Cut down on SQL-injection with mysql_real_escape_string() Check that youre getting what you expect Check that youre getting the length you expect Dont trust JavaScript
PHP Workshop #
Data Validation
Cross site scripting vulnerability
Allows a user to input scripts Allows a user to input links to malicious sites Allows a user to steal a session/cookie/password
The htmlentities() function turns entities into its harmless entity number. A is turned into '
#
PHP Workshop
Data Validation
SQL-injection vulnerability
Allows a user to directly access your database Allows a user to get access to other accounts Allows a user to read data you dont want read
Prevention can be as simple as escaping quotes with mysql_real_escape_string to all user input $clean_user = mysql_real_escape_string($_POST[username]) # PHP Workshop ;
Data Validation
Get what you expect to get Dont change it, give error message
Example: (validinsert.php) Age, should be less than 110, and numeric. Reject anything else if(strlen($age)>3){ //error message } if(!is_int($age)){ //error message } if($age>110 || $age<18){ //error message }
PHP Workshop #
Data Validation
Get the length you expect
<input type=text name=username maxlength=8>
PHP Workshop
Data Validation
Dont trust JavaScript Do client side AND server side validation
PHP Workshop
Overview of phpMyAdmin
Note: mysql1.php
PHP Workshop #
Insert
PHP Workshop
Update
PHP Workshop
Delete
PHP Workshop
Connecting to a Database
PHP Postgresql Functions: http://www.php.net/manual/en/ref.pgsql.php pg_connect() returns a connection resource that is needed by other PostgreSQL functions. <?php $username = cs386"; $password = "introdb"; $databasename = cs386"; $hostname = "db.cecs.pdx.edu";
$connection = pg_connect("host=$hostname dbname=$databasename user=$username password=$password") or die ("Could not connect"); // do stuff pg_close($connection); ?>
PHP Workshop #
Connection Errors
<?php $username = cs386"; $password = "foobar"; // wrong password $databasename = cs386"; $hostname = "db.cecs.pdx.edu";
$connection = pg_connect("host=$hostname dbname=$databasename user=$username password=$password") or die ("Could not connect"); // do stuff pg_close($connection);?>
Error Message
Warning: pg_connect(): Unable to connect to PostgreSQL server: FATAL: Password authentication failed for user cs386" in ./display.php(433) : eval()'d code on line 7 # PHP Workshop Could not connect
<?php // assuming we already connected with code from previous slide... $query = " SELECT DISTINCT N.candname, N.party FROM candcl N; "; $result = pg_query($connection, $query)
PHP Workshop
We would have seen the error message Warning: pg_query(): Query failed: ERROR: column "foobar" does not exist in ./display.php(433) : eval()'d code on line 20 Query error: ERROR: column "foobar" does not exist
PHP Workshop
Output
4 rows returned Name: MCCAIN, JOHN S. Party: REP PHP Workshop
PHP Workshop
Calling pg_fetch_array() will return an enumerated and an associative array <?php $array = pg_fetch_array($result); echo "Name: $array[candname"]<br/>\n"; echo Party: $array[party"]<br/>\n";
PHP Workshop
<?php $username = "akimbo_ro"; $password = "readme"; $databasename = "akimbo"; $hostname = "db.cecs.pdx.edu"; $connection = mysql_connect($hostname, $username, $password) or die ("Could not connect");
mysql_select_db($databasename) or die("Database select error: " . mysql_error()); $query = " SELECT DISTINCT N.candname, N.party FROM candcl ); "; $result = mysql_query($query, $connection) or die("Query error: " . mysql_error()); echo mysql_num_rows($result) . " rows returned\n"; while ($row = mysql_fetch_row($result)) { echo "Name: $row[0]<br/>\n"; echo Party: $row[1]<br/>\n"; } mysql_close($connection); ?>
PHP Workshop #
PHP Workshop
Rainfall Application
Read the contents of a database Get the rainfall data Parse the results Display it
PHP Workshop
Connecting to a Database
PHP Has a set of functions that can be used with MySQL First step is to setup a link to the desired database
PHP Workshop
Making a Query
Once a link is established, querying is easy Errors for any given function are returned by mysql_error()
PHP Workshop
PHP Workshop
Associative Arrays
An array that can be indexed by a string A set of key->value pairs Very similar to a hash in Perl
PHP Workshop
PHP foreach
Similar to the Perl equivalent Allows iterating through each element of an array
PHP Workshop
PHP Workshop
PHP Workshop
The Results
PHP Workshop
http://128.174.242.224/PHPExamples/rainfall.php
A Slight Improvement
This was not the exact code we came up with I added some titles and a neat trick
Highlight every other row in the table This makes information more readable
PHP Workshop
PHP Workshop
SQL | PHP
Tutorial
at 8am. god, its early.
PHP Workshop
SQL intro
There are many different versions of SQL available for usage. Oracle MySQL SQLite DB2 Mimer The popular ones are Oracle and MySQL with MySQL quickly gaining ground. Ill be showing you MySQL. The syntax between SQL domains varies little and with google skills you can adjust this knowledge for SQLite, which Ive # PHP Workshop never used.
Databases _ creation
CREATE TABLE tableName ( name VARCHAR(55), sex CHAR(1), age INT(3), birthdate DATE, salary DECIMAL(10,2), primary key(name) ); Types of attributes: char, varchar, int, smallint, decimal, date, float, etc. *varchar is a string with varying # of characters. In our example, 55 is the characters longest possible string allowed. *decimal(10,2) indicated 2 places after the decimal point and 10 total digits (including the decimal numbers)
PHP Workshop
Databases _ creation 2
CREATE TABLE tableName ( name VARCHAR(55), sex CHAR(1) NOT NULL, age INT(3), birthdate DATE, salary DECIMAL(10,2) DEFAULT 0.00, primary key(name) ); Primary key: primary key is a UNIQUE value. For every entry in your database this must be unique and not null and every DB must have one. NOT NULL: column must have a value DEFAULT: you can set a default value if no other value is inputted for # PHP Workshop that column.
Databases _ indexed primary keys specifying a column as a primary key you can have the Instead of
database create a column of numbers that will automatically increment with each entry inserted into the DB. Example: CREATE TABLE tableName ( id INT AUTO_INCREMENT, name VARCHAR(55), sex CHAR(1), age INT(3), birthdate DATE, salary DECIMAL(10,2), primary key(id) );
PHP Workshop #
Databases _ deletion
DROP TABLE tableName;
PHP Workshop
Databases _ insertion
Inserting data in the database: INSERT INTO tableName(name,sex,age) VALUES(Mr. Freeze,M,42); Also valid: INSERT INTO tableName(sex,name,age) VALUES(F,Mr. Freeze,42); Order doesnt matter.
PHP Workshop
PHP Workshop
Databases _ updating
Suppose we want to change Mr. Freezes age to 52.
UPDATE tableName SET age = 52 WHERE name LIKE Mr. Freeze And so forth.
PHP Workshop
Databases _ aggregates
This is the actual meat of using SQL. These are where you set your conditions, narrow down your table into a usable set. Here are the usable functions, Ill show a quick example with each. The only way to really know this stuff is practice. Group by Count Sum Avg Min/Max Order by
PHP Workshop
Databases _ group by
This is the actual meat of using SQL. These are where you set your conditions, narrow down your table into a usable set. Here are the usable functions, Ill show a quick example with each. The only way to really know this stuff is practice. Group by lumps all the common attributes into one row. SELECT employee_id, MAX(salary) FROM Works_In GROUP BY dept_id; * MAX selects the maximum value in its () likewise for MIN
PHP Workshop
Databases _ count
Count counts the number of columns with the specified attribute.
SELECT term, COUNT(course_id) FROM teaches GROUP BY term; We counted the number of courses taught during x term. AVG & SUM function pretty much the same way.
PHP Workshop
PHP Workshop
PHP Workshop
PHP Workshop
PHP Workshop
PHP Workshop
PHP _ insertion
<?php mysql_connect(localhost,username,pw) or die(mysql_error()); mysql_select_db(ljlayou_comp353 or die(mysql_error()); mysql_query(INSERT INTO Works_In(company,position) VALUES(McDonalds,fry cook)); ?> Were querying PHP to tell MySQL to do something, in this case create the table. The same applies for dropping a table. As you can see our code is being reused over and over. It gets pretty repetitive like this.
PHP Workshop
PHP Workshop
PHP Workshop
<?php []
while ($row = mysql_fetch_array($result)) { echo company: .$row[company]. | position: .$row[position]; echo <br/>;} ?> If you have noticed the . symbol signifies a concatenation.
PHP Workshop
<?php
PHP Workshop
PHP Workshop
PHP Workshop
PHP Workshop
PHP Workshop
PHP Workshop
Add/Delete/Update Table
INSERT INTO user VALUES (bond, 007); DELETE FROM user WHERE id=007; UPDATE user SET name=BOND WHERE id=007;
PHP Workshop #
Query Database
SELECT * FROM user; SELECT * FROM user WHERE name=BOND; SELECT DISTINCT name FROM user; SELECT name, id FROM user ORDER BY name;
PHP Workshop
Other PHP pages can link to it and use the variables as their own.
PHP Workshop
PHP Workshop
include("conf.php");
// form submitted so start processing it
$title = $_POST["title"];
$authors = $_POST["authors"]; // set up error list array & validate text input fields $errorList = array(); $count = 0; if (!$title) { $errorList[$count] = "Invalid entry: Title"; $count++; } // set default value for contact person if (!$contact) { $contact = $def_contact; } // check for errors & if none found... if (sizeof($errorList) == 0) {
$query = "INSERT INTO papers (title, authors, description, comment, super, bibtex, url, genre) VALUES ('$title', '$authors', '$description', '$comment', '$super','$bibtex','$url','$genre')"; $result = mysql_query($query) or die ("Error in query: $query. " . mysql_error());
echo "<font size=-1>Addition successful.<br><br> <a href=papers.php>Go back to the main page</a> | <a href=http://www.cs.tcd.ie/Karl.Quinn/>home</font>"; // close database connection
mysql_close($connection);
} else {// errors occurred} ?> PHP Workshop
$connection = mysql_connect($host, $user, $pass) or die (); mysql_select_db($db) or die ("Unable to select database!"); $query = "SELECT * FROM papers"; $result = mysql_query($query) or die ("Error in query);
?> <table cellpadding="0" cellspacing="0" border="0" width="622"> <tr><td bgcolor="990000"><img src="images/spacer.gif" alt="" height="2"></td></tr> <? // if records present
if (mysql_num_rows($result) > 0)
{ // iterate through resultset & print title with links to edit and delete scripts
while($row = mysql_fetch_object($result))
{ ?> <font size="-2"><a href="edit.php?id=<? echo $row->id; ?>">edit/view</a> | <a href="delete.php?id=<? echo $row->id; ?>">delete</a></font><p>
<font size="-1"><b><? echo $row->title; ?></b><br> <font size="-1"><b>-<? echo $row->authors; ?></b>
<br><a href="<? echo $row->url; ?>" target="_blank"> pdf</a> <br><br><br> </font> <table cellpadding="0" cellspacing="0" border="0" width="622"> <tr><td bgcolor="990000"><img src="images/spacer.gif" alt=" height="2"></td></tr> <? } } // if no records present else{}
mysql_close($connection);
?>
PHP Workshop
PHP Workshop
PHP Workshop
</form> </table>
$query = "UPDATE papers SET title = '$title', authors = '$authors', description = '$description', comment = '$comment', super = '$super', bibtex = '$bibtex', url = '$url', genre = '$genre' WHERE id = '$id'";
$result = mysql_query($query) or die ("Error in query: $query. " . mysql_error()); // print result echo "<font size=-1>Update successful.<br><br> <a href=papers.php>Go back to the main page</a> | <a href=http://www.cs.tcd.ie/Karl.Quinn/>home</a></font>";
// close database connection mysql_close($connection); } else{} ?>
PHP Workshop
Create Form
Note: form.html
PHP Workshop
Slide #50
I think thats enough [email protected] Next topic to be announced for early May
PHP Workshop
www.php.net
PHP Workshop
Review
Weve started PHP..
Escaping XHTML Comments Basic Syntax Variables Constants
PHP Workshop
Basic Math:
Note: basic.php
PHP Workshop #
Float
PHP Workshop
Float
Note: float.php
PHP Workshop #