VKDoc PHP 编程高级教程(四) - ***清单 10-13
.";
$pdf->WriteHTML ( $txt );
//save the PDF $pdf->Output ( ‘image_and_html.pdf’, ‘I’ ); ?>`
运行这个例子的结果可以在图 10-4 中看到。
***图 10-4。*运行清单 10-7 修复重叠问题
我们的第三个也是最后一个 TCPDF 用法的例子,见清单 10-8 ,将输出一个条形码和渐变。可用的条形码类型可在barcodes.php文件中找到。输出条形码的方法有write1DBarcode、write2DBarCode,和setBarcode。渐变方式有Gradient、LinearGradient、CoonsPatchMesh,和RadialGradient。
清单 10-8。 TCPDF 生成条形码和渐变
`
error_reporting ( E_ALL ); require_once (‘/tcpdf/config/lang/eng.php’); require_once (‘/tcpdf/tcpdf.php’);
//Contruct a new TCPDF object $pdf = new TCPDF ();
//set document meta information $pdf->SetCreator ( PDF_CREATOR ); $pdf->SetAuthor ( ‘Brian Danchilla’ ); $pdf->SetTitle ( ‘Pro PHP Programming - Chapter 10’ ); $pdf->SetSubject ( ‘TCPDF Example 3 - Barcode & Gradient’ ); $pdf->SetKeywords ( ‘TCPDF, PDF, PHP’ );
//set font $pdf->SetFont ( ‘times’, ‘’, 20 );
//set margins $pdf->SetMargins( PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT );
//add a page $pdf->AddPage(); $txt = <<Write( 20,
t
x
t
)
;
‘
‘
txt );` `
txt);‘‘pdf->Ln();
$pdf->write1DBarcode(‘101101101’, ‘C39+’);
$pdf->Ln();
$txt = “Above: a generated barcode. Below, a generated gradient image”;
p
d
f
−
>
W
r
i
t
e
H
T
M
L
(
pdf->WriteHTML(
pdf−>WriteHTML(txt);
$pdf->Ln();
b
l
u
e
=
a
r
r
a
y
(
0
,
0
,
200
)
;
∗
∗
∗
∗
blue = array( 0, 0, 200 );** **
blue=array(0,0,200);∗∗∗∗yellow = array( 255, 255, 0 ); $coords = array( 0, 0, 1, 1 );
//paint a linear gradient $pdf->LinearGradient( PDF_MARGIN_LEFT, 90, 20, 20, $blue, $yellow,
c
o
o
r
d
s
)
;
∗
∗
∗
∗
coords );** **
coords);∗∗∗∗pdf->Text( PDF_MARGIN_LEFT, 111, ‘Gradient cell’ ); //label
//save the PDF $pdf->Output( ‘barcode_and_gradient.pdf’, ‘I’ ); ?>`
清单 10-8 中的代码增加了设置页边距、编写条形码和绘制线性渐变的功能。运行这个例子会产生图 10-5 。
***图 10-5。*用 TCPDF 生成的条码和渐变
最后,您应该知道您可以用方法SetAutoPageBreak改变分页符的行为。默认情况下,分页是自动的,就像调用了$pdf->SetAutoPageBreak( TRUE, PDF_MARGIN_FOOTER);一样。要关闭自动分页,你可以调用$pdf->SetAutoPageBreak( FALSE );。如果没有自动分页符,一页上放不下的任何额外数据都会被删除。这就需要程序员增加更多的AddPage调用,检查页面内容的大小。使用自动分页符,不适合的数据会输出到新页面上。
抓取网站数据
有时候,我们希望从一个网站检索信息,但是通过 web 服务 API 调用或提要并不容易访问。我们感兴趣的数据以原始 HTML 的形式呈现。我们希望以自动化的方式获得数据,以便进行进一步的数据处理。这个过程被称为页面抓取。
抓取数据不如从提要或 API 接收 XML 数据精确。但是,我们可以使用上下文线索,如 CSS 元素、id 和类值,并定期在表中输出数据,以理解检索到的数据。更严格遵循格式的网站提供更容易精确抓取的数据。
抓取网站数据是一个两步的过程。首先,我们需要获取远程内容,然后我们必须对其进行处理。抓取远程内容可以简单地通过file_get_contents函数来完成,或者使用 cURL 库的更多配置选项来完成。我们可以对数据做的一些事情是直接显示它,过滤/解析它的特定内容,或者将它存储在文件或数据库中。
在本节中,我们关注第二个选项,解析特定的内容。对于一般内容,我们可以用正则表达式来完成。对于我们的 HTML 示例,将数据加载到 DOMDocument 对象中更有意义。我们将展示如何将 DOMDocument 与 DOMXPath 一起使用。我们还将使用 phpQuery 库展示等效的功能。
phpQuery 包装了 DOMDocument,旨在成为服务器端 jQuery 符号的“端口”。因此,如果您已经了解 jQuery,那么这个库将很容易上手。关于 XML、DOM 和 jQuery 的更多信息可以在第十四章和第十五章中找到。
注意如果你收到消息Fatal error: Call to undefined function curl_init(),那么你需要安装或者启用cURL扩展。如果您的系统中没有cURL库,您可能需要下载它。
在php.ini中添加或启用延长线:
`;windows: extension=php_curl.dll
;linux: extension=php_curl.so`
并重新启动您的 web 服务器
在清单 10-9 的中,我们将使用 cURL 从[www.nhl.com](http://www.nhl.com)获取和输出数据。
***清单 10-9。*基本卷发用法
`
$url = “http://www.nhl.com”; print fetchRawData ( $url );
function fetchRawData(KaTeX parse error: Expected '}', got 'EOF' at end of input: url) { ch = curl_init (); curl_setopt ( $ch, CURLOPT_URL, $url ); curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true ); //return the output as a variable curl_setopt ( $ch, CURLOPT_FAILONERROR, true ); //fail if error encountered curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, true ); //allow redirects curl_setopt ( $ch, CURLOPT_TIMEOUT, 10 ); //time out length
$data = curl_exec ( $ch ); if (! $data) { echo “cURL error:\n”; echo “#” . curl_errno ( $ch ) . “\n”; echo curl_error ( $ch ) . “\n”; echo “Detailed information:”; var_dump ( curl_getinfo ( $ch ) ); die (); }
curl_close ( $ch ); return $data; }
?>`
在清单 10-9 中,我们用curl_init()得到了一个 cURL 资源句柄。然后我们用curl_setopt调用配置 cURL 设置。curl_exec执行请求并返回结果。最后,我们检查结果是否为非空。如果是,那么我们使用curl_errno、curl_error和curl_getinfo来排除故障。curl_getinfo包含关于最后一个请求的信息。典型的错误如下所示:
cURL error: #6 Could not resolve host: www.znhlz.com; Host not found
cURL 是非常可配置的。其他一些选项包括:
curl_setopt( $ch, CURLOPT_POST, true ); //POST request curl_setopt( $ch, CURLOPT_POSTFIELDS, "key1=value1&key2=value2" );//POST key/value pairs curl_setop($ch, CURLOPT_USERPWD, "username:password" ); //for authenticated sites //some sites block requests that do not have the user agent sent curl_setopt( $ch, CURLOPT_USERAGENT, $userAgent );
如果我们不需要大量配置并且在php.ini,中启用了file_get_contents用法,那么清单 10-9 中的脚本可以简化为清单 10-10 。
***清单 10-10。*使用文件获取内容简化内容获取
`
$url = “http://www.nhl.com”; print fetchRawData( $url );
//our fetching function function fetchRawData( KaTeX parse error: Expected '}', got 'EOF' at end of input: url ) { **data = file_get_contents($url);** if( $data === false ) { die(“Error”); } return $data; }
?>`
在基于清单 10-9 的下一个脚本中,我们将解析特定的数据并显示结果。在这种情况下,我们将找到网页上的所有链接及其标题。参见清单 10-11 。
***清单 10-11。*使用 cURL、DOMDocument 和 DOMXPath 查找网页上的链接
`
error_reporting ( E_ALL ^ E_NOTICE );
$url = “http://www.nhl.com”; $rawHTML = fetchRawData ( $url ); $parsedData = parseSpecificData ( $rawHTML ); displayData ( $parsedData );
//our fetching function function fetchRawData(KaTeX parse error: Expected '}', got 'EOF' at end of input: url) { ch = curl_init (); curl_setopt ( $ch, CURLOPT_URL, $url ); curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true ); //return the output as a variable curl_setopt ( $ch, CURLOPT_FAILONERROR, true ); //fail if error encountered curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, true ); //allow redirects curl_setopt ( $ch, CURLOPT_TIMEOUT, 10 ); //time out length
$data = curl_exec ( $ch ); if (! $data) { echo “cURL error:\n”; echo “#” . curl_errno ( $ch ) . “\n”; echo curl_error ( $ch ) . “\n”; echo “Detailed information:”; var_dump ( curl_getinfo ( $ch ) ); die (); } curl_close ( $ch ); return $data; }
//our parsing function function parseSpecificData(KaTeX parse error: Expected '}', got 'EOF' at end of input: …ata) { parsedData = array (); //load into DOM
d
o
m
=
n
e
w
D
O
M
D
o
c
u
m
e
n
t
(
)
;
@
dom = new DOMDocument (); @
dom=newDOMDocument(); @dom->loadHTML($data); //normally do not use error suppression!
$xpath = new DOMXPath (
d
o
m
)
;
dom );
dom); links =
x
p
a
t
h
−
>
q
u
e
r
y
(
"
/
h
t
m
l
/
b
o
d
y
/
/
a
"
)
;
i
f
(
xpath->query ( "/html/body//a" ); if (
xpath−>query("/html/body//a"); if(links) { foreach ( $links as KaTeX parse error: Expected '}', got 'EOF' at end of input: … nodes =
e
l
e
m
e
n
t
−
>
c
h
i
l
d
N
o
d
e
s
;
element->childNodes;
element−>childNodes; link = $element->attributes->getNamedItem ( ‘href’ )->value; foreach ( $nodes as KaTeX parse error: Expected '}', got 'EOF' at end of input: … if (node instanceof DOMText) { $parsedData [] = array (“title” => $node->nodeValue, “href” => $link ); } } } } return $parsedData; }
//our display function function displayData(Array $data) { foreach ( $data as KaTeX parse error: Expected '}', got 'EOF' at end of input: … cleaned_title = htmlentities (
l
i
n
k
[
′
t
i
t
l
e
′
]
,
E
N
T
Q
U
O
T
E
S
,
"
U
T
F
−
8
"
)
;
link ['title'], ENT_QUOTES, "UTF-8" );
link[′title′],ENTQUOTES,"UTF−8"); cleaned_href = htmlentities ( $link [‘href’], ENT_QUOTES, “UTF-8” ); echo “
” . $cleaned_title . “\n”; echo $cleaned_href . “\n”;
}
}
?>`
在清单 10-11 的中,我们将原始数据加载到一个DOMDocument对象中。然后我们调用loadHTML并使用 PHP 的错误抑制操作符@。
注意通常我们不使用错误抑制,因为它会妨碍调试。然而,在这种情况下,它隐藏了许多我们不关心的 DOMDocument 警告。
然后我们使用DOMXPath来查找文档链接和相应的文本,并将它们存储到一个数组中。由于数据来自外部,我们不应该相信它。在将输出打印到屏幕上之前,我们对所有的值进行了转义。这是防止跨站脚本的最佳实践,这在第十一章:安全性中有所涉及。
以下是运行清单 10-11 的示例输出:
`TEAMS
http://www.nhl.com/ice/teams.htm#?nav-tms-main
Chicago Blackhawks
http://blackhawks.nhl.com
Columbus Blue Jackets
http://bluejackets.nhl.com
Detroit Red Wings
http://redwings.nhl.com`
我们现在将展示 phpQuery 库如何允许我们使用类似于 jQuery 的选择器和符号(参见清单 10-12 )。这简化了我们的抓取脚本的解析步骤。您首先需要从[code.google.com/p/phpquery/](http://code.google.com/p/phpquery/)下载 phpQuery 库。
***清单 10-12。*使用 cURL 和 phpQuery 查找网页上的链接
`
$url = “http://www.nhl.com”; $rawHTML = fetchRawData ( $url ); $parsedData = parseSpecificData ( $rawHTML ); displayData ( $parsedData );
//our fetching function function fetchRawData(KaTeX parse error: Expected '}', got 'EOF' at end of input: url) { ch = curl_init (); curl_setopt ( $ch, CURLOPT_URL, $url ); curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true ); //return the output as a variable curl_setopt ( $ch, CURLOPT_FAILONERROR, true ); //fail if error encountered curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, true ); //allow redirects curl_setopt (
c
h
,
C
U
R
L
O
P
T
T
I
M
E
O
U
T
,
10
)
;
/
/
t
i
m
e
o
u
t
l
e
n
g
t
h
‘
‘
ch, CURLOPT_TIMEOUT, 10 ); //time out length` `
ch,CURLOPTTIMEOUT,10);//timeoutlength‘‘ data = curl_exec ( $ch ); if (! $data) { echo “cURL error:\n”; echo “#” . curl_errno ( $ch ) . “\n”; echo curl_error ( $ch ) . “\n”; echo “Detailed information:”; var_dump ( curl_getinfo ( $ch ) ); die (); }
curl_close ( $ch ); return $data; }
//our parsing function function parseSpecificData(KaTeX parse error: Expected '}', got 'EOF' at end of input: … {** **parsedData = array (); phpQuery::newDocumentHTML ( $data ); foreach ( pq ( “a” ) as KaTeX parse error: Expected '}', got 'EOF' at end of input: … **title = pq (
l
i
n
k
)
−
>
t
e
x
t
(
)
;
∗
∗
∗
∗
i
f
(
link )->text ();** **if (
link)−>text();∗∗ ∗∗if(title) { $parsedData [] = array (“title” => $title, “href” => pq ( $link )->attr ( ‘href’ ) ); } } return $parsedData; }
//our display function function displayData(Array $data) { foreach ( $data as KaTeX parse error: Expected '}', got 'EOF' at end of input: … cleaned_title = htmlentities (
l
i
n
k
[
′
t
i
t
l
e
′
]
,
E
N
T
Q
U
O
T
E
S
,
"
U
T
F
−
8
"
)
;
link ['title'], ENT_QUOTES, "UTF-8" );
link[′title′],ENTQUOTES,"UTF−8"); cleaned_href = htmlentities ( $link [‘href’], ENT_QUOTES, “UTF-8” ); echo “
” . $cleaned_title . “\n”; echo $cleaned_href . “\n”;
}
}
?>`
注意,从清单 10-11 到清单 10-12 ,只有我们的解析函数发生了变化。为了直接使用phpQuery而不是DOMDocument,我们称之为newDocumentHTML方法:
phpQuery::newDocumentHTML($data);
这里不包括 phpQuery 库的全部内容。相反,我们将比较示例中使用的选择器的 XPath、phpQuery 和 jQuery 符号(表 10-1 )。
谷歌地图整合
为了使用 Google Maps,我们将使用位于[code.google.com/p/php-google-map-api](http://code.google.com/p/php-google-map-api) /的 php-google-map-api 库。当前版本 3.0 的直接下载包目前不可用。您需要使用 subversion 客户机来签出源代码,命令如下:
svn checkout http://php-google-map-api.googlecode.com/svn/trunk/
两个 svn 客户端分别是在tortoisesvn.net/downloads.html可用的 tortoiseSVN 和在www.sliksvn.com/en/download可用的 slik svn。
php-google-map-api 库正在积极开发,功能丰富。我们将定义一个样板模板,我们的示例脚本将输出到这个模板中(清单 10-13 )。
***清单 10-13。*我们的样板模板,gmap_template.php
` getHeaderJS(); echo $gmap->getMapJS(); ?> printOnLoad(); echo $gmap->printMap(); echo $gmap->printSidebar(); ?> `
在我们的第一个例子中,我们将显示一个只有一个标记的 Google 地图。参见清单 10-14 。
***清单 10-14。*谷歌地图卫星图像,单一标记示例
`
$gmap = new GoogleMapAPI(); $gmap->addMarkerByAddress( “Eiffel Tower, Paris, France”, “Eiffel Tower Title”, “Eiffel Tower Description” ); require_once(‘gmap_template.php’); ?>`
正如你所看到的,用库显示谷歌地图非常容易。在清单 10-14 中,我们创建了一个新的GoogleMapAPI对象并标记了一个地址。方法addMarkerByAddress将标题和描述作为附加参数。结果如图图 10-6 所示。
***图 10-6。*标记艾菲尔铁塔的谷歌地图
在清单 10-15 的中,我们将展示一张地图,而不是卫星图像。我们还将设置默认缩放级别,并将交通路线显示为叠加图。结果如图 10-7 中所示。
***清单 10-15。*谷歌地图交通路线叠加示例
`
$gmap = new GoogleMapAPI();
g
m
a
p
−
>
a
d
d
M
a
r
k
e
r
B
y
A
d
d
r
e
s
s
(
"
N
e
w
Y
o
r
k
,
N
Y
"
,
"
N
e
w
Y
o
r
k
T
r
a
f
f
i
c
"
,
"
T
r
a
f
f
i
c
d
e
s
c
r
i
p
t
i
o
n 拼多多帮助力入口
h
e
r
e
"
)
;
∗
∗
gmap->addMarkerByAddress( "New York, NY", "New York Traffic", "Traffic description here" ); **
gmap−>addMarkerByAddress("NewYork,NY","NewYorkTraffic","Trafficdescriptionhere");∗∗gmap->setMapType( ‘map’ );**
g
m
a
p
−
>
s
e
t
Z
o
o
m
L
e
v
e
l
(
15
)
;
∗
∗
∗
∗
gmap->setZoomLevel( 15 );** **
gmap−>setZoomLevel(15);∗∗∗∗gmap->enableTrafficOverlay(); require_once(‘gmap_template.php’); ?>`
***图 10-7。*谷歌地图显示纽约交通路线
对于最后一个例子,我们将在同一张地图上放置几个标记。我们还将把地图类型设置为地形。参见清单 10-16 ,其结果显示在图 10-8 中。
***清单 10-16。*谷歌地图地形,多个标记示例
`
g
m
a
p
=
n
e
w
G
o
o
g
l
e
M
a
p
A
P
I
(
)
;
∗
∗
gmap = new GoogleMapAPI(); **
gmap=newGoogleMapAPI();∗∗gmap->addMarkerByAddress( “Saskatoon, SK”, “”, “Home” );**
g
m
a
p
−
>
a
d
d
M
a
r
k
e
r
B
y
A
d
d
r
e
s
s
(
"
V
a
n
c
o
u
v
e
r
,
B
C
"
,
"
"
,
"
W
e
s
t
C
o
a
s
t
"
)
;
∗
∗
∗
∗
gmap->addMarkerByAddress( "Vancouver, BC", "", "West Coast" );** **
gmap−>addMarkerByAddress("Vancouver,BC","","WestCoast");∗∗∗∗gmap->addMarkerByAddress( “Montreal, QC”, “”, “Hockey” );
g
m
a
p
−
>
a
d
d
M
a
r
k
e
r
B
y
A
d
d
r
e
s
s
(
"
P
l
a
y
a
d
e
l
C
a
r
m
e
n
,
M
e
x
i
c
o
"
,
"
"
,
"
T
r
o
p
i
c
a
l
v
a
c
a
t
i
o
n
"
)
;
∗
∗
∗
∗
gmap->addMarkerByAddress( "Playa del Carmen, Mexico", "", "Tropical vacation" );** **
gmap−>addMarkerByAddress("PlayadelCarmen,Mexico","","Tropicalvacation");∗∗∗∗gmap->setMapType( ‘terrain’ );
require_once(‘gmap_template.php’); ?>`
***图 10-8。*谷歌地图显示地形和多个标记
电子邮件和短信
PHP 有一个内置函数mail,用来发送电子邮件。然而,对于更复杂的服务器或电子邮件设置,外部库支持以更容易的面向对象方式创建邮件。PHPMailer 库让我们可以轻松地发送电子邮件和短信。PHPMailer 可以在http://sourceforge. net/projects/phpmailer/files/phpmailer%20for%20php5_6/下载。
清单 10-17 显示了 PHPMailer 库的基本用法。
***清单 10-17。*基本邮件使用
`
$mail = new PHPMailer(); //default is to use the PHP mail function
$mail->From = “from@foobar.com”; $mail->AddAddress( “to@foobar.net” );
$mail->Subject = “PHPMailer Message”; $mail->Body = “Hello World!\n I hope breakfast is not spam.”;
if( $mail->Send() ) { echo ‘Message has been sent.’; } else { echo ‘Message was not sent because of error:’; echo $mail->ErrorInfo; } ?>`
注意如果您收到错误消息“Could not instantiate mail function,”,那么很可能是因为From电子邮件地址在您发送邮件的服务器上无效。
接下来,我们将演示如何发送 HTML 格式的消息和附件(清单 10-18 )。
***清单 10-18。*发送带有附件的 HTML 格式的消息
`
$mail = new PHPMailer(); //default is to use the PHP mail function
$mail->From = “from@foobar.com”;
m
a
i
l
−
>
A
d
d
A
d
d
r
e
s
s
(
"
t
o
@
f
o
o
b
a
r
.
n
e
t
"
)
;
‘
‘
mail->AddAddress( "to@foobar.net" );` `
mail−>AddAddress("to@foobar.net");‘‘mail->Subject = “PHPMailer Message”;
m
a
i
l
−
>
I
s
H
T
M
L
(
)
;
/
/
t
e
l
l
P
H
P
M
a
i
l
e
r
t
h
a
t
w
e
a
r
e
s
e
n
d
i
n
g
H
T
M
L
∗
∗
∗
∗
mail->IsHTML(); //tell PHPMailer that we are sending HTML** **
mail−>IsHTML();//tellPHPMailerthatwearesendingHTML∗∗∗∗mail->Body = “Hello World! I hope breakfast is not spam.”;
//fallback message in case their mail client does not accept HTML KaTeX parse error: Undefined control sequence: \n at position 30: …= "Hello World!\̲n̲ ̲I hope breakfas…mail->AddAttachment( “document.txt” );
if( $mail->Send() ) { echo ‘Message has been sent.’; } else { echo ‘Message was not sent because of error:’; echo $mail->ErrorInfo; } ?>`
在清单 10-19 中,我们将使用带认证的 SMTP 服务器。我们还将遍历一组电子邮件地址和名称来发送批量电子邮件。
清单 10-19。 PHPMailer 用 SMTP 发送批量邮件
`
error_reporting(E_ALL); require(“phpmailer/class.phpmailer.php”);
$mail = new PHPMailer();
m
a
i
l
−
>
I
s
S
M
T
P
(
)
;
/
/
u
s
i
n
g
S
M
T
P
∗
∗
∗
∗
mail->IsSMTP(); //using SMTP** **
mail−>IsSMTP(); //usingSMTP∗∗∗∗mail->Host = “smtp.example.com”; // SMTP server
//authenticate on the SMTP server
m
a
i
l
−
>
S
M
T
P
A
u
t
h
=
t
r
u
e
;
∗
∗
∗
∗
mail->SMTPAuth = true;** **
mail−>SMTPAuth=true;∗∗∗∗mail->Username = “brian”; $mail->Password = “briansPassword”;
$mail->From = “from@foobar.com”; $mail->Subject = “PHPMailer Message”;
$names = array( array( “email” => “foobar1@a.com”, “name” => “foo1” ), array( “email” => “foobar2@b.com”, “name” => “foo2” ), array( “email” => “foobar3@c.com”, “name” => “foo3” ), array( “email” => “foobar4@d.com”, “name” => “foo4” ) ); foreach ( $names as KaTeX parse error: Expected '}', got 'EOF' at end of input: n ) {** mail->AddAddress(
n
[
′
e
m
a
i
l
′
]
)
;
∗
∗
n['email'] );**
n[′email′]);∗∗ mail->Body = “Hi {$n[‘name’]}!\n Do you like my SMTP server?”; if( $mail->Send() ) { echo ‘Message has been sent.’; } else { echo ‘Message was not sent because of error:’; echo KaTeX parse error: Expected 'EOF', got '}' at position 22: …ErrorInfo; }̲ mail->ClearAddresses(); } ?>`
在我们最后一个使用 PHPMailer 库的例子中,我们将发送一条短消息服务(SMS)消息。SMS 消息通常被称为文本消息或文本。要发送短信,我们需要知道收件人的电话号码和提供商。从提供商那里,我们需要知道 SMS 域。
***清单 10-20。*使用 PHPMailer 发送短信
`
error_reporting(E_ALL); require(“phpmailer/class.phpmailer.php”); define( ‘MAX_SMS_MESSAGE_SIZE’, 140 );
$mail = new PHPMailer();
$mail->IsSMTP(); $mail->Host = “smtp.example.com”; $mail->SMTPAuth = true; $mail->Username = “brian”; $mail->Password = “briansPassword”;
$mail->From = “from@foobar.com”; $mail->Subject = “PHPMailer Message”;
KaTeX parse error: Expected 'EOF', got '#' at position 35: … 555 kfla555-@#̲1122";** **clean_phone_number = filter_var(
p
h
o
n
e
n
u
m
b
e
r
,
F
I
L
T
E
R
S
A
N
I
T
I
Z
E
N
U
M
B
E
R
I
N
T
)
;
∗
∗
∗
∗
/
/
+
555555
−
1122
∗
∗
∗
∗
phone_number, FILTER_SANITIZE_NUMBER_INT );** **//+555555-1122** **
phonenumber,FILTERSANITIZENUMBERINT);∗∗∗∗//+555555−1122∗∗∗∗cleaner_phone_number = str_replace( array( ‘+’ , ‘-’ ), ‘’, $clean_phone_number ); //5555551122
$sms_domain = “@sms.fakeProvider.com”;
//5555551122@fake.provider.com $mail->AddAddress( $cleaner_phone_number .
s
m
s
d
o
m
a
i
n
)
;
∗
∗
∗
∗
sms_domain );** **
smsdomain);∗∗∗∗mail->Body = “Hi recipient!\r\n here is a text”; if ( strlen( $mail->Body ) < MAX_SMS_MESSAGE_SIZE ) { if ( $mail->Send() ) { echo ‘Message has been sent.’; } else { echo ‘Message was not sent because of error:’; echo $mail->ErrorInfo; } } else { echo “Your message is too long.”; } ?>`
在清单 10-20 中,我们首先确保我们的电话号码只包含数字。我们使用filter_var去掉除了数字、加号和减号之外的所有字符。然后,我们使用str_replace删除任何加号或减号。我们还定义了一个最大字符串长度,并确保我们的身体小于这个限制。我们将清除的电话号码与我们的 SMS 域连接起来,并将其用作发送 SMS 消息的地址。
注意大多数短信提供商要求号码长度为十位数,不带标点符号。这意味着该数字不包括国家代码。您可能希望添加验证,确认清除的数字长度为十位数。
gChartPHP:一个谷歌图表 API 包装器
Google Chart API 是一个非常容易使用的非常强大的库,可以生成动态图形和图表。gChartPHP 包装器以面向对象的方式抽象出 API 所需的精确语法。这使得它更容易使用,更不容易出错。有了 Chart API,Google 就可以生成图像,从而减轻服务器的负担。您可以在[code.google.com/p/gchartphp/](http://code.google.com/p/gchartphp/)下载 API 包装器。有关 Google Chart API 的更多信息,请访问[code.google.com/apis/chart/](http://code.google.com/apis/chart/)。
Google Chart API 可以生成以下类型的图表:折线图、条形图、饼图、地图、散点图、维恩图、雷达图、二维码图、google-o-meter、复合图、烛台图和 GraphViz 。我们将展示如何生成地图和蜡烛图。
地图就像谷歌分析中的地图。我们要标记的国家在两个颜色值的渐变范围之间着色。我们分配给一个国家的数据决定了该国接受的阴影级别。这有助于显示在我们绘制的统计数据中具有更大权重的国家或地区。参见清单 10-21 。
***清单 10-21。*显示部分欧洲国家的彩色地图
`
error_reporting(E_ALL); require_once (‘GChartPhp/gChart.php’);
$map = new gMapChart();
$map->setZoomArea( ‘europe’ ); //geographic area //italy, sweden, great britain, spain, finland
m
a
p
−
>
s
e
t
S
t
a
t
e
C
o
d
e
s
(
a
r
r
a
y
(
′
I
T
′
,
′
S
E
′
,
′
G
B
′
,
′
E
S
′
,
′
F
I
′
)
)
;
‘
‘
map->setStateCodes( array( 'IT', 'SE', 'GB', 'ES', 'FI') );` `
map−>setStateCodes(array(′IT′,′SE′,′GB′,′ES′,′FI′));‘‘map->addDataSet( array( 50, 100, 24, 80, 65 ) ); //level of shading in gradient $map->setColors( ‘E7E7E7’, //default array(‘0077FF’, ‘000077’) //gradient color range ); echo “getUrl() . “” />Europe"; ?>`
在清单 10-21 中,我们构造了一个**gMapChart**对象并放大到欧洲。然后我们添加一些国家代码。这些缩写的列表可以在网上的[en.wikipedia.org/wiki/ISO_3166-1_alpha-2](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)找到。我们为每个国家代码设置相应的数据。如果我们希望所有的国家都是相同的颜色,那么将所有的值设置为相等。接下来,我们设置颜色。我们的渐变范围从浅蓝绿色到深蓝色。最后,我们将 URL 直接输出到一个图像标签中。图 10-9 显示了用谷歌图表 API 生成的地图。
注意在执行GET请求时,我们受到查询长度的限制。Google Chart API 和包装器确实有发送POST请求的方法。其中一种方法就是使用renderImage(true)。
***图 10-9。*用谷歌海图 API 生成的地图
我们的第二个也是最后一个例子将展示如何制作蜡烛图。蜡烛图需要至少四个数据系列,通常用于描绘股票市场数据。参见图 10-10 。
***图 10-10。*烛台标记
在蜡烛线标记中,股票开盘和收盘之间的区域被称为“主体”或“真实主体”高低“灯芯”也被称为“影子”,显示一天中最高和最低的股票价格。清单 10-22 产生了一个烛台风格的图表。
***清单 10-22。*代码生成一个Candlestic样式的图表
`
error_reporting(E_ALL); require_once (‘GChartPhp/gChart.php’);
$candlestick = new gLineChart( 400, 400 );
//the regular line graph of close prices //32 pts $candlestick->addDataSet( array( 90, 70, 60, 65, 75, 85, 70, 75, 80, 70, 75, 85, 100, 105, 100, 95, 80, 70, 65, 35, 30, 45, 40, 50, 40, 40, 50, 60, 70, 75, 80, 75 ));
//the candlestick markers. the close price is the same as our line graph
c
a
n
d
l
e
s
t
i
c
k
−
>
a
d
d
H
i
d
d
e
n
D
a
t
a
S
e
t
(
a
r
r
a
y
(
100
,
95
,
80
,
75
,
85
,
95
,
90
,
95
,
90
,
85
,
85
,
105
,
110
,
120
,
110
,
110
,
105
,
90
,
75
,
85
,
45
,
55
,
50
,
70
,
55
,
50
,
55
,
65
,
80
,
85
,
90
,
85
)
)
;
/
/
h
i
g
h
‘
‘
candlestick->addHiddenDataSet( array( 100, 95, 80, 75, 85, 95, 90, 95, 90, 85, 85, 105, 110, 120, 110, 110, 105, 90, 75, 85, 45, 55, 50, 70, 55, 50, 55, 65, 80, 85, 90, 85 )); //high` `
candlestick−>addHiddenDataSet( array(100,95,80,75,85,95,90,95, 90,85,85,105,110,120,110,110, 105,90,75,85,45,55,50,70, 55,50,55,65,80,85,90,85));//high‘‘candlestick->addHiddenDataSet( array( 80, 90, 70, 60, 65, 75, 85, 70, 75, 80, 70, 75, 85, 100, 105, 100, 95, 80, 70, 65, 35, 30, 45, 40, 50, 45, 40, 50, 60, 70, 75, 80 )); //open $candlestick->addHiddenDataSet( array( 90, 70, 60, 65, 75, 85, 70, 75, 80, 70, 75, 85, 100, 105, 100, 95, 80, 70, 65, 35, 30, 45, 40, 50, 40, 40, 50, 60, 70, 75, 80, 75 )); //close $candlestick->addHiddenDataSet( array( 65, 65, 50, 50, 55, 65, 65, 65, 70, 50, 65, 75, 80, 90, 90, 85, 60, 60, 55, 30, 25, 20, 30, 30, 30, 25, 30, 40, 50, 55, 55, 55 )); //low
$candlestick->addValueMarkers( ‘F’, //line marker type is candlestick ‘000000’, //black color 1, //start with “high” data series ‘1:’, //do not show first marker 5 //marker width ); $candlestick->setVisibleAxes( array( ‘x’, ‘y’ ) ); //both x and y axis $candlestick->addAxisRange( 0, 0, 32 ); //x-axis $candlestick->addAxisRange( 1, 0, 110 ); //y-axis
echo “getUrl() . “” />Stock market report"; ?>`
在清单 10-22 中,我们构造了一个gLineChart对象。然后,我们定义将用于烛台的线数据集和四个隐藏数据集。接下来,我们添加烛台标记。最后,我们设置一些轴信息并显示我们生成的图像。清单 10-22 的输出如图 10-11 中所示。
***图 10-11。*运行清单 10-22 输出一个股市蜡烛图
总结
在这一章中,我们展示了很多 PHP 库和它们的用法。通过这样做,我们展示了如何使用现有的解决方案是非常有益的。我们使用包装器来集成 Google Maps 和 Google Chart API。我们解析了 RSS 提要并搜集了网站数据。我们生成了 pdf、电子邮件和短信。
使用现有的库使我们能够在高层次上快速开发,抽象出低层次的细节。另一方面,我们无法控制第三方代码。我们必须相信它不是恶意的或错误的。
作为程序员,编写自己的库可能很有诱惑力,因为现有的选项缺少一些功能或者不符合您的标准。然而,这样做通常会浪费大量的时间和精力。通常,更好的办法是参与现有开源库的补丁、错误修复和特性请求。
十一、安全
在编写网页时,考虑安全性是非常重要的。攻击者会试图利用许多潜在的站点漏洞。一个好的 PHP 开发人员需要保持勤奋,并且了解最新的安全实践。在这一章中,我们将介绍一些强化我们网站的最佳实践和技术。
本章的一个关键思想是永远不要相信数据或用户的意图。我们需要过滤和转义的用户数据可能来自多个来源,比如 URL 查询字符串、表单数据、
C
O
O
K
I
E
S
、
_COOKIES、
COOKIES、_SESSION、$_SERVER 数组和 Ajax 请求。
我们还将讨论常见的攻击及其预防,包括以下主题:
通过输出转义防止跨站点脚本(XSS)使用隐藏表单令牌防止跨站点请求伪造(CSRF)通过不将会话 ID (SID)存储在 cookie 中并在每页开始时重新生成 SID 来防止会话固定使用预准备语句和 PDO 预防 SQL 注入使用筛选器扩展
我们还将讨论如何巩固我们的php.ini和服务器设置,并涵盖密码散列强度。
永远不要相信数据
在电视连续剧《X 档案》中,福克斯·莫特说过一句名言:“不要相信任何人。”说到 web 编程,我们应该遵循这个建议。假设最坏的情况:所有数据都被污染了。Cookies、Ajax 请求、头和表单值(甚至使用 POST)都可能被欺骗或篡改。即使用户可以被完全信任,我们仍然希望确保表单字段被正确填写,并防止出现格式错误的数据。所以要过滤所有输入,转义所有输出。在本章的后面,我们将会看到一些新的 PHP 过滤函数,它们使得这个过程变得更加容易。
我们还将讨论如何配置php.ini来提高安全性。然而,如果我们编写一个代码库供公众使用,那么我们不能确保最终开发者遵循了他们的php.ini文件中的最佳实践。由于这个原因,我们应该总是防御性地编码,并假设php.ini文件没有被收紧。
注册 _ 全局
最佳实践是始终初始化变量。这是针对当在php.ini中打开register_globals指令时可能出现的攻击的一种保护措施。启用register_globals后,$_POST和$_GET变量被注册为脚本中的全局变量。如果在脚本中添加一个查询字符串,比如"?foobar=3",PHP 会在后台创建一个同名的全局变量:
$foobar = 3; //register_globals declares this global variable for you.
当register_globals被启用并且 URL 被设置为[foobar.com/login.php?is_admin=true](http://foobar.com/login.php?is_admin=true)时,清单 11-1 中的脚本将总是被授予管理员权限。
清单 11-1。【login.php】绕过安全检查的 register _ globals】
`
//$is_admin =
G
E
T
[
′
i
s
a
d
m
i
n
′
]
i
n
i
t
i
a
l
i
z
e
d
b
y
r
e
g
i
s
t
e
r
g
l
o
b
a
l
s
/
/
_GET['is_admin'] initialized by register globals //
GET[′isadmin′] initializedbyregisterglobals //is_admin = true; current value passed in
if ( user_is_admin( KaTeX parse error: Expected '}', got 'EOF' at end of input: … is_admin = true; }
if ( $is_admin ) { //will always be true //give the user admin privileges } … ?>`
攻击者必须猜出$is_admin变量的正确名称,攻击才会成功。或者,如果正在使用一个已知的库,攻击者可以通过研究 API 或库的完整源代码很容易地找到变量名。防止这种攻击的关键是初始化所有变量,如清单 11-2 所示。这确保了register_globals不能覆盖现有的变量。
***清单 11-2。*启动变量以防止 register_globals 滥用
`
G
E
T
[
′
i
s
a
d
m
i
n
′
]
i
n
i
t
i
a
l
i
z
e
d
b
y
r
e
g
i
s
t
e
r
g
l
o
b
a
l
s
/
/
_GET['is_admin'] initialized by register globals //
GET[′isadmin′] initializedbyregisterglobals //is_admin = true; current value passed in $is_admin = false; //defensively set to override //initial value set by register globals if ( user_is_admin( KaTeX parse error: Expected '}', got 'EOF' at end of input: … is_admin = true; }
if ( $is_admin ) { //this will only be true now //if the user_is_admin function returns true //give the user admin privileges } … ?>`
白名单和黑名单
我们不应该对include或require函数调用使用$_GET或$_POST值。这是因为文件名对我们来说是未知的。攻击者可能试图通过在文件名前加上类似"../../"的字符串来绕过文档根限制。对于include和require调用中的变量,我们应该有一个可接受文件名的白名单,或者对文件名进行净化。
注意白名单是被批准的项目的列表。相反,黑名单是不允许的项目列表。白名单比黑名单更严格,因为它们明确规定了什么是被批准的。黑名单需要不断更新才能生效。
白名单的例子有可接受的电子邮件地址、域名或 HTML 标签。黑名单的示例包括不允许的电子邮件地址、域名或 HTML 标记。
清单 11-3 展示了如何接受可接受文件名的白名单。
***清单 11-3。*通过使用可接受文件名的白名单来限制包含文件
对于我们的脚本打开的文件,basename函数可以帮助确保所包含的文件不会超出我们的文档根目录。
对于由用户提供并使用file_get_contents检索的外部 URL,我们需要过滤文件名。我们可以使用parse_url函数提取 URL 并删除查询字符串,或者使用FILTER_SANITIZE_URL和FILTER_VALIDATE_URL来确保一个合法的 URL。我们将在本章后面讨论使用过滤器。
表格数据
大多数读者都知道,用 HTTP GET 方法提交的表单域可以通过直接修改 URL 查询来修改。这通常是期望的行为。例如,[stackoverflow.com](http://stackoverflow.com)的搜索表单可以单独使用查询来提交。见清单 11-4 。
***清单 11-4。*通过直接修改 URL 查询来搜索stackoverflow.com
http://stackoverflow.com/search?q=php+xss
搜索表单的实际标记如清单 11-5 所示。
***列表 11-5。*查询表
`