0% found this document useful (0 votes)
16 views47 pages

Week 05b - PHP

Week 05b - PHP

Uploaded by

colio
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views47 pages

Week 05b - PHP

Week 05b - PHP

Uploaded by

colio
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

PHP

Dr. Michele C. Weigle


CS 312 - Internet Concepts
Old Dominion University
Much of these slides are based on materials and notes from Dr. Ralph Grove

This work is licensed under a


Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
What is PHP?
• PHP: Hypertext Preprocessor
• Open-source server-side scripting language
– different from JavaScript (a client-side scripting language)
• Free alternative to Microsoft's Active Server Pages (ASP)
• Syntax is similar to Perl and C
• PHP is often combined with a MySQL database
• Can be directly embedded into HTML
PHP Tutorial at W3Schools: http://www.w3schools.com/php/default.asp
CS 312 - Internet Concepts / Weigle 2
PHP Execution Modes
• Two main execution modes
– interpreted on the command line
– embedded in HTML

• Common Gateway Interface (CGI)


– allows web servers to execute programs/scripts
– usually in response to a HTTP GET or POST request
– program typically generates HTML as output that is sent in the HTTP
response
– scripts used to be required to be stored in cgi-bin folder on server
https://en.wikipedia.org/wiki/Common_Gateway_Interface
CS 312 - Internet Concepts / Weigle 3
Outline
• PHP and HTML Interaction
• PHP Basic Syntax
• PHP Conditionals, Loops, Functions
• User Registration Example

CS 312 - Internet Concepts / Weigle 4


Hello World Example
<html> • PHP code must start with <?
<head> php and end with ?>
<title>PHP Test</title> – file extension must be .php
</head> – file must be executable by
<body> owner and group (http), so
<?php chmod 770
echo '<p>Hello • Lines end with semicolon (;)
World</p>';
• echo - output string
?>
</body>
</html>
https://www.cs.odu.edu/~mweigle/cs312/examples/php/hello.php (text version)
CS 312 - Internet Concepts / Weigle 5
CGI-HTTP Process (HTML+PHP)
Client Server
• Client requests a .php file
that contains both HTML HTTP GET request retrieve file
hello.php
and PHP execute PHP
• Server retrieves file code in file
• Server executes any PHP form HTTP
code in the file response
• Output of PHP code inserted including
PHP output
in place in the HTML
• Result is sent to client in HTTP response send
response to
body of HTTP response 200 OK
<data> client
CS 312 - Internet Concepts / Weigle 6
Response Body vs. Original File
% curl -i
https://www.cs.odu.edu/~mweigle/cs312/examples/php/hello.php
HTTP/1.1 200 OK
Server: nginx
Date: Fri, 25 Sep 2020 14:32:12 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 182
Connection: keep-alive
Vary: Accept-Encoding ~/secure_html/cs312/examples/php/hello.php
X-Powered-By: PHP/5.6.40

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="UTF-8"/>
<title>PHP Test</title>
</head>
<body>
<p>Hello World</p></body>
</html>
CS 312 - Internet Concepts / Weigle 7
Simple PHP Form Processing Example
• HTML document calling a PHP script
<html><body>
<form action="action.php" method="post">

<p>Your name: <input type="text" name="name" />


</p>

<p>Your age: <input type="text" name="age" /></p>


