Title: PHP Userdefined Functions
1PHP User-defined Functions
- SI 539
- Fall 2004
- Prof. Sandra Bartlett
2What is a Function?
- A block of code
- with a name
- that does a job.
- May need external information.
- May return a value.
3You Have Used Functions!
- result mysql_query("SELECT id,
-
first_name, - surname
FROM people") - echo date("F d Y Hi", filemtime(__FILE__))
- How do they do what they do?
- (print and echo are not technically functions
they are language constructs)
4How do they work?
- When a function name is encountered in a program
- The computer starts executing the first statement
of code written in the function definition - Continues executing the function code until it
gets to the end or it is told to return - Then it goes back to the original code and
continues executing where it left off
5subtrahend) return minuend -
subtrahend // subtract echo "Hello
World
" remainder subtract (5, 4.5)
echo "5 4.5 remainder" ?
alternative echo "5 4.5 ", subtract (5,
4.5) ?
6Why write your own functions?
- You can't find a built-in function to do a job
- You know you want to do it more than once
- You find yourself coping and pasting code
- You might want to use it in another project
- Reduce code complexity
- Isolate code that is likely to change
- Isolate code that is platform dependent (makes
porting easier)
7General Form
- function name(parameter1, parameter2, ...)
-
- code to do the job goes here!!
- return value
- // name
- function is a keyword used to define a function
- hold the code for the function
- name is the function name that you make up it
must be meaningful, and follow the naming style - Function ends if final is reached or return is
found - Can have any kind of PHP code in
8Optional Parts
- Parameters pieces of information from outside
the function that are needed by the function to
do its job - mysql_query needs a query to send
- filemtime needs a file name
- date needs the date and how to format it
- return statement tells the function to stop
executing and optionally pass back a value
9Defining vs. Calling
- Define a function write the code to do the job
- function fred(fun) echo "fred loves fun"
- Call a function tell the computer to execute
the code to actually do the job - fred("sky diving")
- A function can be called before it is defined
(there are exceptions, but that is beyond the
scope of this course)
10Variable Scope
- Parameters and variables declared inside a
function are available only inside the function - They come into existence when the function is
called - They disappear when the function exits
- Variables declared outside a function are not
available inside the function
11FYI Global Variables
- Automatically global
- _POST, _GET
- _SERVER, _ENV
- The keyword global
- Makes internal variables available externally
- Makes external variables available internally
- global fred
- Beyond the scope of this course
12Example 1(no parameters, no return value)
- // maybe code here
- function printThanksgivingGreeting()
-
- echo "Happy Thanksgiving!"
- // printThanksgivingGreeting
- // maybe code here
- ?
- Maybe HTML here
- // maybe code here
- printThanksgivingGreeting()
- // maybe code here
- ?
13Example 2(parameters, no return value)
- // maybe code here
- function sayHi(name)
-
- if (strlen(name))
- echo "Hi, name!"
- else
- echo "Hi there!"
- // sayHi
- // maybe code here
- ?
- Maybe HTML here
- // maybe code here
- sayHi(Santa Claus)
- // maybe code here
- ?
14Example 3(no parameters, return value)
- function dndRoll3D6()
-
- total rand(1,6) rand(1,6) rand(1,6)
- return total
- // dndRoll3D6
- ?
- echo "Your Strength is ", dndRoll3D6()
- echo "Your Dexterity is ", dndRoll3D6()
- ?
15Example 4(parameters, return value)
- function gameRoll(howMany)
-
- for (i 0 i
- total rand(1,6)
- return total
- // gameRoll
- ?
- thisRoll gameRoll(rand(2,8))
- echo "You rolled thisRoll"
- ?
16Which Example to Follow?
- Does your function need outside information to do
its job? - Yes have parameters
- No no parameters
- Does the calling code need information back from
the function? - Yes return a value
- No let the function end naturally, or use
return with no value
17Why write your own functions?
- You can't find a built-in function to do a job
- You know you want to do it more than once
- You find yourself coping and pasting code
- You might want to use it in another project
- Reduce code complexity
- Isolate code that is likely to change
- Isolate code that is platform dependent (makes
porting easier)
18Validation Functions
- Used on any web page with text input
- Make sure text follows a set of rules or
guidelines - Filter out malicious data
- (PHP server side JavaScript client side)
19Writing Validation Functions
- Must be efficient
- Used often
- Must not print or do anything
- May need to do different things in different
pages - Usually returns a boolean value
- Consistent, meaningful naming style makes
maintenance easier and code more readable - isZip(str) phoneValid(str) checkURL(str)
- Often use regular expressions (beyond the scope
of this course)
20Things that need validating
- name
- date
- zip code
- phone number
- credit card number
- URL
- email address
- email message
- list of thangs
- etc.
21Helpful Functions
- string functions (strstr(), etc.)
- is_ functions (is_integer(), etc.)
- ctype_ functions (ctype_alpha(), etc.)
- date functions
22PHP Date Validating Functions
- int strtotime ( string aTime)
- If date is between 1/1/1970 and /2039
- returns a timestamp, if it can figure out what
time the string, aTime, stands for else -1 - http//www.si.umich.edu/bartlett/strtotimeTest.ph
p - boolean checkdate ( int month, int day, int year)
- If year is between 1 and 32767 inclusive
- Returns TRUE if the date is valid (does leap year)
23Using Dates in Complex Websites
- How would you get a date from the user?
- How would you validate a date?
- How would you store it in a database?
24Getting a Date from a Form
- Text field, textarea, radio buttons, checkboxes,
select? - Number and range of dates
- Airplane flight
- Birthday
- Customer order
- Historical personage
- Paleontology
25Validating a Date
- If date is between 1/1/1970 and /2039
- if (strtotime(_POSTfred)
- echo "Your date is not valid"
- Else if year is between 1 and 32767 inclusive
- if (!checkdate(month, day, year))
- echo "Your date is not valid"
- Else write your own using string functions, etc.
26Storing a Date in MySql
- DATE
- "YYYY-MM-DD"
- YYYYMMDD
- DATETIME
- "YYYY-MM-DD HHMMSS"
- YYYYMMDDHHMMSS
- TIMESTAMP (? stored as DATETIME)
- 1099630800
- STRING
27MySql Date Storage "Gotcha"
- The MySQL server performs only basic checking on
the validity of a DATE - year - 1000 to 9999
- month - 00 to 12
- day - 00 to 31
- Doesn't check for 28 days in Feb., etc.
- Bad date stored as 0000-00-00
- 2 digit year format is ambiguous
28Malicious HTML
- Deface a web site where user input is included in
a web page (guest book, message board, etc.) - htmlspecialchars() - strips the HTML parsing
symbols ( ") and replaces them with their
equivalents as html entities (lt gt amp
quot ). This prevents the execution of any HTML
you dont want. - The htmlentities() - strips out all special
characters and replaces them with their
respective HTML entity equivalents.
29Example of Malicious HTML
- Where malicious HTML gets into your database
- What I typed in
- See what an exciting course
-
- SI 539 is!!!
-
- Result of malicious HTML
- http//www.si.umich.edu/bartlett/fixHTML.phps
http//www.si.umich.edu/bartlett/fixHTML.php
30Other Problems
- http//projects.si.umich.edu/bartlett/state.php