Bài giảng Web technologies and e-Services - Bài 5, Phần 1: PHP - Trường Đại học Bách khoa Hà Nội
PHP
1
Content
PHP 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
2
Introduction to PHP
• Server-side programming tries to avoid the drawbacks
▪ 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.
• 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.
3
Introduction to PHP
• 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
▪ free, open-source
▪ 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
• The acronym PHP means (in a slightly recursive definition)
▪ PHP: Hypertext Preprocessor
4
Basic PHP syntax
<html>
<!-- hello.php CS443 -->
<head><title>Hello World</title></head>
<body>
A PHP scripting block always starts with <?php
and ends with ?>. A PHP scripting block can be
placed (almost) anywhere in an HTML document.
<p>This is going to be ignored by the PHP interpreter.</p>
<?php echo '<p>While this is going to be parsed.</p>';
?>
print and echo
for output
<p>This will also be ignored by the PHP preprocessor.</p>
<?php print('<p>Hello and welcome to <i>my</i>
page!</p>');
?>
<?php
//This is a comment
/*
This is
a comment
block
*/
a semicolon (;)
at the end of each
statement
// for a single-line comment
?>
/* and */ for a large
comment block.
</body>
</html>
view the output page
The server executes the print and echo statements, substitutes output.
Scalars
<html><head></head>
<!-- scalars.php CS443 -->
<body> <p>
<?php
$foo = true; if ($foo) echo "It is TRUE! <br /> \n";
$txt='1234'; echo "$txt <br /> \n";
$a = 1234; echo "$a <br /> \n";
$a = -123;
echo "$a <br /> \n";
$a = 1.234;
echo "$a <br /> \n";
$a = 1.2e3;
echo "$a <br /> \n";
All 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).
$a = 7E-10;
echo "$a <br /> \n";
echo 'Arnold once said: "I\'ll be back"', "<br /> \n";
$beer = 'Heineken';
echo "$beer's taste is great <br /> \n";
$str = <<<EOD
Example of string
spanning multiple lines
using “heredoc” syntax.
EOD;
Four scalar types:
boolean
true or false
integer,
float,
echo $str;
?>
floating point numbers
string
</p>
</body>
</html>
single quoted
double quoted
view the output page
Arrays
<?php
$arr = array("foo" => "bar", 12 => true);
echo $arr["foo"]; // bar
array()= creates arrays
key = either an integer or a string.
value = any PHP type.
echo $arr[12];
?>
// 1
if no key given (as in example), the PHP
interpreter uses (maximum of the integer
indices + 1).
<?php
array(5 => 43, 32, 56, "b" => 12);
array(5 => 43, 6 => 32, 7 => 56, "b" => 12);
?>
if an existing key, its value will be overwritten.
<?php
can set values in an array
$arr = array(5 => 1, 12 => 2);
foreach ($arr as $key => $value) { echo $key, '=>',
$value); }
$arr[] = 56;
$arr["x"] = 42; // adds a new element
unset()removes a
key/value pair
// the same as $arr[13] = 56;
array_values()
makes reindexing effect
(indexing numerically)
unset($arr[5]); // removes the element
unset($arr);
// deletes the whole array
$a = array(1 => 'one', 2 => 'two', 3 => 'three');
unset($a[2]);
$b = array_values($a);
?>
*Find more on arrays
view the output page
Constants
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");
You can access
// Invalid constant names (they shouldn’t start
constants anywhere in
your script without
regard to scope.
//
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
define("__FOO__", "something");
?>
Operators
Example
x+=y
x-=y
x*=y
x/=y
Is the same as
x=x+y
x=x-y
x=x*y
x=x/y
• Arithmetic Operators: +, -, *,/ , %, ++, --
• Assignment Operators: =, +=, -=, *=, /=, %=
x%=y
x=x%y
• Comparison Operators: ==, !=, >, <, >=, <=
• Logical Operators: &&, ||, !
• String Operators: . and .= (for string concatenation)
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
$a = "Hello ";
$a .= "World!";
Conditionals: if else
Can execute a set of code depending on a condition
<html><head></head>
<!-- if-cond.php CS443 -->
<body>
if (condition)
code to be executed if condition
is true;
<?php
$d=date("D");
echo $d, "<br/>";
if ($d=="Fri")
echo "Have a nice weekend! <br/>";
else
else
code to be executed if condition
is false;
echo "Have a nice day! <br/>";
$x=10;
if ($x==10)
{
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
echo "Hello<br />";
echo "Good morning<br />";
}
?>
In this case we get a three letter
string for the day of the week.
</body>
</html>
view the output page
Conditionals: switch
<html><head></head>
<body>
<!–- switch-cond.php CS443 -->
<?php
Can select one of many sets of lines to execute
$x = rand(1,5); // random integer
echo "x = $x <br/><br/>";
switch ($x)
switch (expression)
{
{
case label1:
case 1:
echo "Number 1";
code to be executed if expression = label1;
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;
break;
echo "No number between 1 and 3";
break;
}
}
?>
</body>
</html>
view the output page
Looping: while and do-while
Can loop depending on a condition
<html><head></head>
<body>
<html><head></head>
<body>
<?php
$i=0;
do
{
<?php
$i=1;
while($i <= 5)
{
$i++;
echo "The number is $i <br />";
echo "The number is $i <br />";
$i++;
}
}
?>
while($i <= 10);
?>
</body>
</html>
</body>
</html>
view the output page
view the output page
loops through a block of code if, and
as long as, a specified condition is
true
loops through a block of code once,
and then repeats the loop as long
as a special condition is true (so
will always execute at least once)
Looping: for and foreach
Can loop depending on a "counter"
<?php
<?php
for ($i=1; $i<=5; $i++)
$a_array = array(1, 2, 3, 4);
{
foreach ($a_array as $value)
echo "Hello World!<br />";
{
}
?>
$value = $value * 2;
echo "$value <br/> \n";
}
?>
loops through a block of code a
specified number of times
<?php
$a_array=array("a","b","c");
foreach ($a_array as $key => $value)
{
echo $key . " = " . $value . "\n";
}
?>
view the output page
loops through a block of code for each
element in an array
User Defined Functions
Can define a function using syntax such as the following:
<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
Can also define conditional
{
echo "Example function.\n";
functions, functions within functions,
return $retval;
and recursive functions.
}
?>
Can return a value of any type
<?php
<?php
function small_numbers()
{
function square($num)
return array (0, 1, 2);
{
}
return $num * $num;
list ($zero, $one, $two) = small_numbers();
}
echo square(4);
?>
echo $zero, $one, $two;
?>
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
takes_array(array(1,2));
?>
view the output page
Variable Scope
The scope of a variable is the context within which it is defined.
<?php
$a = 1; /* limited variable scope */
function Test()
{
echo $a;
The scope is local within functions,
/* reference to local scope variable */
and hence the value of $a is
}
undefined in the “echo” statement.
Test();
?>
<?php
<?php
$a = 1;
function Test()
$b = 2;
function Sum()
{
{
static
global
static $a = 0;
echo $a;
$a++;
does not lose
its value.
refers to its
global
version.
global $a, $b;
$b = $a + $b;
}
}
Test1();
Test1();
Test1();
?>
Sum();
echo $b;
?>
view the output page
Including Files
The include() statement includes and evaluates the specified file.
// vars.php
<?php
<?php
function foo()
{
$color = 'green';
$fruit = 'apple';
global $color;
?>
include ('vars.php‘);
// test.php
<?php
echo "A $color $fruit";
}
echo "A $color $fruit"; // A
include 'vars.php';
/* 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.
*/
echo "A $color $fruit"; // A green apple
?>
foo();
// A green apple
echo "A $color $fruit"; // A green
view the output page
?>
view the output page
*The scope of variables in “included” files depends on where the “include” file is added!
You can use the include_once, require, and require_once statements in similar ways.
PHP Information
The phpinfo() function is used to output PHP information about the version installed on the server, parameters
selected when installed, etc.
INFO_GENERAL
The configuration line,
php.ini location,
build date,
<html><head></head>
<!– info.php CS443
Web Server,
<body>
System and more
<?php
// Show all PHP information
phpinfo();
?>
<?php
INFO_CREDITS
INFO_CONFIGURATION Local and master values
PHP 4 credits
for php directives
// Show only the general information
phpinfo(INFO_GENERAL);
INFO_MODULES
Loaded modules
?>
</body>
</html>
INFO_ENVIRONMENT
INFO_VARIABLES
Environment variable
information
All predefined variables
from EGPCS
view the output page
INFO_LICENSE
PHP license information
INFO_ALL Shows all of the above (default)
Server Variables
The $_SERVERarray variable is a reserved variable that contains all server information.
<html><head></head>
<body>
<?php
echo "Referer: " . $_SERVER["HTTP_REFERER"] . "<br />";
echo "Browser: " . $_SERVER["HTTP_USER_AGENT"] . "<br />";
echo "User's IP address: " . $_SERVER["REMOTE_ADDR"];
?>
<?php
echo "<br/><br/><br/>";
echo "<h2>All information</h2>";
foreach ($_SERVER as $key => $value)
{
echo $key . " = " . $value . "<br/>";
$_SERVER info
on php.net
}
?>
</body>
</html>
view the output page
The $_SERVER is a super global variable, i.e. it's available in all scopes of a PHP script.
File Open
The fopen("file_name","mode")function is used to open files in PHP.
r
Read only.
Write only.
Append.
r+
w+
a+
Read/Write.
Read/Write.
Read/Append.
Create and open for read/write.
w
a
x
Create and open for write only. x+
For w, and a, if no file exists, it tries to create it
(use with caution, i.e. check that this is the case,
otherwise you’ll overwrite an existing file).
<?php
$fh=fopen("welcome.txt","r");
?>
For x if a file exists, this function fails (and
returns 0).
<?php
if
( !($fh=fopen("welcome.txt","r")) )
exit("Unable to open file!");
?>
If the fopen()function is unable to open
the specified file, it returns 0 (false).
File Workings
<?php
<?php
fclose() closes a file.
$myFile = "welcome.txt";
if (!($fh=fopen($myFile,'r')))
exit("Unable to open file.");
while (!feof($fh))
$myFile = "welcome.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
?>
fgetc()reads a single character
fwrite(), fputs ()
writes a string with and without \n
{
$x=fgetc($fh);
echo $x;
}
view the output page
<?php
fclose($fh);
?>
feof()determines if the end is
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or
die("can't open file");
$stringData = "New Stuff 1\n";
fwrite($fh, $stringData);
$stringData = "New Stuff 2\n";
fwrite($fh, $stringData);
fclose($fh);
view the output page
true.
fgets()reads a line of data
<?php
$lines = file('welcome.txt');
foreach ($lines as $l_num => $line)
{
echo "Line #{$l_num}:“
.$line.”<br/>”;
file()reads entire file into an
array
?>
view the output page
}
?>
view the output page
Tải về để xem bản đầy đủ
Bạn đang xem 20 trang mẫu của tài liệu "Bài giảng Web technologies and e-Services - Bài 5, Phần 1: PHP - Trường Đại học Bách khoa Hà Nội", để tải tài liệu gốc về máy hãy click vào nút Download ở trên
File đính kèm:
- bai_giang_web_technologies_and_e_services_bai_5_phan_1_php_t.pdf