<!DOCTYPE>, <html>, <head>,
<p><input type="submit" /></p> <meta>, <body> tags should be included
in the HTML returned by the PHP script, but
</form> have been omitted from the slides for brevity.
</body></html>
https://www.cs.odu.edu/~mweigle/cs312/examples/php/php-form.html
CS 312 - Internet Concepts / Weigle 8
action.php
<p>Hi <?php echo htmlspecialchars($_POST['name']); ?>!
</p>
<p>You are <?php echo (int) $_POST['age']; ?> years
● $_POST - associative array that holds the names and values from the
old.</p>
HTML input form (when HTTP POST used).
● htmlspecialchars() - ensures that any special HTML characters
are properly encoded so people can't inject HTML tags or JavaScript into
your page.
● int() - convert text to an integer
https://www.cs.odu.edu/~mweigle/cs312/examples/php/action.php (text version)
CS 312 - Internet Concepts / Weigle 9
CGI-HTTP Process (HTML Form)
• Form submission triggers Client Server
HTTP POST request for HTTP POST request retrieve file
action.php action.php
execute PHP
• Form names and values are in name=John&age=21 code in file
the body of the request
form HTTP
• Server retrieves file response,
• Server executes the PHP script body is PHP
• Output of PHP code is the output
HTTP response body HTTP response send
• Result is sent to client 200 OK response to
<data> client
CS 312 - Internet Concepts / Weigle 10
Response Body vs. Original File
% curl -i -d "name=John&age=21"
https://www.cs.odu.edu/~mweigle/cs312/examples/php/action.php
HTTP/1.1 200 OK
Server: nginx
Date: Fri, 25 Sep 2020 15:29:12 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 45
Connection: keep-alive
X-Powered-By: PHP/5.6.40

<p>Hi John!</p>
<p>You are 21 years old.</p>
~/secure_html/cs312/examples/php/action.php
<p>Hi <?php echo htmlspecialchars($_POST['name']); ?>!
</p>
<p>You are <?php echo (int)$_POST['age']; ?> years
old.</p>

CS 312 - Internet Concepts / Weigle 11


Embedded vs. All PHP
action.php
<p>Hi <?php echo htmlspecialchars($_POST['name']); ?>!</p>
<p>You are <?php echo (int) $_POST['age']; ?> years old.</p>

action2.php
<?php
echo "<p> Hi ";
echo These PHP scripts are
htmlspecialchars($_POST['name']); functionally equivalent.
echo "!</p>";
echo "<p>You are ";
echo (int)$_POST['age'];
echo " years old.</p>";
?> https://www.cs.odu.edu/~mweigle/cs312/examples/php/php-form2.html
CS 312 - Internet Concepts / Weigle 12
Process Summary
• PHP scripts are executed on the web server

• An HTTP request is sent in order to execute the script


– directly - user navigates to a .php URL
– indirectly - client-side code (such as JavaScript or HTML form)
issues an HTTP request

• The output of the script is returned in the HTTP response


– directly - PHP code is embedded in page and result is returned to
client (using .php URL)
– indirectly - using echo statements in PHP script
CS 312 - Internet Concepts / Weigle 13
<form action="action-get.php" method="get">

CGI-HTTP Process (HTML Form)


• Form submission triggers Client Server
HTTP GET request for action- HTTP GET request action- retrieve file
get.php?name=John&age=21
get.php execute PHP
• Form names and values are in code in file
the request line
form HTTP
• Server retrieves file response,
• Server executes the PHP script body is PHP
• Output of PHP code is the output
HTTP response body HTTP response send
• Result is sent to client 200 OK response to
<data> client
https://www.cs.odu.edu/~mweigle/cs312/examples/php/php-form-get.html
CS 312 - Internet Concepts / Weigle 14
John Smith

Using POST 21

action.php
<p>Hi <?php echo
htmlspecialchars
($_POST['name']); ?
>!</p>
<p>You are <?php echo
(int)
$_POST['age']; ?>
years old.</p>

CS 312 - Internet Concepts / Weigle 15


John Smith

Using GET 21

action-get.php
<p>Hi <?php echo
htmlspecialchars
($_GET['name']); ?
>!</p>
<p>You are <?php echo
(int) $_GET['age'];
?> years old.</p>

CS 312 - Internet Concepts / Weigle 16


Outline
• PHP and HTML Interaction
• PHP Basic Syntax
• PHP Conditionals, Loops, Functions
• User Registration Example

CS 312 - Internet Concepts / Weigle 17


Basic Syntax
• Comments
– one-line //
– multi-line /* … */

• All variables start with $


– data type does not need to be set before declaring variable
• $text = "Hello World";
• $num = 16;

