Server-Side Dynamic Web Programming• CGI is one of the most common approaches to server-side programming Universal support: almost Every server supports CGI programming.. • Other serv
Trang 1Learning PHP/MySQL
Introduction
Trang 2• Not to teach everything about PHP, but provide the basic knowledge
• Explain code of examples
• Provide some useful references
Trang 3PHP Basics:
Introduction to PHP
• a PHP file, PHP workings, running PHP.
Basic PHP syntax
• variables, operators, if else and switch, while, do while, and for.
Some useful PHP functions
How to work with
• HTML forms, cookies, files, time and date.
How to create a basic checker for user-entered data
Trang 4Server-Side Dynamic Web Programming
• CGI is one of the most common approaches to server-side
programming
Universal support: (almost) Every server supports CGI programming A great deal
of ready-to-use CGI code Most APIs (Application Programming Interfaces) also allow CGI programming.
Choice of languages: CGI is extremely general, so that programs may be written
in nearly any language Perl is by far the most popular, with the result that many people think that CGI means Perl But C, C++, Ruby, and Python are also used for CGI programming
Drawbacks: A separate process is run every time the script is requested A
distinction is made between HTML pages and code.
Trang 5• Other server-side alternatives try to avoid the drawbacks
Server-Side Includes (SSI): Code is embedded in HTML pages, and evaluated
on the server while the pages are being served Add dynamically generated
content to an existing HTML page, without having to serve the entire page via a CGI program.
Active Server Pages (ASP, Microsoft) : The ASP engine is integrated into the web server so it does not require an additional process It allows programmers to mix code within HTML pages instead of writing separate programs ( Drawback (?) Must be run on a server using Microsoft server software.)
Java Servlets (Sun): As CGI scripts, they are code that creates documents
These must be compiled as classes which are dynamically loaded by the web server when they are run.
Java Server Pages (JSP): Like ASP, another technology that allows developers
to embed Java in web pages.
Trang 6• developed in 1995 by Rasmus Lerdorf (member of the Apache Group)
originally designed as a tool for tracking visitors at Lerdorf's Web site
within 2 years, widely used in conjunction with the Apache server
developed into full-featured, scripting language for server-side programming
free, open-source
server plug-ins exist for various servers
now fully integrated to work with mySQL databases
• PHP is similar to JavaScript, only it’s a server-side language
PHP code is embedded in HTML using tags
when a page request arrives, the server recognizes PHP content via the file extension (.php or phtml)
the server executes the PHP code, substitutes output into the HTML page
the resulting page is then downloaded to the client
user never sees the PHP code, only the output in the page
Trang 7What do You Need?
• Our server supports PHP
• You don't need to do anything special! *
• You don't need to compile anything or install any extra tools!
• Create some php files in your web directory - and the server will parse them for you
* Slightly different rules apply when dealing with an SQL database (as will be explained when we get to that point)
Trang 8• Most servers support PHP
• Download PHP for free here: http://www.php.net/downloads.php
• Download MySQL for free here: http://www.mysql.com/downloads/index.html
• Download Apache for free here: http://httpd.apache.org/download.cgi
(Note: All of this is already present on the CS servers, so you need not do any installation yourself to utilize PHP on our machines.)
Trang 9What is PHP?
• PHP == ‘Hypertext Preprocessor’
• Open-source, server-side scripting language
• Used to generate dynamic web-pages
• PHP scripts reside between reserved PHP tags
• This allows the programmer to embed PHP scripts within HTML pages
• The acronym PHP means (in a slightly recursive definition)
PHP: Hypertext Preprocessor
Trang 10What is PHP (cont’d)
• Interpreted language, scripts are parsed at run-time rather
than compiled beforehand
• Executed on the server-side
• Source-code not visible by client
• ‘View Source’ in browsers does not display the PHP code
• Various built-in functions allow for fast development
• Compatible with many popular databases
Trang 11What does PHP code look
like? • Structurally similar to C/C++
• Supports procedural and object-oriented paradigm (to
some degree)
• All PHP statements end with a semi-colon
• Each PHP script must be enclosed in the reserved PHP tag
<?php …
?>
Trang 12Comments in PHP
• Standard C, C++, and shell comment symbols
// C++ and Java-style comment
# Shell-style comments
/* C-style comments
These can span multiple lines */
Trang 13Variables in PHP
• PHP variables must begin with a “$” sign
• Case-sensitive ($Foo != $foo != $fOo)
• Global and locally-scoped variables
• Global variables can be used anywhere
• Local variables restricted to a function or class
• Certain variable names reserved by PHP
• Form variables ($_POST, $_GET)
• Server variables ($_SERVER)
• Etc.
Trang 14Constants
A constant is an identifier (name) for a simple value A constant is case-sensitive by
default By convention, constant identifiers are always uppercase.
<?php
// Valid constant names
define("FOO", "something");
define("FOO2", "something else");
define("FOO_BAR", "something more");
// Invalid constant names (they shouldn’t start
// with a number!)
define("2FOO", "something");
// This is valid, but should be avoided:
// PHP may one day provide a “magical” constant
// that will break your script
Trang 15• Arithmetic Operators: +, -, *,/ , %, ++,
• Assignment Operators: =, +=, -=, *=, /=, %=
• Comparison Operators: ==, !=, >, <, >=, <=
• Logical Operators: &&, ||, !
• String Operators: and .= (for string concatenation)
Example Is the same as
x+=y x=x+yx-=y x=x-yx*=y x=x*yx/=y x=x/yx%=y x=x%y
$a = "Hello ";
$b = $a "World!"; // now $b contains "Hello World!"
$a = "Hello ";
$a = "World!";
Trang 16Variable usage
<?php
$foo = ($foo * 7); // Multiplies foo by 7
$bar = ($bar * 7); // Invalid expression
?>
Trang 17<p>This is going to be ignored by the PHP interpreter.</p>
<?php echo ‘<p>While this is going to be parsed.</p>‘; ?>
<p>This will also be ignored by the PHP preprocessor.</p>
<?php print( ‘<p> Hello and welcome to <i>my</i> page!</p> ' ) ;
The server executes the print and echo statements, substitutes output.
print and echo for output
Trang 18All variables in PHP start with a $ sign symbol A variable's type is determined by the
context in which that variable is used (i.e there is no strong-typing in PHP).
spanning multiple lines
using “heredoc” syntax.
floating point numbers
string
single quoted double quoted
Trang 19• void echo (string arg1 [, string argn ])
• In practice, arguments are not passed in parentheses since
echo is a language construct rather than an actual function
Trang 20Echo example
• Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it with 25
• Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP
• This is true for both variables and character escape-sequences (such as “\n” or “\\”)
<?php
echo “5x5=”,$foo; // Outputs 5x5=25
echo ‘5x5=$foo’; // Outputs 5x5=$foo
?>
Trang 21?>
Trang 23Escaping the Character
• If the string has a set of double quotation marks that must remain visible, use the \ [backslash] before the quotation marks to ignore and display them.
Trang 24PHP Control Structures
Control Structures: Are the structures within a language that
allow us to control the flow of execution through a program or
script.
repetition structures (e.g while loops).
Example if/else if/else statement:
if ($foo == 0) {
echo ‘The variable foo is equal to 0’;
} else if (($foo > 0) && ($foo <= 5)) {
echo ‘The variable foo is between 1 and 5’;
} else {
echo ‘The variable foo is equal to ‘.$foo;
}
Trang 25Print “Hello John.”;
} Else {
Print “You are not John.”; }
?>
No THEN in PHP
Trang 26is true ; else code to be executed if condition
is false ;
date() is a built-in PHP function that can be called with many different parameters to return the date (and/or local time) in various formats
In this case we get a three letter string for the day of the week
Trang 27Print “hello PHP ”;
$count += 1;
// $count = $count + 1; // or
// $count++;
?>
hello PHP hello PHP hello PHP.
Trang 28Looping: for and foreach
Can loop depending on a "counter"
loops through a block of code a
specified number of times
Trang 29Conditionals: switchCan select one of many sets of lines to execute
expression = label1;
break;
case label2: code to be executed if
}
Trang 30Date Display
$datedisplay=date(“yyyy/m/d”); Print $datedisplay;
# If the date is June 25th, 2012
# It would display as 2012/25/6 2012/25/6
$datedisplay=date(“l, F m, Y”); Print $datedisplay;
# If the date is June 25th ,2012
# Monday, June 25th,2012
Monday, June 25, 2012
Trang 31An array in PHP is actually an ordered map A map is a type that maps values to keys.
array() = creates arrays
<?php
$arr = array("foo" => "bar", 12 => true);
echo $arr["foo"]; // bar
echo $arr[12]; // 1
?>
key = either an integer or a string
value = any PHP type.
if an existing key , its value will be overwritten.
$arr[] = 56; // the same as $arr[13] = 56;
$arr["x"] = 42; // adds a new element
unset($arr[5]); // removes the element
unset($arr); // deletes the whole array
$a = array(1 => 'one', 2 => 'two', 3 => 'three');
*Find more on arrays
array_values() makes reindexing effect (indexing numerically)
Trang 32Month, Day & Date Format Symbols
Day of Week l Monday
Day of Week D Mon
Trang 33• Functions MUST be defined before then can be called
• Function headers are of the format
• Note that no return type is specified
• Unlike variables, function names are not case sensitive
(foo(…) == Foo(…) == FoO(…))
function functionName($arg_1, $arg_2, …, $arg_n)
Trang 35User Defined Functions
Can define a function using syntax such as the following:
return array (0, 1, 2);
} list ($zero, $one, $two) = small_numbers();
echo $zero, $one, $two;
Trang 36<?phpfunction Test(){
static $a = 0;
echo $a;
$a++;
}Test1();
Test1();
Test1();
?>
static does not lose its value.
Trang 37global $color;
include ('vars.php‘);
echo "A $color $fruit";
}
/* vars.php is in the scope of foo() so *
* $fruit is NOT available outside of this *
* scope $color is because we declared it *
* as global */
foo(); // A green apple
echo "A $color $fruit"; // A green
?>
Trang 38The file footer.php might look like:
<hr SIZE=11 NOSHADE WIDTH=“100%”>
<i>Copyright © 2001-2012 gsu</i></font><br>
<i>ALL RIGHTS RESERVED</i></font><br>
<i>URL: http://www.gsu.edu.edu</i></font><br>
Trang 39PHP - Forms
• Access to the HTTP POST and GET data is simple in PHP
• The global variables $_POST[] and $_GET[] contain the
<form action="form.php" method="post">
<input type="submit" name="submit" value="Submit">
<input type="submit" name="cancel" value="Cancel">
</form>
Trang 40WHY PHP – Sessions ?
Whenever you want to create a website that allows you to store and display information about a user, determine which user groups a person belongs to, utilize permissions on your website or you just want to do something cool on your site, PHP's Sessions are vital to each of these features
Cookies are about 30% unreliable right now and it's getting worse every day More and more web browsers are starting to come with security and privacy settings and people browsing the net these days are starting to frown upon Cookies because they store information on their local computer that they do not want stored there.
PHP has a great set of functions that can achieve the same results of Cookies and more without storing information on the user's computer PHP Sessions store the information on the web server in a location that you chose in
special files These files are connected to the user's web browser via the
server and a special ID called a "Session ID" This is nearly 99% flawless in operation and it is virtually invisible to the user.
Trang 41PHP - Sessions
• Sessions store their identifier in a cookie in the client’s browser
• Every page that uses session data must be proceeded by the
Trang 42Avoid Error PHP - Sessions
Trang 43Destroy PHP - Sessions
Destroying a Session
why it is necessary to destroy a session when the session will get
destroyed when the user closes their browser Well, imagine that you had
a session registered called "access_granted" and you were using that to determine if the user was logged into your site based upon a username and password Anytime you have a login feature, to make the users feel better, you should have a logout feature as well That's where this cool function called session_destroy() comes in handy session_destroy() will completely demolish your session (no, the computer won't blow up or self destruct) but it just deletes the session files and clears any trace of that session.
NOTE: If you are using the $_SESSION superglobal array, you must clear the array values first, then run session_destroy.
Here's how we use session_destroy():
Trang 44}
?>
Trang 45PHP Overview
• Easy learning
• Syntax Perl- and C-like syntax Relatively easy to learn.
• Large function library
• Embedded directly into HTML
• Interpreted, no need to compile
• Open Source server-side scripting language designed specifically for the web.
Trang 46PHP Overview (cont.)
• Conceived in 1994, now used on +10 million web sites.
• Outputs not only HTML but can output XML, images (JPG & PNG), PDF files and even Flash movies all
generated on the fly Can write these files to the file system.
• Supports a wide-range of databases (20+ODBC).
• PHP also has support for talking to other services
using protocols such as LDAP, IMAP, SNMP, NNTP,
POP3, HTTP.
Trang 48Example of parameter reading
value='cranberries'> cranberries <li>
<input type='checkbox' name='foo[]' value='plums'> plums </ul> <input
type='submit'> </form> end of
Trang 49Example – show data in the
Trang 51echo "<h1>Choose one table:<h1>";
echo "<form action=\"showtable.php\" method=\"POST\">";
echo "<select name=\"table\" size=\"1\" Font size=\"+2\">";
for($i=0; $i<$num_row; $i++) {
Trang 52die("Can't select database");
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) die("Query to show fields from table failed!" mysql_error());
Trang 53showtable.php (cont.)
$fields_num = mysql_num_fields($result);
echo "<h1>Table: {$table}</h1>";
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++) {
// $row is array foreach( ) puts every element
// of $row to $cell variable