0% found this document useful (0 votes)
1 views94 pages

Web06_PHPAdvanced

Uploaded by

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

Web06_PHPAdvanced

Uploaded by

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

WEB DESIGN

HienLTH – KhietLTN Web Design 1


PHP Advanced

MSc. Luong Tran Ngoc Khiet

HienLTH – KhietLTN Web Design 2


Content
1. Object oriented
2. Data transmission (POST / GET)
3. Cookies, Sessions
4. Process the date
5. Handles files & folders
6. Upload files to the Server
7. Picture
8. E-mail, Secure E-mail
9. Hash
10.Error handling
HienLTH – KhietLTN Web Design 3
1. Object oriented

• Class declaration
• The constructor
• Scope
• Inheriting
• Function serialize, unserialize

HienLTH – KhietLTN Web Design 4


1. Object oriented
• Declare

• The constructor

HienLTH – KhietLTN Web Design 5


1. Object oriented
• Class declaration
class class_name
{
properties and methods
}
• Create and destroy an object
$variable_name = new class_name();

The object is automatically destroyed when there are no


more references to it
$variable_name = NULL;

HienLTH – KhietLTN Web Design 6


1. Object oriented
• Keywords declared:
– public: can be used outside of the class
– private: for local use only inside the class
– protected: used by the class inherits
• Some general rules:
– Can not declare two methods with the same name
– The method must be declared within the class
declaration
– Use the dummy variable $ this to access the members
and methods in the class
– Use the -> operator to access members and methods
HienLTH – KhietLTN Web Design 7
1. Object oriented
• Declare constructor and destructor
public function __construct (parameter list)
{
initialize the values of members
}
The constructor is automatically executed when the object is created
public function __destruct()
{
clean
}
The destructor is automatically performed when the object is destroyed

HienLTH – KhietLTN Web Design 8


1. Object oriented

HienLTH – KhietLTN Web Design 9


1. Object oriented

• Declare
const TÊN_HẰNG = value;

• Access
tên_lớp::TÊN_HẰNG // ngoài lớp
seft::TÊN_HẰNG // trong lớp

HienLTH – KhietLTN Web Design 10


1. Object oriented

• Declare
… static $thuộc_tính

• Truy xuất
tên_lớp::$thuộc_tính // ngoài lớp
seft::$thuộc_tính // trong lớp

HienLTH – KhietLTN Web Design 11


1. Object oriented

• Khai báo
– … static function phương_thức(…)

• Truy xuất
– tên_lớp::phương_thức(…) // ngoài lớp
– seft:: phương_thức(…) // trong lớp

HienLTH – KhietLTN Web Design 12


1. Object oriented

• Declare subclasses
class lớp_con extends lớp_cha
{
properties and methods
}

All members and methods declared public or


protected in the parent class are inherited and can
be used in subclasses

HienLTH – KhietLTN Web Design 13


Method overloading

• Call a superclass method


parent::method(…)

By redefining an existing method in the parent


class, all calls to this method that are not
specified above are interpreted as calling the
method with the same name of the subclass

HienLTH – KhietLTN Web Design 14


Polymorphism
• Abstract class declaration
abstract class lớp_trừu_tượng
{
// các thuộc tính
abstract public function phương_thức_trừu_tượng(…);

// các phương thức khác
}
Cannot create object directly from abstract class
The child class is required to define the abstract
methods of the parent class

HienLTH – KhietLTN Web Design 15


Ngăn kế thừa và nạp chồng

• Lớp không thể kế thừa


final class không_thể_kế_thừa { … }

• Phương thức không thể nạp chồng


final public function không_thể_nạp_chồng(…) { … }

HienLTH – KhietLTN Web Design 16


interface

• Declare Interface
interface giao_diện
{
public function phương_thức();

}

• Declare class according to the Interface template


abstract class tên_lớp implements giao_diện
{

}
Classes that use Interface or inherit from a class using Interface are
required to define all the methods in that Interface

HienLTH – KhietLTN Web Design 17


1. Object oriented

HienLTH – KhietLTN Web Design 18