CS 312 - Internet Concepts / Weigle 18


Strings in PHP
• Concatenation operator .

$txt1 = "Hello World";


$txt2 = "1234";
echo $txt1 . " " . $txt2;

Hello World 1234


http://www.w3schools.com/PHP/php_string.asp
CS 312 - Internet Concepts / Weigle 19
Useful String Functions
• strlen(String)
– returns the length of the string
– number of characters, including spaces

• strpos(String, SearchString)
– returns the starting position of SearchString if found inside
String
• position starts from 0 (i.e., 0 is the first character)
– returns FALSE if SearchString is not found in String
http://www.w3schools.com/PHP/php_string.asp
CS 312 - Internet Concepts / Weigle 20
PHP Numeric Arrays
• Creation
$names = array("Peter", "Quagmire", "Joe");
OR
$names[0] = "Peter"; Length of an array:
$names[1] = "Quagmire"; count (array)
$names[2] = "Joe";
• Usage count ($names)
3
$names[1] Quagmire
http://www.w3schools.com/PHP/php_arrays.asp
CS 312 - Internet Concepts / Weigle 21
PHP Associative Arrays
• Creation
$ages = array("Peter"=>"32", "Quagmire"=>"30",
"Joe"=>"34");
OR
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
• Usage
$ages['Peter'] 32
http://www.w3schools.com/PHP/php_arrays.asp
CS 312 - Internet Concepts / Weigle 22
Outline
• PHP and HTML Interaction
• PHP Basic Syntax
• PHP Conditionals, Loops, Functions
• User Registration Example

CS 312 - Internet Concepts / Weigle 23


PHP Conditionals
• Familiar C++/Java/Perl • Familiar C++/Java/Perl
operators conditionals syntax
– comparison: ==, !=, >, if (condition) {
>=, <, <= statements;
– assignment: =, +=, *=,
} elseif {

statements;
– logical: &&, ||, !
} else {
statements;
}
CS 312 - Internet Concepts / Weigle 24
PHP Loops
• Familiar C++/Java syntax • Includes foreach statement
while (condition) { foreach (array as item) {
statements;
statements;
}
}
do {
statements; $arr = array ("one",
} while (condition); "two");
foreach ($arr as $item) {
for (init; condition; echo $item . "<br />";
increment) {
}
statements;
}

CS 312 - Internet Concepts / Weigle 25


Displaying Browser Type
<html>, <head>, <body> tags removed in remaining examples to save space

• Let's check what browser the user is using


– look at the "User-Agent:" option that is sent in the HTTP request
header
– $_SERVER is a special reserved variable

<?php echo $_SERVER['HTTP_USER_AGENT'];


?>

http://www.cs.odu.edu/~mweigle/cs312/examples/php/browser.php (text version)


Ref: https://www.php.net/manual/en/reserved.variables.server.php
CS 312 - Internet Concepts / Weigle 26
Displaying Browser Type w/Conditionals
<?php
if (strpos ($_SERVER['HTTP_USER_AGENT'], 'Safari') !=
FALSE) {
echo "You are using Apple Safari.";
}
else {
echo "You aren't using Apple Safari, you're using
<br />" .
$_SERVER['HTTP_USER_AGENT'];
}
http://www.cs.odu.edu/~mweigle/cs312/examples/php/browser2.php (text version)
?>
Ref: https://www.php.net/manual/en/reserved.variables.server.php
CS 312 - Internet Concepts / Weigle 27
Mixing PHP and HTML
• Logical flow of the script remains intact even if broken up
with HTML statements.
<?php
if (strpos ($_SERVER['HTTP_USER_AGENT'], 'Safari') != FALSE) {
?>
<h3>strpos() returned non-false</h3>
<p>You are using Apple Safari</p>
<?php
} else {
?>
<h3>strpos() returned false</h3>
<p>You are not using Apple Safari, you're using</p>
<?php
echo $_SERVER['HTTP_USER_AGENT'];
}
https://www.cs.odu.edu/~mweigle/cs312/examples/php/html-php.php (text version)
?>
CS 312 - Internet Concepts / Weigle 28
PHP Functions
• There are over 700 built-in functions available
http://www.w3schools.com/PHP/default.asp

