PHP functions

advertisement
PHP and MySQL
David Lash
Module 3
Powering scripts with functions
1
Objectives

Some interesting PHP functions:
» print() & echo(), rand(), is_numeric, is_set, empty(),
htmlspecialchars(), addslashes(), and date().

Creating your own functions
»
»
»
»
»
»
»
»
General format
Passing arguments
Passing Arguments to Functions
Returning values
Passing by Reference
Using Default Argument Values
Using External Script Files
Variable Scope
Competency
Alert:
You need to
know this
!
Common
Problem
Area!
People seem to forget this
2
Notes on print()


You don’t need to use parenthesis with print()
Double quotes means output the value of any variable:
» $x = 10;
» print ("Mom, please send $x dollars");

Single quotes means output the actual variable name
» $x = 10;
» print ('Mom, please send $x dollars');

To output a single variable’s value or expression, omit the
quotation marks.
» $x=5;
» print $x*3;
- Note: Single quotes with HTML tags: print
'<font color="blue">';
- Can also escape with \
»print "<font color=\"blue\">";
3
print() VS echo()

Use echo() when want to output a
variable's value directly
<?php
echo "hello";
echo "x=", rand(1, 6);
echo “2 + 2 =“, 2+2, “but 4 + 4=“, 4+4;
?>
4
Testing variable status

PHP supports a series of variable testing
functions that return true or false.
» is_numeric() tests if a variable is a valid
number or a numeric string.
» is_set() – tests if a variable exists.
» empty() – checks if a variable is empty
5
is_numeric()
<?php
echo '2 ', (is_numeric('2') ? "true" : "false") . "<br>";
echo '2.4 ', (is_numeric('2.4') ? "true" : "false") . "<br>";
echo '2.2b ', (is_numeric('2.2b') ? "true" : "false") . "<br>";
echo '.5 ', (is_numeric('.5') ? "true" : "false") . "<br>";
echo '1.2.5 ', (is_numeric('1.2.5') ? "true" : "false") . "<br>";
echo 'A.5 ', (is_numeric('A.5') ? "true" : "false") . "<br>";
?>
6
is_set()
Checks if variable exists.
 Most useful for checking array elements:

if (!is_set($_POST[‘name’] && !is_set($_POST[‘score’]
{
print (“Error you must specify name and score”);
}
Note: from php.net contrib notes:
<?php
$a = 0;
$b = "0";
$c = "";
$d = 1;
print
print
print
print
print
$f= TRUE; print
$g= FALSE; print
$h=array();print
?>
isset($a)
isset($b)
isset($c)
isset($d)
isset($e)
isset($f)
isset($g)
isset($h)
?
?
?
?
?
?
?
?
"TRUE<br>" : "FALSE<br>"; //TRUE
"TRUE<br>" : "FALSE<br>"; //TRUE
"TRUE<br>" : "FALSE<br>"; //TRUE
"TRUE<br>" : "FALSE<br>"; //TRUE
"TRUE<br>" : "FALSE<br>"; //FALSE
"TRUE <br>" : "FALSE<br>"; //TRUE
"TRUE<br>" : "FALSE<br>"; //TRUE
"TRUE<br>" : "FALSE<br>"; //TRUE
7
)
empty()

Check if a variable is empty. Am empty string is:
» "" (an empty string)
» 0 (integert) or "0" (string)
» NULL, or FALSE
» array() (an empt)
» var $var; (a variable declared, but without a value in a class
if (empty($_POST[‘name’] && empty($_POST[‘score’] ) {
print (“Error you must specify name and score”);
}
Note: from php.net contrib notes:
$a
$b
$c
$d
=
=
=
=
0 ; print empty($a) ? "TRUE" : "FALSE"; //TRUE
"0" ; print empty($b) ? "TRUE" : "FALSE"; //TRUE
"" ; print empty($c) ? "TRUE" : "FALSE"; //TRUE
1 ; print empty($d) ? "TRUE" : "FALSE"; //FALSE
print empty($e) ? "TRUE" : "FALSE"; //TRUE
$f= TRUE ; print empty($f) ? "TRUE" : "FALSE"; //FALSE
$g= FALSE; print empty($g) ? "TRUE" : "FALSE"; //TRUE
$h=array();print empty($h) ? "TRUE" : "FALSE"; //TRUE
8
The rand() Function

Generate a random number.
» simulate a dice roll or a coin toss or
» to randomly show advertisement banner.

E.g., return a number 1 - 15
– $num = rand(1, 15);
Since PHP 4.2.0 do not need to seed with srand(). A
random seed value if omitted.
srand ((double) microtime() * 10000000);
$dice = rand(1, 6);
print "Your random dice toss is $dice";
9
A rand() application
<html><head><title> Favorite Character
</title> </head><body>
Banner ads can be randomly displayed:
My favorite cartoon character is
1. Store image as toon1.gif, toon2.gif, etc.
<?php
$r = rand(1, 6);
2. Assemble file image to use on the fly
print "<img src=toon{$r}.gif>";
?>
that guy
</body></html>
10
Objectives

Some interesting PHP functions:
» print() & echo(), rand(), is_numeric, is_set, empty(),
htmlspecialchars(), addslashes(), and date().

Creating your own functions
»
»
»
»
»
»
»
»
General format
Passing arguments
Passing Arguments to Functions
Returning values
Passing by Reference
Using Default Argument Values
Using External Script Files
Variable Scope
11
A couple HTML support Functions
$str = htmlspecialchars($str1);
Find html special characters, and convert
(e.g., < to <, & to &
$str = htmlspecialchars($str1, ENT_QUOTES);
$str = addslashes($str1);
Translates quotes too.
Find characters that need back slashes and add them. (‘,”,
\ and null)
(e.g., ‘ to \’, and “ to \”.
<?php
$str = "A <b>bold</b> 'quote' < and & fun .";
print "Original string=$str \n";
echo "specchars(str)=", htmlspecialchars($str), "\n";
echo "specchars(str, ENTQUOTE)=", htmlspecialchars($str, ENT_QUOTES), "\n";
echo "addslashes(str)=", addslashes($str), "\n";
?>
Original string=A <b>bold</b> 'quote' < and & fun .
specchars(str)=A <b>bold</b> 'quote' < and & fun .
specchars(str, ENTQUOTE)=A <b>bold</b> 'quote' < and & fun .
addslashes(str)=A <b>bold</b> \'quote\' < and & fun
Note, sites can also run with magic_quotes_gpc set to ‘on’ within php.ini, this
essentially, addslashes() to each string input from all get, post and cookie (gpc)
12
The date()Function

Use date() for date and time info
One or more characters that
define output.
$str = date(‘format string');

The format string defines output format:
– $day = date('d');
– print "day=$day";
Request date() to return the
numerical day of the month.
Note: If executed on December 27, 2005, would output “day=27”.

Note: Can also combine multiple character formats
» For example,
$today = date( 'l, F d, Y');
print "Today=$today";

On April 27, 2005, would output
Today=Wednesday, December 27, 2005
13
Selected date() character formats
Format
String
D
Meaning
d
Numerical day of month
returned as two digits (for
example, 01, 02)
Current month in long format
(for example, January,
February)
Current hour in day from 01 to
12 (for example, 02, 11)
s
H
Current hour in day from 00 to
23 (for example, 01, 18).
w
i
Current minute from 00 to 59
(for example, 05, 46)
Current day of week in long
format (for example, Sunday,
Monday)
Returns 1 if it is a leap year or 0
otherwise
y
F
h
l
L
m
Three-letter indication of day of
week (for example, Mon, Tue)
Current month of year from 01
to 12
Format
String
M
Meaning
Current month of year in short
three-letter format (for example,
Jan, Feb)
Seconds in current minute from
00 to 59 (for example, 07, 50)
t
Number of days in current
month (28, 29, 30, or 31)
U
Number of seconds since the
epoch (usually since January 1,
1970)
Current day of week from 0 to 6
(where 0 is Sunday, 1 is
Monday, and so on)
Current year returned in two
digits (for example, 01, 02)
Current year returned in four
digits (for example, 2001, 2002)
Y
z
Day number of the year from 0
to 365 (where January 1 is day
0, January 2 is day 1, and so on)
14
Working with UNIX timestamps
$stamp =
$var1=
time ();
Returns number of seconds since
Unix Epoch (January 1 1970
00:00:00 GMT)
date ('l, F d, Y', $stamp );
Convert optional UNIX time stamp
to format
$stamp2 = mktime ( $hr, $min, $src, $mon, $day, $year );
<?
Convert time and date into UNIX
timestamp
$today=date('Y-m-d');
$nextWeek = time() + (7 * 24 * 60 * 60);
$next_week = date('Y-m-d', $nextWeek);
print "today is $today \n" ;
print "please comeback nextweek = $next_week
\n";
?>
today is 2005-04-18
please comeback nextweek = 2005-04-25
15
Days to Christmas Code
1 <html> <head> <title> days to Christmas </title> </head>
2 <body>
3 <?
Get the current time since UNIX epoch.
4 $today = time();
5 $day = date( 'l, F d, Y');
6 print "Today=$day <br>";
7
Get the current day
8 $christmas = mktime(00,00,00,12,25,2004);
9
10 $secs_to_christmas = $christmas - $today;
11
Get the current epoch
12 $days_to_christmas = floor( $secs_to_christmas / 86400);
Seconds for 00:00:00
25, 2004;
14
Dec
15
16 print "There are $days_to_christmas shopping days to Christmas!";
17 ?></body> </html>
16
A little more on mktime() and date()
Converts 32nd day
<?php
echo date("M-d-Y", mktime(0, 0, 0, 12, 32, 2010)), "\n";
Converts extra 13th month
echo date("M-d-Y", mktime(0, 0, 0, 13, 1, 2002)), "\n";
echo date("M-d-Y", mktime(0, 0, 0, 1, 1, 1998)), "\n";
echo date("M-d-Y", mktime(0, 0, 0, 24, 1, 05)), "\n";
Converts date in past
Converts 2 digit year
?>
Jan-01-2011
Jan-01-2003
Jan-01-1998
Dec-01-2006
17
Objectives

Some interesting PHP functions:
» print() & echo(), rand(), is_numeric, is_set, empty(),
htmlspecialchars(), addslashes(), and date().

Creating your own functions
»
»
»
»
»
»
»
»
General format
Passing arguments
Passing Arguments to Functions
Returning values
Passing by Reference
Using Default Argument Values
Using External Script Files
Variable Scope
18
Defining Your Own Functions

Programmer-defined functions provide a way
to group a set of statements, set them aside,
and turn them into mini-scripts within a larger
script.
» Scripts that are easier to understand and change.
» Reusable script sections.
» Smaller program size
19
Writing Your Own Functions

Use the following general format
function function_name() {
set of statements
}
Enclose in curly brackets.

Include parentheses
at the end of the
function name
The function runs these
statements when called
Consider the following:
function OutputTableRow() {
print '<tr><td>One</td><td>Two</td></tr>';
}

You can run the function by executing
OutputTableRow();
20
As a full example …
Note: Function definition can be before or after function call
1. <html>
2. <head><title> Simple Table Function </title> </head> <body>
3. <font color="blue" size="4"> Here Is a Simple Table <table border=1>
4. <?php
OutputTableRow()
5.
function OutputTableRow() {
6.
print '<tr><td>One</td><td>Two</td></tr>';
function definition.
7.
}
8.
OutputTableRow();
9.
OutputTableRow();
10. OutputTableRow();
Three consecutive calls
11. ?>
to the OutputTableRow()
12. </table></body></html>
function
21
Passing Arguments to Functions
Input variables to functions are called
arguments to the function
 For example, the following sends 2 arguments

» OutputTableRow("A First Cell", "A Second Cell");

Within function definition can access values
function OutputTableRow($col1, $col2) {
print "<tr><td>$col1</td><td>$col2</td></tr>";
}
22
Consider the following code …
1. <html>
2. <head><title> Simple Table Function </title> </head> <body>
3. <font color="blue" size=4> Revised Simple Table <table border=1>
4. <?php
5. function OutputTableRow( $col1, $col2 ) {
6.
print "<tr><td>$col1</td><td>$col2</td></tr>";
7. }
8. for ( $i=1; $i<=4; $i++ ) {
9.
$message1="Row $i Col 1";
10.
$message2="Row $i Col 2";
11.
OutputTableRow( $message1, $message2 );
12. }
13. ?>
14. </table></body></html>
OutputTableRow()
Function definition.
Four calls to
OuputTableRow()
23
Objectives

Some interesting PHP functions:
» print() & echo(), rand(), is_numeric, is_set, empty(),
htmlspecialchars(), addslashes(), and date().

Creating your own functions
»
»
»
»
»
»
»
»
General format
Passing arguments
Passing Arguments to Functions
Returning values
Passing by Reference
Using Default Argument Values
Using External Script Files
Variable Scope
24
Returning Values

Use the following to immediately return a
value to the calling script:
return $result;
Can return, a string, a
value, array, or TRUE,
FALSE
1. function Simple_calc( $num1, $num2 ) {
2.
// PURPOSE: returns largest of 2 numbers
3.
// ARGUMENTS: $num1 -- 1st number, $num2 -- 2nd number
4.
if ($num1 > $num2) {
5.
return($num1);
6.
} else {
7.
return($num2);
8.
}
9. }
For example
$largest = Simple_calc(15, -22);
25
Example 2 – Function checks if its
been 24 hours since last post
<?php
$lastpost = mktime(5,15,0,04,15,2005);
echo 'Last Post was: ', date("M-d-Y H:m:s a", $lastpost), "\n";
$now = date("M-d-Y H:m:s a", time());
print "Time is: $now \n";
if (canPost($lastpost, 24)) {
print "It is OK to Post\n";
} else {
echo 'next post time is ', date("M-d-Y H:m:s a", $lastpost+(3600*24));
}
function canPost($lastpost, $diff) {
$diff = $diff*3600;
# convert hourse into seconds
$nextpost = $lastpost+$diff;
$timenow = time();
if ($timenow > $nextpost) {
return true;
} else {
return false;
}
}
Last Post was: Apr-15-2005 05:04:00 am
Time is: Apr-19-2005 07:04:09 am
It is OK to Post
26
Passing by Reference

When want to change an argument must pass reference.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<html> <head><title> Pass by Reference </title> </head>
<body>
<?php
$fname = 'John';
$lname = 'Adams';
print "<font color=blue> Pre call ";
print "fname=$fname lname=$lname </font><br>";
output_val( $fname, $lname );
print "<br><font color=red> Post call ";
print "fname=$fname lname=$lname </font>";
function output_val( &$first, $last ) {
$first = 'George';
$last = 'Washington';
}
?> </body></html>
The ‘&’ indicates
pass by reference
The default is
pass value
27
Using Default Argument Values

When want to change an argument must pass
reference.
1 <html> <head><title> Pass by Reference</title> </head>
2 <body>
3 <?php
4
5 output_val( 'Yankee Doodle' );
6 output_val( 'went to town', 4, 'red' );
7 output_val( 'riding on a pony', 6 );
8
9 function output_val( $text, $size = 3, $color = 'blue' ) {
10
print "<font size=$size color=$color>";
11
print "$text </font>";
12 }
13 ?> </body></html>
Call three
different ways
Set default values
for $size and
$color
28
Objectives

Some interesting PHP functions:
» print() & echo(), rand(), is_numeric, is_set, empty(),
htmlspecialchars(), addslashes(), and date().

Creating your own functions
»
»
»
»
»
»
»
»
General format
Passing arguments
Passing Arguments to Functions
Returning values
Passing by Reference
Using Default Argument Values
Using External Script Files
Variable Scope
29
Using External Script Files
Search for the file named within the double quotation marks and
insert its PHP, HTML, or JavaScript code into the current file.
Produce a warning
if it can’t insert the
specified file.
require ("header.php");
require_once(“header.php”);
include ("trailer.php");
include_once(“trailer.php”);
produce a fatal
error if it can’t
insert the specified file.
Use require_one() and include_once() when want to ensure
functions are included only once (E.g., when using libraries that may
also include code.)
30
Consider the following example
1. <font size=4 color="blue">
The script will output
2. Welcome to Harry’s Hardware Heaven!
these lines when the
file is included.
3. </font><br> We sell it all for you!<br>
4. <?php
5.
$time = date('H:i');
The value of $time will be set
6.
function Calc_perc($buy, $sell) {when the file is included.
7.
$per = (($sell - $buy ) / $buy) * 100;
8.
return($per);
This function will
9.
}
be available for
use when the file
10. ?>
is included.
31
header.php

If the previous script is placed into a file called header.php …
1. <html><head><title> Hardware Heaven </title></head> <body>
2. <?php
3. include("header.php");
4. $buy = 2.50;
Include the file
5. $sell = 10.00;
header.php
6. print "<br>It is $time.";
7. print "We have hammers on special for \$$sell!";
8. $markup = Calc_perc($buy, $sell);
Calc_perc() is defined in
9. print "<br>Our markup is only $markup%!!";
header.php
10. ?>
11. </body></html>
32
More Typical Use of External Code Files
Might use one or more files with only functions
and other files that contain HTML
 For example,

<hr>
Hardware Harry's is located in beautiful downtown
Hardwareville.
<br>We are open every day from 9 A.M. to midnight, 365
days a year.
<br>Call 476-123-4325. Just ask for Harry.
</body></html>

Can include using:
<?php include("footer.php"); ?>
33
More Typical Use of External Code Files
config.php
<?php
$HOME = ‘/home/dlash’;
$email = ‘dlash01@yahoo.com’;
$color = ‘red’;
$size = 122;
function output_val( $text, $size = 3, $color = 'blue' ) {
print "<font size=$size color=$color>";
print "$text </font>";
}
?>
34
Summary

Some interesting PHP functions:
» print() & echo(), rand(), is_numeric, is_set, empty(),
htmlspecialchars(), addslashes(), and date().

Creating your own functions
»
»
»
»
»
»
»
»
General format
Passing arguments
Passing Arguments to Functions
Returning values
Passing by Reference
Using Default Argument Values
Using External Script Files
Variable Scope
35
Module 3 Hands on Assignment

Create a PHP a set of PHP functions that create HTML form elements:
oradio( $name, $label1, $value1, $lebel2, $name2 )
– Would output
<input type=radio name=$name value=$value1> $label1
<input type=radio name=$name value=$value2> $lable2
otextbox( $name, $label, $size );
Would output
<input type=text name=$name size=$size> $label
Use default value of 40 for size but output an error if label has no value.
oform( $action );
• Would putput:
• Output an error is action is null.
• Place these functions in an external file called htmlhelpers.php
and include it into your script.
36
One possible solution
1
2
3
4
5
6
7
8
9
10
11
<html> <head> <title> form test </title> </head>
<body>
<?php
include('lab3.php');
oform( 'lab3_handle.php');
otextbox( "name", 'What is your name?', 20 );
print "<br>Did you enjoy the course?";
oradio( 'enjoy', 'yes', 1, 'no', 0);
?>
<br><input type=submit>
</form> </body> </html>
37
The file lab3.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
function oradio( $name, $label1, $value1, $label2, $name2 ) {
print "<input type=radio name=$name value=$value1> $label1";
print "<input type=radio name=$name value=$value2> $label2";
}
function otextbox( $name, $label, $size = 40 ) {
print "$label <input type=text name=$name size=$size> ";
}
function oform ( $action ) {
if ( empty($action) ) {
print "Error action=$action cannot be empty <br>";
exit;
}
print "<form action=$action method=post>";
}
?>
38
Hands-on Lab 2
Ask 2 survey questions
Common footer
Must answer both questions
39
Front end-Survey
survey.php
<html>
<head>
<title>Schedules</title>
</head> <body bgcolor="#ffffff">
<h1> Precourse Survey for Building Web Applications with PHP and Mysql </h1>
<table cellpadding="6" cellspacing="0" border="0" >
<form action='results.php' method=post>
<tr> <td> 1. What is your experience using any programming language? </td>
<td>
<input type=radio name=programming value=0> none
<input type=radio name=programming value=1> some
<input type=radio name=programming value=2> lots
</td> </tr>
<tr> <td> 2. What is your experience using any php/mysql ? </td>
<td>
<input type=radio name=php value=0> none
<input type=radio name=php value=1> some
<input type=radio name=php value=2> lots
</td> </tr>
<tr> <td> <input type=submit> </td>
</form>
</table>
<?php
include 'footer.php' ?>
</body>
<hr>
</html>
footer.php
<center>
David Lash
<br>
13 13 Mockingbird Lane
<br>
dlash@yahoo.com
40
One possible solution
<html>
<head>
<title>Schedules</title>
</head> <body bgcolor="#ffffff">
<h1> Survey Results </h1>
<?php
if ( !isset( $_POST['php'] ) || !isset( $_POST['programming'] ) ) {
print "Error you must specify a value for Q1 and Q2 <br>";
include 'footer.php';
exit;
} else {
$prog = $_POST['programming'];
print "Received Q1 = $prog <br>";
print "Received Q2 = {$_POST['php']} <br>";
}
include 'footer.php';
?> </body> </html>
41
Which Can Be Modified To . . .
<html>
<head>
<title>Schedules</title>
</head> <body bgcolor="#ffffff">
<h1> Survey Results </h1>
<?php
if ( !isset( $_POST['php'] ) || !isset( $_POST['programming'] ) ) {
print "Error you must specify a value for Q1 and Q2 <br>";
include 'footer.php';
exit;
} else {
$prog = $_POST['programming'];
print "Received Q1 = $prog <br>";
print "Received Q2 = {$_POST['php']} <br>";
$addr = 'dlash@condor.depaul.edu';
$subj = 'Survey Results' ;
$msg = "Q1=$prog \n Q2=$php ";
mail( "$addr", "Indelible Survey Results", $msg);
}
include 'footer.php';
?> </body> </html>
42
Download