1. Object oriented
1. Hàm serialize() dùng để lưu trữ đối tượng, hàm trả về một chuỗi các byte để lưu thông tin của đối tượng
2. Hàm unserialize() dùng để khôi phục đối tượng được lưu giữ bởi hàm serialize()
<?php
class AClass {
var $a;
function AClass() {
}
};
$ob1 = new AClass();
$ob1->a = 10;
$ob1->b = 100;
$ob1->c = “Nguyen Ngoc Thuy Hang";

$luu = serialize($ob1);
echo "$luu <br>";
$ob2 = unserialize($luu);
var_dump($ob2);
?>

HienLTH – KhietLTN Web Design 19


2. Data transmission
(POST / GET)
2.1 Mechanism of data transmission
2.2 Ways of data transmission

HienLTH – KhietLTN Web Design 20


Mechanism of data
transmission
www.example.com
Webserver

2
Internet
or Intranet
Yêu cầu trang b.php 7

HienLTH – KhietLTN Web Design 21


Mechanism of data
transmission

HienLTH – KhietLTN Web Design 22


Mechanism of data
transmission
www.example.com
Textbox : txtDangnhap
Webserver
Password Box: txtDangnhap
2
txtDangnhap = phpAdmin Internet
or Intranet
txtDangnhap = admin
7
Yêu cầu trang xlDangnhap.php

HienLTH – KhietLTN Web Design 23


2. Data transmission
(POST / GET)
• Data entry site
– Way 1: Direct data transfer via url
• Use the link to revise the url
• Through the object location
– Way 2: data transmission via the form
• Using objects <form>
• Input through formfield
• Performs data transmission via submit
• Two methods send GET / POST data
• Website receives data (using global variables)
– Way 1: $_GET[“variable”]
– Way 2: $_POST[“variable”]
– way 3: $_REQUEST[“variable”]
HienLTH – KhietLTN Web Design 24
2. Data transmission
(POST / GET)
• $_POST (invisible in the URL)
thanks.php

• $_GET (visible in the URL)


thanks.php?name=Steve&age=54

HienLTH – KhietLTN Web Design 25


3. Cookies, Sessions

3.1 What are Cookies?


3.2 Use of cookies
3.3 Example Cookies
3.4 What is Session?
3.5 Using the Session
3.6 Session example

HienLTH – KhietLTN Web Design 26


3.1 What are Cookies?
▪ The messages are saved by the server to the client's
machine
▪ Each time the client sends a request to a web page, it
will also send a cookie file saved last time to the server.
▪ Processing information (save, retrieve) in cookies is
done by the server.
▪ Usually used to store client's personal information.

cookie

$_COOKIE

setcookie
Client Webserver

HienLTH – KhietLTN Web Design 27


3.2 Use of cookies
• Lệnh ghi cookie
setcookie(name, value, expire, path, domain);
setrawcookie(name, value, expire, path, domain);
• name : Tên cookie
• value: Giá trị cookie
• expire : Thời điểm mà cookie hết hiệu lực
• path : Đường dẫn trên server mà cookie có hiệu lực
• domain : Xác định tên miền mà cookie được gởi đi
• Bắt buộc phải xuất hiện trước thẻ <html>

• Lấy giá trị cookie