• Writing your own functions


– begin with the word function
function functionName ()
• syntax similar to JavaScript
{
statements;
http://www.w3schools.com/PHP/php_functions.asp
}
CS 312 - Internet Concepts / Weigle 29
PHP Functions
• Functions with parameters
function functionName (parameters) {
statements;
}
• Functions with return values
function functionName (parameters) {
statements;
return value;
}
CS 312 - Internet Concepts / Weigle 30
PHP Function Example
function add ($x, $y)
{
$total = $x + $y; output:
return $total; 1 + 16 = 17
}

echo "1 + 16 = " .


add(1,16);
CS 312 - Internet Concepts / Weigle 31
PHPInfo Example
• phpinfo() is a built-in function that displays useful
information about your system setup (loaded PHP
modules, predefined variables, configuration settings)

http://www.cs.odu.edu/~mweigle/cs312/examples/php/info.php (text version)


CS 312 - Internet Concepts / Weigle 32
Outline
• PHP and HTML Interaction
• PHP Basic Syntax
• PHP Conditionals, Loops, Functions
• User Registration Example

CS 312 - Internet Concepts / Weigle 33


Revisit echo.php
<?php
foreach ($_POST as $key => $item) {
if (!is_array($item)) {
echo htmlentities($key) . " => " . htmlentities($item) .
"</br>";
} else {
for ($i=0; $i < count($item); $i++) {
echo htmlentities($key) . "[" . $i . "] => " .
htmlentities($item[$i]) . "</br>";
}
}
echo("</p>");
}
?>
https://www.cs.odu.edu/~mweigle/cs312/examples/forms/form.html
https://www.cs.odu.edu/~mweigle/cs312/examples/forms/echo.php.txt
CS 312 - Internet Concepts / Weigle 34
User Registration Example
• HTML code to take registration
data from user and submit to
PHP script

• PHP script to process the


registration
– get the form data
– validate the registration data
– if valid, save the registration data
to a text file
CS 312 - Internet Concepts / Weigle 35
User Registration Form
1. Present the HTML form to the user register.html

2. Handle form submission


<form method="POST" action="register_action.php">
register_action.php
<p><label>Name: <input type="text" size="30"
name="name"/> </label></p>

<p><label>Email: <input type="email" size="50"


name="email"/> </label></p>

<p><label>Zip Code: <input type="text" pattern="[0-9]


{5}" title="A 5-digit code" name="zip"/> </label></p>

<p><input type="Submit" name="action"


value="Send"/></p>
</form>

CS 312 - Internet Concepts / Weigle 36


PHP Form Handler
1. Present the HTML form to the user register.html

2. Handle form submission


• getregister_action.php
the form data <?php
// setup
• validate the $messages = array();
registration data $error = FALSE;
• if valid, save the
// get the parameters
registration data to a $name = $_POST['name'];
text file $email = $_POST['email'];
• set up and return $zip = $_POST['zip'];
response
CS 312 - Internet Concepts / Weigle 37
PHP Form Handler
1. Present the HTML form to the user register.html

2. Handle form submission// validate the name field


• getregister_action.php
the form data if (empty($name) ||
• validate the !preg_match('/^[a-zA-Z0-9 ]{2,}$/',
$name))
registration data {
• if valid, save the $error = TRUE;
registration data to a $messages[] = "The name field is
required, and can contain only letters,
text file numbers, and$array_var[]
spaces."; = syntax adds string to end of
• set up and return } array (like array_push())
response
Ref: https://www.w3schools.com/php/func_regex_preg_match.asp
CS 312 - Internet Concepts / Weigle 38
RegEx
/^[a-zA-Z0-9 ]
• {2,}$/
/ … / - delimiters for the pattern
• ^ - indicates match should start at beginning of string
• [a-zA-Z0-9 ] - alphanumeric and space
• {2,} - at least 2 of the previous pattern (at least 2
alphanumeric or space characters)
• $ - indicates match should be at end of string

