Upload
barry-clyde-casey
View
251
Download
0
Tags:
Embed Size (px)
Citation preview
IntroductionIntroduction PHP is a powerful server-side scripting PHP is a powerful server-side scripting
language for creating dynamic and language for creating dynamic and interactive websites.interactive websites.
PHP is the widely-used, free, and efficient PHP is the widely-used, free, and efficient alternative to competitors such as alternative to competitors such as Microsoft's ASP.Microsoft's ASP.
PHP is perfectly suited for Web PHP is perfectly suited for Web development and can be embedded directly development and can be embedded directly into the HTML code.into the HTML code.
The PHP syntax is very similar to Perl and C. The PHP syntax is very similar to Perl and C. PHP is often used together with Apache PHP is often used together with Apache
(web server) on various operating systems. (web server) on various operating systems. It also supports ISAPI and can be used with It also supports ISAPI and can be used with
Microsoft's IIS on Windows.Microsoft's IIS on Windows.
What is PHP?What is PHP?
PHP stands for PHP stands for PPHP: HP: HHypertext ypertext PPreprocessor reprocessor PHP is a server-side scripting language, like PHP is a server-side scripting language, like
ASP ASP PHP scripts are executed on the server even PHP scripts are executed on the server even
though even though combined with an HTML though even though combined with an HTML codecode
PHP supports many databases (MySQL, PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) Generic ODBC, etc.)
PHP is an open source software (OSS) PHP is an open source software (OSS) PHP is free to download and usePHP is free to download and use
What is a PHP File?What is a PHP File?
PHP files may contain text, HTML PHP files may contain text, HTML tags and scripts tags and scripts
PHP files are returned to the PHP files are returned to the browser as plain HTML browser as plain HTML
PHP files have a file extension of PHP files have a file extension of ".php", ".php3", or ".phtml" ".php", ".php3", or ".phtml"
What is MySQL?What is MySQL?
MySQL is a database server MySQL is a database server MySQL is ideal for both small and MySQL is ideal for both small and
large applications large applications MySQL supports standard SQL MySQL supports standard SQL MySQL compiles on a number of MySQL compiles on a number of
platforms platforms MySQL is free to download and useMySQL is free to download and use
PHP + MySQLPHP + MySQL
PHP combined with MySQL are PHP combined with MySQL are cross-platform (means that you can cross-platform (means that you can develop in Windows and serve on a develop in Windows and serve on a Unix platform) Unix platform)
Why PHP?Why PHP?
PHP runs on different platforms PHP runs on different platforms (Windows, Linux, Unix, etc.) (Windows, Linux, Unix, etc.)
PHP is compatible with almost all PHP is compatible with almost all servers used today (Apache, IIS, etc.) servers used today (Apache, IIS, etc.)
PHP is FREE to download from the PHP is FREE to download from the official PHP resource: official PHP resource: www.php.net
PHP is easy to learn and runs PHP is easy to learn and runs efficiently on the server sideefficiently on the server side
Where to Start?Where to Start? Install an Apache server on a Windows or Linux Install an Apache server on a Windows or Linux
machine machine Install PHP on a Windows or Linux machine Install PHP on a Windows or Linux machine Install MySQL on a Windows or Linux machine Install MySQL on a Windows or Linux machine Install PHP triadInstall PHP triad
All in oneAll in one LAMPLAMP
LLinux inux AApache pache MMySQL ySQL PPHPHP WAMP (Apache, PHP, MySQL)WAMP (Apache, PHP, MySQL)
http://www.wampserver.com/en/ XAMPP (XAMPP (MySQL, PHP and Perl)MySQL, PHP and Perl)
http://www.apachefriends.org/en/xampp.html
First Example – Hello First Example – Hello World!World!
Activity 01Activity 01 NOTESNOTES
You cannot view the PHP source code You cannot view the PHP source code by selecting "View source" in the by selecting "View source" in the browser browser
you will only see the output from the you will only see the output from the PHP file, which is plain HTML. PHP file, which is plain HTML.
This is because the scripts are executed This is because the scripts are executed on the server before the result is sent on the server before the result is sent back to the browser. back to the browser.
PHP SyntaxPHP Syntax
A PHP scripting block always starts with A PHP scripting block always starts with <?php<?php and ends with and ends with ?>?>. .
A PHP scripting block can be placed A PHP scripting block can be placed anywhere in the HTML document.anywhere in the HTML document.
On servers with shorthand support enabled On servers with shorthand support enabled you can start a scripting block with <? and you can start a scripting block with <? and end with ?>.end with ?>.
However, for maximum compatibility, it is However, for maximum compatibility, it is recommend that you use the standard form recommend that you use the standard form (<?php) rather than the shorthand form.(<?php) rather than the shorthand form.
PHP SyntaxPHP Syntax A PHP file normally contains HTML tags, just like A PHP file normally contains HTML tags, just like
an HTML file, and some PHP scripting code. an HTML file, and some PHP scripting code. View source for View source for activity 01activity 01 Each code line in PHP must end with a Each code line in PHP must end with a
semicolon. semicolon. The semicolon is a separator and is used to The semicolon is a separator and is used to
distinguish one set of instructions from another.distinguish one set of instructions from another. There are two basic statements to output text There are two basic statements to output text
with PHP: with PHP: echoecho and and printprint. . In activity 01, we have used the echo statement In activity 01, we have used the echo statement
to output the text "Hello World".to output the text "Hello World".
PHP SyntaxPHP Syntax
Comments in PHPComments in PHP In PHP, we use // to make a single-line In PHP, we use // to make a single-line
comment or comment or /* and */ to make a large comment /* and */ to make a large comment
block. block.
PHP VariablesPHP Variables
All variables in PHP start with a $ sign All variables in PHP start with a $ sign symbol. symbol.
Variables may contain strings, numbers, Variables may contain strings, numbers, or arrays (untype).or arrays (untype).
Activity 02Activity 02 Variable concatenation – using the (.) Variable concatenation – using the (.)
operatoroperator All converted to stringAll converted to string
Str . Str = strStr . Str = str Num . Num = strNum . Num = str
Variable Naming RulesVariable Naming Rules
Same as C, C++ or JavaSame as C, C++ or Java A variable name must start with a letter or an A variable name must start with a letter or an
underscore "_" underscore "_" A variable name can only contain alpha-A variable name can only contain alpha-
numeric characters and underscores (a-Z, 0-9, numeric characters and underscores (a-Z, 0-9, and _ ) and _ )
A variable name should not contain spaces. A variable name should not contain spaces. If a variable name should be more than one If a variable name should be more than one
word, it should be separated with underscore word, it should be separated with underscore ($my_string), ($my_string),
or with capitalization ($myString) or with capitalization ($myString)
PHP operator, PHP operator, conditionalconditional
Same as C or C++Same as C or C++ PHP If...Else Statements – PHP If...Else Statements –
Activity 03Activity 03 Same as C or C++Same as C or C++
Swith statementSwith statement Same as C or C++Same as C or C++
PHP array (Numeric)PHP array (Numeric)
Numeric Arrays (Numeric Arrays (Activity 04Activity 04)) $names = $names =
array("Peter","Quagmire","Joe"); array("Peter","Quagmire","Joe"); Assign manualy:Assign manualy:
$names[0] = "Peter"; $names[0] = "Peter"; $names[1] = "Quagmire"; $names[1] = "Quagmire"; $names[2] = "Joe"; $names[2] = "Joe";
PHP array (Associative)PHP array (Associative)
Using Hash technique Using Hash technique ((Activity 04Activity 04)) An associative array where each ID key An associative array where each ID key
is associated with a value.is associated with a value. When storing data about specific When storing data about specific
named values, a numerical array is not named values, a numerical array is not always the best way to do it. always the best way to do it.
With associative arrays we can use the With associative arrays we can use the values as keys and assign values to values as keys and assign values to them.them.
PHP array (Associative)PHP array (Associative)
$ages = array("Peter"=>32, "Quagmire"=>30, $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);"Joe"=>34);
oror $ages['Peter'] = "32"; $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34"; $ages['Joe'] = "34";
Tutorial 01Tutorial 01
Download tutorial01.phpDownload tutorial01.php Produce out such as the following:Produce out such as the following:
Father’s name: QuagmireFather’s name: Quagmire Children’s name: GlennChildren’s name: Glenn
You need to upload your You need to upload your tutorial01.php to the server to view tutorial01.php to the server to view the result!the result!
PHP Looping – PHP Looping – Activity Activity 0505
Same as C or C++Same as C or C++ while while - loops through a block of code if - loops through a block of code if
and as long as a specified condition is true and as long as a specified condition is true do...whiledo...while - loops through a block of code - loops through a block of code
once, and then repeats the loop as long as once, and then repeats the loop as long as a special condition is true a special condition is true
for for - loops through a block of code a - loops through a block of code a specified number of times specified number of times
foreach foreach - loops through a block of code - loops through a block of code for each element in an array for each element in an array
PHP – Data transferPHP – Data transfer
Transferring data between client Transferring data between client (web browser) to the server-side(web browser) to the server-side
Two method:Two method: Using form: POST methodUsing form: POST method Through URL: GET methodThrough URL: GET method
POST MethodPOST Method
The body of the message is sent as a The body of the message is sent as a stream of data (HTML form data)stream of data (HTML form data)
Separated with the PHP URL in the Separated with the PHP URL in the FORM post URLFORM post URL
Client send data to servlet using Client send data to servlet using HTML form elementHTML form element
POST MethodPOST Method Form tagForm tag
<FORM METHOD=”post” <FORM METHOD=”post” ACTION=”login.php”ACTION=”login.php”
TARGET=“”>TARGET=“”> Fill the Fill the TARGETTARGET value if form result have to value if form result have to
display in a different framedisplay in a different frame After coding all the form element (button, After coding all the form element (button,
textfield, etc) FORM tag must be close textfield, etc) FORM tag must be close using the equivalent end tag - using the equivalent end tag - </FORM></FORM>
If you have multiple form in a single page If you have multiple form in a single page every separate every form using the end every separate every form using the end tagtag
GET methodGET method The body of the message (the data) is appended to The body of the message (the data) is appended to
the PHP URL,the PHP URL, http://myserver.com/hello.phphttp://myserver.com/hello.php
Separated by a question mark Separated by a question mark http://myserver.com/hello.php?http://myserver.com/hello.php?
Followed by name-value pair which separated by Followed by name-value pair which separated by equals signequals sign
If value consist of more than one word, separate it If value consist of more than one word, separate it using plus sign which the php will convert it to space using plus sign which the php will convert it to space character after parsing character after parsing name=john+doename=john+doe
Every consecutive name-value pair will be separated Every consecutive name-value pair will be separated using ampersand sign using ampersand sign (&)(&) name=john+doe&id=007name=john+doe&id=007
PHP FunctionPHP Function
Also similar to C, C++ and JavaAlso similar to C, C++ and Java Normal – 8-1Normal – 8-1 With parameter – 8-2With parameter – 8-2 Return value – 8-3Return value – 8-3
PHP MySQL – PHP MySQL – mysql_query()mysql_query()•mysql_query ( string $query [, resource
$link_identifier] )•$query
•A SQL query•The query string should not end with a semicolon.
•$link_identifier•DB connection•If is not specified, the last link opened by mysql_connect() is assumed otherwise DB error
PHP MySQL – SELECTPHP MySQL – SELECT The example above stores the data
returned by the mysql_query() function in the $result variable.
Next, we use the mysql_fetch_array() function to return the first row from the recordset as an array.
Each subsequent call to mysql_fetch_array() returns the next row in the recordset.
The while loop loops through all the records in the recordset.
To print the value of each row, we use the PHP $row variable ($row['FirstName'] and $row['LastName']).
PHP SessionPHP Session A PHP session allow us to store user A PHP session allow us to store user
information on the server for later use information on the server for later use (i.e. username, shopping items, etc). (i.e. username, shopping items, etc).
However, session information is However, session information is temporary and will be deleted after the temporary and will be deleted after the user has left the website. user has left the website.
If you need a permanent storage you may If you need a permanent storage you may want to store the data in a database.want to store the data in a database.
Sessions work by creating a unique id Sessions work by creating a unique id (UID) for each visitor and store variables (UID) for each visitor and store variables based on this UID. based on this UID.
The UID is either stored in a cookie or is The UID is either stored in a cookie or is propagated in the URL.propagated in the URL.
PHP CookiesPHP Cookies
A cookies allow us to store user A cookies allow us to store user information permanently on the information permanently on the user’s machine (client) for later user’s machine (client) for later use (i.e. username & password, use (i.e. username & password, last visit etc). last visit etc).
arguments are arguments are setcookie(name, setcookie(name, value, expiration)value, expiration)::
PHP CookiesPHP Cookies
A cookies allow us to store user A cookies allow us to store user information permanently on the information permanently on the user’s machine (client) for later user’s machine (client) for later use (i.e. username & password, use (i.e. username & password, last visit etc). last visit etc).
arguments are arguments are setcookie(name, setcookie(name, value, expiration)value, expiration)::
PHP CookiesPHP Cookies namename: The name of your cookie. You will : The name of your cookie. You will
use this name to later retrieve your use this name to later retrieve your cookie, so don't forget it! cookie, so don't forget it!
valuevalue: The value that is stored in your : The value that is stored in your cookie. Common values are cookie. Common values are username(string) and last visit(date). username(string) and last visit(date).
expirationexpiration: The date when the cookie will : The date when the cookie will expire and be deleted. If you do not set expire and be deleted. If you do not set this expiration date, then it will be this expiration date, then it will be treated as a session cookie and be treated as a session cookie and be removed when the browser is restarted. removed when the browser is restarted.
setcookie("user", “kim bo-ra", time()setcookie("user", “kim bo-ra", time()+3600);+3600);
Expire in 1 hourExpire in 1 hour
PHP CookiesPHP Cookies
Last visit:Last visit: //Calculate 60 days in the future //Calculate 60 days in the future //seconds * minutes * hours * days + current //seconds * minutes * hours * days + current
timetime $inTwoMonths = 60 * 60 * 24 * 60 + time();$inTwoMonths = 60 * 60 * 24 * 60 + time(); setcookie(lastVisit, date("G:i - m/d/y“, setcookie(lastVisit, date("G:i - m/d/y“,
$inTwoMonths)$inTwoMonths) Deleting cookies:Deleting cookies:
When deleting a cookie you should assure that When deleting a cookie you should assure that the expiration date is in the past.the expiration date is in the past.
setcookie("user", "", time()-3600);setcookie("user", "", time()-3600);
PHP SessionPHP Session Starting session: Starting session:
session_start();session_start(); No session exist – new session variable created, No session exist – new session variable created, otherwise, current session variable is retrieveotherwise, current session variable is retrieve
Storing data in session ($_SESSION)Storing data in session ($_SESSION) $_SESSION['views']=1; $_SESSION['views']=1;
Retrieving and checkingRetrieving and checking echo "Pageviews=". $_SESSION['views']; echo "Pageviews=". $_SESSION['views']; isset($_SESSION['user']) – checking if variable user isset($_SESSION['user']) – checking if variable user
exist in $_SESSIONexist in $_SESSION Destroying session data and sessionDestroying session data and session
Session data: unset($_SESSION['views']); Session data: unset($_SESSION['views']); session_destroy(); session_destroy();
Authenticating, Access Control & Authenticating, Access Control & Profile ManagementProfile Management
Using FORM authenticationUsing FORM authentication Supplying login and password through HTML Form to Supplying login and password through HTML Form to
log to the restricted applicationlog to the restricted application Data send to php script using SSL protocol – prevent Data send to php script using SSL protocol – prevent
from snifferfrom sniffer PHP for login-password processing and PHP PHP for login-password processing and PHP
redirecting redirecting Authenticating user login and password from the Authenticating user login and password from the
databasedatabase Creating user sessionCreating user session Creating user profile using User Object and store in Creating user profile using User Object and store in
the user newly created sessionthe user newly created session Direct user to the session protected PHP pagesDirect user to the session protected PHP pages
Authenticating, Access Control & Authenticating, Access Control & Profile ManagementProfile Management
PHP pages (view)PHP pages (view) Control user access to protected resources Control user access to protected resources
using user sessionusing user session Every PHP pages which involve in the Every PHP pages which involve in the
restricted application should also have a restricted application should also have a section for session authenticationsection for session authentication