echo $_COOKIE[“cookieName"];

• Xóa cookie
setcookie(“cookieName", "", time() -3600);

HienLTH – KhietLTN Web Design 28


3.3 Example Cookie

$_COOKIE[fieldName]

cookie
Lưu username & password

setcookie
Client

Webserver

HienLTH – KhietLTN Web Design 29


3.4 What is session?

User 2
Session: user 1
User 1 Session: user 2
Session: user 3

User 3

HienLTH – KhietLTN Web Design 30


3.4 What is session?
$_SESSION[sessionVar]
Cookie: PHPSESSID

session_start
Client
Webserver

▪ The client information is stored by the server on the server


machine
▪ Use a session that stores a unique identifier for each client
▪ Purpose to store shared data for many pages in a client
session
HienLTH – KhietLTN Web Design 31
3.5 Using session
• Start the Session
session_start();
• Write & Read Session Values
$_SESSION[“sessionVar”] = $value ;
$_SESSION[“sessionVar”] = array();
$_SESSION[“sessionVar”][] = $value;

if (isset($_SESSION[“sessionVar"])
echo $_SESSION[“sessionVar"];

• Cancel Variables in Session


unset($_SESSION[“sessionVar”]);

• Cancel Session
session_destroy();

HienLTH – KhietLTN Web Design 32


3.6 For example: Count the
number of web page visits
<?php
session_start( );
if (isset($_SESSION["count"]))
$_SESSION["count"] = $_SESSION["count"] + 1;
else
$_SESSION["count"] = 1;

print “You've looked at this page ” .


$_SESSION['count'] . “times.”;
?>

HienLTH – KhietLTN Web Design 33


3.6 EG2: Application for Login

• How to prevent users from accessing


websites if not logged in?
• Idea:
• Use Session variables to store the user's login state:
$_SESSION[“IsLogin”] = true/false : Save login status
$_SESSION[“Username”] : Save Username
$_SESSION[“Authentication”] : Save Login
permission type

HienLTH – KhietLTN Web Design 34


Application for login–
Consists of 4 steps
1. Create a login.html page that requires users to login.
2. Create a validateuser.php page that handles login
information from login.htm page
– Connect to the database, check the login information is valid or not?
• If invalid, the redirect page login.html.
• If valid, then use a variable in the Session to store login status successful
For example: $_SESSION[“IsLogin”] = true.
– Note: The default value for this Session variable must be set to
false when initiating a Session.
3. Create the logout.php page which is the handle when the
user logs out
▪ Reset login status is not logged in ($_SESSION[“IsLogin”] = false).

HienLTH – KhietLTN Web Design 35


Session –
Application for Login
4. In all the pages that want to secure, add the
following code to check whether the user is
logged in or not, if not, then redirect the
login.html page again.
<?php
session_start();

if (!isset($_SESSION[“IsLogin”]) ||
$_SESSION[“IsLogin”] == false)
header(“Location: login.htm”);
?>

HienLTH – KhietLTN Web Design 36


Shopping cart (giỏ hàng)

Xóa biến trong Session


{‘Book1’, ‘Book2’, ‘Book3’}
Session : Array : Mathang [ ] Ghi xuống CSDL

Session : Array : Soluong[ ]

{13, 2, 7}

HienLTH – KhietLTN Web Design 37


Session – Cookie – Database
Cookie1

Session 1

Cookie2
Client 1 Web Server

Session 2 Session 3
Internet
or Intranet
Client 2 Database Server

Cookie3

Client 3

Information Storage Duration of Number Number of


sharing location existence of client websites used
Database/File Server Long Much Much
Session Server Short 1 Much
Cookies Client Long 1 Much
HienLTH – KhietLTN Web Design 38
Break
HienLTH – KhietLTN Web Design 39
4. Process the date

http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html
HienLTH – KhietLTN Web Design 40
4.Process the date

<?php
// Assuming today is: March 10th, 2001, 5:16:18 pm
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date('h-i-s, j-m-y, it is w Day z ');
// 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // It is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 15:16:08 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:17 m is month
$today = date("H:i:s"); // 17:16:17
?>
HienLTH – KhietLTN Web Design 41
Using date() function
string date ( string $format [, int $timestamp] )
format

Format Description Example returned values


character
d Day of the month, 2 digits with leading zeros 01 to 31

D A textual representation of a day, three letters Mon through Sun

j Day of the month without leading zeros 1 to 31

l A full textual representation of the day of the week Sunday through Saturday

S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j

F A full textual representation of a month, such as January or March January through December

Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003

HienLTH – KhietLTN Web Design 42


Date and time formats

DAYS MONTH
d - day of the month 2 digits (01-31) F - Full name of month (January - December)
j - day of the month (1-31) m - 2 digit month number (01-12)
D - 3 letter day (Mon - Sun) n - month number (1-12)
l - full name of day (Monday - Sunday) M - 3 letter month (Jan - Dec)
N - 1=Monday, 2=Tuesday, etc (1-7) t - Days in the month (28-31)
S - suffix for date (st, nd, rd)
w - 0=Sunday, 1=Monday (0-6) YEAR
z - day of the year (1=365) L - leap year (0 no, 1 yes)
o - ISO-8601 year number (Ex. 1979, 2006)
WEEK
W - week of the year (1-52)

HienLTH – KhietLTN Web Design 43


Date and time formats

TIME
a - am or pm
A - AM or PM
B - Swatch Internet time (000 - 999)
g - 12 hour (1-12)
G - 24 hour c (0-23)
h - 2 digit 12 hour (01-12)
H - 2 digit 24 hour (00-23)
i - 2 digit minutes (00-59) <?php
s - 2 digit seconds (00-59) echo date (‘g:i:s A’);
?>
OTHER
e - timezone (Ex: GMT, CST) 11:19:26 PM
I - daylight savings (1=yes, 0=no)
O - offset GMT (Ex: 0200)
Z - offset in seconds (-43200 - 43200)
r - full RFC 2822 formatted date
HienLTH – KhietLTN Web Design 44
Using getdate() function

array getdate ( [ int $timestamp = time() ] )

timestamp

➢The optional timestamp parameter is an integer Unix


timestamp that defaults to the current local time if
a timestamp is not given. In other words, it defaults to
the value of time().

HienLTH – KhietLTN Web Design 45


Using getdate() function

<html>
Gogle Chrome - x
File Edit View Favorites Tool Help
<head> Go
<title>My PHP</title> Address http://localhost/myweb/index.php

</head>
<body> Array ( [seconds] => 19
<? [minutes] => 35
$today = getdate(); [hours] => 3
print_r($today); [mday] => 20
?> [wday] => 3
</body> [mon] => 4
</html> [year] => 2011
[yday] => 109
[weekday] => Wednesday
[month] => April
[0] => 1303270519 )

HienLTH – KhietLTN Web Design 46


Using checkdate() function
• Checks the validity of the date formed by
the arguments. A date is considered valid
if each parameter is properly defined.
bool checkdate (int $month , int $day , int $year)

month ➢The month is between 1 and 12 inclusive.

day ➢The day is within the allowed number of days for


the given month. Leap years are taken into
consideration.
year
➢The year is between 1 and 32767 inclusive.

HienLTH – KhietLTN Web Design 47


Using checkdate() function

<html>
Google Chrome - x
<head> File Edit View Favorites Tool Help
Go
<title>My PHP</title> Address http://localhost/myweb/index.php

</head>
<body> bool(true) bool(false)
<?
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
?>
</body>
</html>

HienLTH – KhietLTN Web Design 48


5. Handles files & folders

1. Use include ()
2. Use include_once ()
3. Use include_path for big project
4. Check the file
5. Read and write files
6. Working with directories

HienLTH – KhietLTN Web Design 49


5. Handles files & folders
• include():
– Used to share shared functions, common code in a
project with many files.
– Other #include syntax of C language, this command
does not insert code into executable files that php file
like a function call syntax.
– Warning message if the file is not found but does not
stop the program.
• require() – similar include(), this difference
command will stop the program when the file is
not found.
HienLTH – KhietLTN Web Design 50
5. Handles files & folders
//vars.php Since include () makes a call to the php file,
<?php you can then return the value from
the included PHP file
$color = 'green';
$fruit = 'apple'; <!--File1.php-->
<?php
?> return 4 + 4;
?>
//test.php
<?php ------------------------------------

echo "A $color $fruit"; <!--File2.php-->


// A <?php
include 'vars.php'; echo "This is from file 2<br>";
echo "A $color $fruit"; $retVal = include("file1.php");
// A green apple echo “Value file 1: $retVal<br>";
echo "This is from file 2\n";
?> ?>
HienLTH – KhietLTN Web Design 51
5. Handles files & folders

• It is possible to place an include statement within


a conditional or iterative structure,
• Depending on the condition of the structure,
whether include () can be performed or not, one
or more times,
• This helps to assist in better architectural design
of the website.

HienLTH – KhietLTN Web Design 52


5. Handles files & folders
• include_once () is the same as include (), but the difference
is that only include once, next time if you see this file again,
it will not include anymore
• include_once () is case sensitive
<?php
include_once("a.php");
// this will include a.php
include_once("A.php");
// this will include a.php again on Windows!
?>

Because it is case sensitive,


include_one is inserted a second time
HienLTH – KhietLTN Web Design 53
5. Handles files & folders

• include file in absolute path: This way is bad


because when installing on another machine,
the included file will not be found
• include file in relative path: This is better, but
every time you change the location of the
included file, you have to edit at all files that
make the include call.
• The best way is to use include_path (set in the
PHP.INI file) for commonly used shared library
files (just like for C language).

HienLTH – KhietLTN Web Design 54


5. Handles files & folders
▪ thay đổi include_path trong PHP.INI
▪ dùng lệnh set_include_path()
<?php
var_dump(get_include_path());
set_include_path('/inc'); // Works as of PHP 4.3.0
var_dump(get_include_path());
restore_include_path();
var_dump(get_include_path());
?>

▪ dùng lệnh ini_set()


<?php
var_dump(ini_get("include_path"));
ini_set("include_path", "/inc"); // Works in all PHP versions
var_dump(ini_get("include_path"));
ini_restore("include_path");
var_dump(ini_get("include_path"));
?>
HienLTH – KhietLTN Web Design 55
5. Handles files & folders
file_exist(), is_file(), is_dir(), is_readable(),
is_writeable(), is_executable(), filesize(), fileatime()
⚫<?php
function outputFileTestInfo( $file ) {
if ( ! file_exists( $file ) ) {
print "$file does not exist<br/>";
return;
}
print "$file is ".(is_file( $file )?"":"not ")."a file<br/>\n";
print "$file is ".(is_dir( $file )?"":"not ")."a directory<br/>\n";
print "$file is ".(is_readable( $file )?"":"not ")."readable<br/>\n";
print "$file is ".(is_writable( $file )?"":"not ")."writable<br/>\n";
print "$file is ".( filesize($file))." bytes<br/>\n";
print "$file was accessed on ".date( "D d M Y g:i A",
fileatime($file ))."<br/>";
print "$file was modified on ".date( "D d M Y g:i A",
filemtime( $file))."<br/>";
print "$file was changed on".date( "D d M Y g:i A",
filectime($file))."<br/>";
}
outputFileTestInfo("c:\\windows\\system32\\cmd.exe");
?>
HienLTH – KhietLTN Web Design 56
5. Handles files & folders

fopen($filename, $mode);

fwrite($handle, $string);
fread($handle, $length);
fgets($handle);

sprintf($format);
fscanf($handle, $format);

fseek($handle, $offset);
fclose($handle);

file_get_contents($filename);

HienLTH – KhietLTN Web Design 57


5. Handles files & folders
<?php
$var1 = 10; echo "Read all file by
$var2 = "This is a String"; fread......\n";
$var3 = true; $f = fopen("test.txt", "rb");
$f = fopen("test.txt", "wt");
fwrite($f, "$var1 $var2 $myfile = fread($f,
$var3\n"); filesize("test.txt"));
fwrite($f, echo $myfile;
"$var1\n$var2\n$var3\n"); fclose($f);
fclose($f);
echo "Read all file......\n";
echo "Read line by $myfile =
line......\n"; file_get_contents("test.txt");
$f = fopen("test.txt", "rt"); echo($myfile);
while (!feof($f)) { ?>
$line = fgets($f);
echo "$line";
}
fclose($f);
HienLTH – KhietLTN Web Design 58
5. Handles files & folders
<?php
$var1=10;
$var2=100;
$var3=100.3434;
$var4="Test string";
$f=fopen("test.txt", "wt");
fwrite($f, sprintf("%d %10.3f %10.3lf\n\r", $var1, $var2,
$var3));
fwrite($f, sprintf("%s", $var4));
fclose($f);
$f=fopen("test.txt", "rt");
if (list($v1, $v2, $v3, $v4) = fscanf($f, "%d %f %lf\n\r%s"))
{
var_dump($v1);
var_dump($v2);
var_dump($v3);
var_dump($v4);
}
$v4 = fgets($f);
var_dump($v4);
fclose($f);
?>
HienLTH – KhietLTN Web Design 59
5. Handles files & folders
<?php
class AClass {
};
$ob1 =& new AClass();
$ob1->a = 10;
$ob1->b = 100.023;
$ob1->c = "Test String";
var_dump($ob1);
$f = fopen("test.txt", "wb");
fwrite($f, serialize($ob1));
fclose($f);
$f = fopen("test.txt", "rb");
$ob2 = unserialize(fgets($f));
fclose($f);
var_dump($ob2);
?>
HienLTH – KhietLTN Web Design 60
5. Handles files & folders
• mkdir(), rmdir()
• opendir(), readdir(), closedir()
<?php
$dir=opendir("c:\\windows");
while ($file=readdir($dir)) {
echo "$file\n";
}
closedir($dir);
?>

HienLTH – KhietLTN Web Design 61


6. Upload the file to the server

• Uploading files to the server is an indispensable


function for Web-based applications.
• In order for the form to upload files, we must
specify the form's enctype attribute to "multipart /
form-data".
• With PHP, you can determine the maximum size
of an upload file by placing a hidden field named
MAX_FILE_SIZE in front of the control file.

HienLTH – KhietLTN Web Design 62


6. Upload the file to the server
Yêu cầu trang upload.php
Webserver

Internet
or Intranet
file

Disk
driver

Upload.php
• $_FILES[“file”]["name"]
• $_FILES[“file”]["type"]
• $_FILES[“file”]["size"]
• $_FILES[“file”]["tmp_name"]
• $_FILES["file”]["error"]

HienLTH – KhietLTN Web Design 63


6. Upload the file to the server

Mảng $_FILE
Element Contains Example
$ FILES['taptin']['name'] Name of uploaded file test.gif

$_FILES['taptin']['tmp_name' Path to temporary file /tmp/phprDfZvN


]
$_FILES['taptin']['size'] Size (in bytes) of uploaded 6835
file
$_FILES['taptin']['error'] An error code corresponding UPLOAD_ERR_F
to a PHP constant ORM_SIZE

$_FILES['taptin']['type'] MIME type of uploaded file image/gif


(where given by client)
HienLTH – KhietLTN Web Design 64
6. Upload the file to the server

Mã lỗi
Constant Name Value Explanation
UPLOAD_ERR_OK 0 No problem
UPLOAD_ERR_INI_SIZE 1 File size exceeds php.ini limit set in
upload_max_filesize
UPLOAD_ERR_FORM_SIZ 2 File size exceeds limit set in hidden
E element named MAX_FILE_SIZE
UPLOAD_ERR_PARTIAL 3 File only partially uploaded
UPLOAD_ERR_NO_FILE 4 File was not uploaded

HienLTH – KhietLTN Web Design 65


6. Upload the file to the server

HienLTH – KhietLTN Web Design 66


6. Upload the file to the server

67
HienLTH – KhietLTN Web Design 67
Check the error, format, file
upload size
• Note:
– $_FILES[“…”][“type”]
• “image/gif”
• “image/jpeg” → Firefox nhận đây là file
jpeg
• “image/pjpeg” → IE nhận đây là file jpeg
– $_FILES[“…”][“size”] : Kích thước file tính
theo byte
– $_FILES[“…”][“error”] : Mã lỗi khi upload File
• = 0 : Không có lỗi
• > 0 : Có lỗi
HienLTH – KhietLTN Web Design 68
7. Image

Draw pictures from text

HienLTH – KhietLTN Web Design 69


8. E-mail, Secure E-mail

• Sử dụng thư viện open source: PHP Mailer


http://phpmailer.sourceforge.net/
• Chép 3 file: class.phpmailer.php,
class.smtp.php, phpmailer.lang-en.php
vào thư mục web của site

HienLTH – KhietLTN Web Design 70


Send email using GMail Mail
Server

HienLTH – KhietLTN Web Design 71


9. Hash problem
• Message Digest (hash) engine. Allows direct or
incremental processing of arbitrary length messages
using a variety of hashing algorithms.
• The Hash extension requires no external libraries and is
enabled by default as of PHP 5.1.2. It may be explicitly
disabled by using the --disable-hash switch to configure.
Earlier versions of PHP may incorporate the Hash
extension by installing the » PECL module.
• There is no installation needed to use these functions;
they are part of the PHP core.
• This extension has no configuration directives defined
in php.ini.
HienLTH – KhietLTN Web Design 72
9. Hash problem (cont. )

• array hash_algos ( void )


– Returns a numerically indexed array containing
the list of supported hashing algorithms.
• string hash_file ( string $algo , string $filena
me [, bool $raw_output = false ] )
– Algo: Name of selected hashing algorithm (i.e.
"md5", "sha256", "haval160,4", etc..)
– Filename: URL describing location of file to be
hashed; Supports fopen wrappers.
– raw_output: When set to TRUE, outputs raw
binary data. FALSE outputs lowercase hexits.

HienLTH – KhietLTN Web Design 73


9. Hash problem (cont. )

<html>
Microsoft Internet Explorer - x
<head> File Edit View Favorites Tool Help
Go
<title>My PHP</title> Address http://localhost/myweb/index.php

</head> Array ( [0] => md2


<body> [1] => md4
<? [2] => md5
[3] => sha1
print_r(hash_algos()); [4] => sha224
?> [5] => sha256
</body> [6] => sha384
[7] => sha512
</html> [8] => ripemd128
[9] => ripemd160
[10] => ripemd256
[11] => ripemd320
[12] => whirlpool
[13] => tiger128,3
[14] => tiger160,3
[15] => tiger192,3
[16] => tiger128,4
[17] => tiger160,4 …

HienLTH – KhietLTN Web Design 74


9. Hash problem (cont. )
Microsoft Internet Explorer - x
<html> File Edit View Favorites Tool Help
<head> http://localhost/myweb/index.php Go
Address
<title>My PHP</title>
</head> 5c6ffbdd40d9556b73a21e63c3e0e904
<body>
<?
file_put_contents('example.txt', 'The qu
ick brown fox jumped over the lazy dog
.');
echo hash_file('md5', 'example.txt');
?>
</body> Create a file named “example.txt” with
</html> content of “The quick …”. This file is
placed at the root folder.

Hash file “example.txt” with


algorithm having name “md5”

HienLTH – KhietLTN Web Design 75


9. Hash problem (cont. )

• string hash ( string $algo , string $data [, b


ool $raw_output = false ] )
– Algo: Name of selected hashing algorithm (i.e.
"md5", "sha256", "haval160,4", etc..)
– Data: Message to be hashed.
– raw_output: When set to TRUE, outputs raw
binary data. FALSE outputs lowercase hexits.

HienLTH – KhietLTN Web Design 76


9. Hash problem (cont. )

Microsoft Internet Explorer - x


<html>
File Edit View Favorites Tool Help
<head> Go
http://localhost/myweb/index.php
<title>My PHP</title> Address
</head> ec457d0a974c48d5685a7efa03d137dc8bbde7e3
<body>
<?
echo hash('ripemd160', 'The quick bro
wn fox jumped over the lazy dog.');
?>
</body>
</html>

Hash string “The quick


brown…” with algorithm
having name “ripemd160”
HienLTH – KhietLTN Web Design 77
10. Error handling

• Using try…catch
try
{
// do something that can go wrong
}
catch (Exception $e)
{
throw new Exception( 'Something really gone wrong', 0, $e);
}

http://php.net/manual/en/language.exceptions.php

HienLTH – KhietLTN Web Design 78


Control operator error

• The error handling operator (@) is used to


precede functions and expressions. Then all
the error messages in the jaw, that expression
is ignored.
• For example:
<?php
$b = @file(“a ag a”) or die(“Khong the mo file”);
?>

HienLTH – KhietLTN Web Design 79


Reference

• Website W3school
• Slide lập trình Web, ĐH KHTN, 2007

HienLTH – KhietLTN Web Design 80


Q&A

HienLTH – KhietLTN Web Design 81


THE END

HienLTH – KhietLTN Web Design 82


Discussion

▪ Họ tên:
▪ Mã SV:
▪ Lớp:
▪ Khoá:
▪ Email:

01 02 … 19 20

HienLTH – KhietLTN Web Design 83


Question 1: Select the correct statement to
get the value of the element named "email"
in the following HTML form:
<form action="index.php" method="post">
<input type="text"
name="email"/>
</form>
A. $_GET['email'], $_POST['email']
B. $_GET['email'], $_REQUEST['email']
C. $_POST['email'], $_REQUEST['email']
D. $_POST['email']
HienLTH – KhietLTN Web Design 84
Question 2: Said the results displayed in index.php page if the user
submits the form from the following page (the user enters hello and
world respectively for 2 textbox):
<form action="index.php" method="post">
<input type="text" name="element[]">
<input type="text" name="element[]">
</form>
❖ index.php page
<?php
echo $_GET['element'];
?>
A. Don't print
anything
B. Print notice notices
C. Print array array
D. helloworld

HienLTH – KhietLTN Web Design 85


Question 3: Which statement is correct to
output the word "user" of the following URL:
http://localhost:8080/index.php?user=admin
A. echo $_REQUEST["user"];
B. echo $_REQUEST[0];
C. echo $_GET["user"];
D. All are wrong

HienLTH – KhietLTN Web Design 86


Question 4: In PHP, if two elements have the
same name then:
A. PHP output error message
B. PHP combines 2 elements into an array
C. The second element is automatically
renamed to the new name
D. The value of the second element overlaps
the first

HienLTH – KhietLTN Web Design 87


Question 5: The session data is stored by
default in:
A. PHP file system
B. Database
C. Virtual memory
D. All are wrong

HienLTH – KhietLTN Web Design 88


Question 6: The isset function ($ _ GET
["user"]) will return the value "TRUE" if:

A. The variable $ _GET ["user"] is empty ""


B. The variable $ _GET ["user"] is loaded
with a value
C. The variable $ _GET ["user"] is
initialized
D. All is incorrect

HienLTH – KhietLTN Web Design 89


Question 7: Assuming the client browser is storing a cookie
named immediatelytruycap and storing the value =
"30042012", select the command to replace for the key word
so that the following code is output: 2012
<?php
if (isset($_COOKIE['ngaytruycap'])) {
key
}
else
echo "khong lay duoc";
?>
A. echo $_COOKIE(['ngaytruycap'],4);
B. echo substr($_COOKIE['ngaytruycap'],4,4);
C. echo substr($_COOKIE['ngaytruycap'],4);
D. echo substr($_COOKIE['ngaytruycap'],3,4);
HienLTH – KhietLTN Web Design 90
Question 8: Which command is correct to
output the word "admin" of the following
URL:
http://localhost:8080/index.php?user=admin
A. echo $_REQUEST["user"];
B. echo $_GET["user"];
C. echo $_REQUEST[0];
D. Both A and B are right

HienLTH – KhietLTN Web Design 91


Question 9: Indicates the result of the index.php page after submitting the
following form (textbox user did not enter data):
<form action="index.php" method="post">
<input type="text" name=“user">
</form>
❖ Trang index.php
1. <?php
2. if(isset($_SERVER["REQUEST_METHOD"]))
3. echo "True";
4. else
5. echo "False";
6. if(isset($_SERVER["user"]))
7. echo "True";
8. else
9. echo "False"; ?>
A. FalseFalse
B. FalseTrue;
C. TrueFalse
D. The wrong code is on line 6
HienLTH – KhietLTN Web Design 92
Question 10: Which method to use to
exchange data between pages (webpage) in a
website:
$_GET, $_POST và $_REQUEST
A. $_SESSION và $_COOKIE
B. Database
C. All are wrong

HienLTH – KhietLTN Web Design 93


Thank you!!!

HienLTH – KhietLTN Web Design 94

You might also like