Ref: https://www.w3schools.com/php/php_ref_regex.asp
CS 312 - Internet Concepts / Weigle 39
PHP Form Handler
1. Present the HTML form to the user register.html

2. Handle form submission


• getregister_action.php
the form data // validate the email addr
• validate the if (empty($email) ||
!preg_match('/^.+@.+$/', $email))
registration data {
• if valid, save the $error = TRUE;
registration data to a $messages[] = "A valid email
address is required.";
text file }
• set up and return
response
CS 312 - Internet Concepts / Weigle 40
PHP Form Handler
1. Present the HTML form to the user register.html

2. Handle form submission


• getregister_action.php
the form data // validate the zip code
• validate the if (empty($zip) || strlen($zip) != 5 ||
! is_numeric($zip))
registration data {
• if valid, save the $error = TRUE;
registration data to a $messages[] = "A five digit zip
code is required.";
text file }
• set up and return
response
CS 312 - Internet Concepts / Weigle 41
PHP Form Handler
1. Present the HTML form to the user register.html

2. Handle form submission


// save the registration if the input is valid
• getregister_action.php
the form data if (!$error) {
• validate the // write data to the register.txt file
registration data $regfile = fopen("registration.txt", "a")
or
• if valid, save the die("Unable to open file!");
registration data to a $txt = str_replace("|", "-", $name) .
text file "|"
• . str_replace("|", "-", $email)
set up and return . "|"
response . str_replace("|", "-", $zip) .
"\n";
CS 312 - Internet Concepts / Weigle 42
PHP Form Handler
1. Present the HTML form to the user register.html

2. Handle form submission


• getregister_action.php
the form data // add a welcome message if the parameters are
• validate the valid
if(!$error) {
registration data $messages[] = "Welcome, " . $name . "!";
• if valid, save the $messages[] = '<a
registration data to a href="registration.txt">Registration
}
File</a>';

text file
• set up and return
response
CS 312 - Internet Concepts / Weigle 43
PHP Form Handler
1. Present the HTML form to the user register.html

2. Handle form submission


• getregister_action.php
the form data ?>
• validate the <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
registration data lang="en">
• if valid, save the <head>
registration data to a <title>Registration Result</title>
<meta charset="UTF-8" />
text file </head>
• set up and return <body>
response <h2>Registration Result</h2>

CS 312 - Internet Concepts / Weigle 44


PHP Form Handler
1. Present the HTML form to the user register.html

2. Handle form submission


• getregister_action.php
the form data <p>
• validate the <?php
// echo the collected messages
registration data foreach ($messages as $message)
• if valid, save the {
registration data to a echo "<p>", $message,
"</p>";
text file }
• set up and return ?>
response </p>
</body>
CS 312 - Internet Concepts / Weigle
</html> 45
Full Example
https://www.cs.odu.edu/~mweigle/cs312/examples/php/register.html
https://www.cs.odu.edu/~mweigle/cs312/examples/php/register_action.php.txt
Permissions Notes:
https://www.cs.odu.edu/~mweigle/cs312/examples/php/registration.txt ● directory with register_action.php must
be executable by web server
● register_action.php must be executable
by web server
● before testing, create registration.txt with
touch registration.txt so you
will be the owner
● directory with registration.txt must be
writable by web server
To meet these requirements, chgrp http
and chmod 770 on everything in the directory
where these files live

CS 312 - Internet Concepts / Weigle 46


Loading PHP into HTML from a file
• Can include same PHP, HTML, or text on multiple
pages of a website
• <?php include 'filename.php'; ?>
– if filename.php doesn't exist, script will continue to
execute
• <?php require 'filename.php'; ?>
– if filename.php doesn't exist, script execution will end
https://www.w3schools.com/php/php_includes.asp
CS 312 - Internet Concepts / Weigle 47

You might also like