curl 的几个例子

Your first Curl scripts

From Practical PHP Programming

resource curl_init ( [string url])

bool curl_setopt ( resource curl_handle, string option, mixed value)

mixed curl_exec ( resource curl_handle)

mixed curl_close ( resource curl_handle)

The first Curl script we are going to look at is the simplest Curl script that is actually useful – it will load a web page, retrieve the contents, then print it out. So, keeping the four-step Curl process in mind, this equates to:

  1. Initialise Curl
  2. Set URL we want to load
  3. Retrieve and print the URL
  4. Close Curl

Here is how that looks in PHP code:

<?php
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, "http://www.php.net");
curl_exec ($curl);
curl_close ($curl);
?>

Thanks to PHP being such a straightforward language, there is actually a one-to-one mapping of steps to lines of code – that is, step 1, “Initialise Curl”, is done by line one, “$curl = curl_init() ;”, etc. There are four functions in that simple script, which are curl_init() , for initialising the Curl library, curl_setopt() , for setting Curl options, curl_exec() , for executing the Curl query, and curl_close() , for shutting down the Curl system. As mentioned already, of these four only the second is complicated – the rest stay as you see them. Curl’s functionality is, for the most part, largely manipulated through repeated calls to curl_setopt() , and it is this that distinguishes how Curl operates.

The curl_init() function returns a Curl instance for us to use in later functions, and you should always store it for later. It has just one optional parameter: if you pass a string into curl_init() , it will automatically use that string as the URL to work with. In the script above, we use curl_setopt() to do that for clarity, but it is all the same.

Curl_setopt() takes three parameters, which are the Curl instance to use, a constant value for the setting you want to change, and the value you want to use for that setting. There are a huge number of constants you can use for settings, and many of these are listed shortly. In the example we use CURLOPT_URL, which is used to set the URL for Curl to work with, and so the working URL is set to the third parameter – elementary, really.

Calling curl_exec() means, “We’re finished setting our options, go ahead and do it”, and you need to pass precisely one parameter: the Curl resource to use. The return value of curl_exec() is true/false by default, although we will be changing that soon.

The final function, curl_close() , takes a Curl resource as its only parameter, closes the Curl session, then frees up the associated memory.

Now, to improve on the previous script, it would be good if we actually had some control over the output of our retrieved HTML page. As it is, calling curl_exec() retrieves and outputs the page, but it would be nice to have the retrieved content stored in a variable somewhere for use when we please. There are two ways of doing this. We already looked at how output buffering, and more specifically the ob_get_contents() function, allows you to catch output before it gets to your visitor and manipulate it as you want. While this might seem like a good way to solve the problem, the second way is even better: Curl has an option specifically for it.

Passing CURLOPT_RETURNTRANSFER to curl_setopt() as parameter two and 1 as parameter three will force Curl not to print out the results of its query. Instead, it will return the results as a string return value from curl_exec() instead of the usual true/false. Note that if there is an error, false will still be the return value from curl_exec() .

Capturing the return value from curl_exec() looks like this in code:

<?php
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, "http://www.php.net");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec ($curl);
curl_close ($curl);
print $result;
?>

That script will output the same as the previous script, but having the web page stored in a variable before printing gives us more flexibility – we could have manipulated the data in any number of ways before printing.

Storing data in a variable is fine, but it would be much better to store it in a file, right? While we could achieve this using the file_put_contents() function, yet again Curl has an option to do the work for us. This time it is CURLOPT_FILE, which takes a file handle as its third parameter. We looked at file handles earlier, and it works the same here – we will use fopen() to open a file as writeable. Therefore, this time the script looks like this:

<?php
$curl = curl_init();
$fp = fopen("somefile.txt", "w");
curl_setopt ($curl, CURLOPT_URL, "http://www.php.net");
curl_setopt($curl, CURLOPT_FILE, $fp);

curl_exec ($curl);
curl_close ($curl);
?>

Again, just a minor change on the previous format, and there should be nothing surprising in there at all. Notice that I have taken out the lines for CURLOPT_RETURNTRANSFER and capturing the return value from curl_exec() , because these are not applicable here – the output from Curl is sent straight to the file “somefile.txt”.

Our next basic script is going to switch from HTTP to FTP so you can see how little difference there is. This next script connects to the GNU FTP server and gets a listing of the root directory there:

<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,"ftp://ftp.gnu.org");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec ($curl);
curl_close ($curl);
print $result;
?>

If you are thinking that looks just like the second script we looked at, you would be right – the output is different, and the protocol has changed, but this is all transparent through Curl. I hope that you are starting to get an idea of the power of Curl!

We could have made that script a little more FTP-specific by providing some FTP options to the script to make it more interesting. For example, the CURLOPT_FTPLISTONLY option will make PHP return much less information – if you tried the script without this you would have received read/write information for each of the files and directories, when they were last changed, etc. CURLOPT_FTPLISTONLY changes this so that you only get the file/directory names.

The second FTP option of interest is CURLOPT_USERPWD, which makes PHP use the third parameter to curl_setopt() as the username and password used for logging in. As the third parameter contains both the username and the password, you need to split them using a colon, like this: username:password. When logging onto the GNU FTP server, we want to use the anonymous FTP account reserved for guests – in this situation, you generally provide your email address as the password.

With both of these changes implemented, the new script looks like this:

<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,"ftp://ftp.gnu.org");
curl_setopt($curl, CURLOPT_FTPLISTONLY, 1);
curl_setopt($curl, CURLOPT_USERPWD, "anonymous:your@email.com");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec ($curl);
curl_close ($curl);
print $result;
?>

Try changing the username and password to random values, as this will cause the login to fail. If you run the script again, you will see nothing is printed out – no errors, no warnings; nothing. This is because Curl fails silently, and you need to request Curl’s error message explicitly using curl_error() . As with the other basic functions, this one takes just a Curl session handler as its only parameter, and returns the error message from Curl. So, with this in mind, here is our final FTP script:

<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,"ftp://ftp.gnu.org");
curl_setopt($curl, CURLOPT_FTPLISTONLY, 1);
curl_setopt($curl, CURLOPT_USERPWD, "foo:barbaz");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec ($curl);
echo curl_error($curl);
curl_close ($curl);
print $result;
?>

Note the bad username and password and the extra call to curl_error() after curl_exec() . As long as the GNU team don’t change their FTP permissions before you read this, running that script should output “Access denied: This FTP server is anonymous only.” Perfect!

The last simple Curl script we are going to look after before we go over a list of the most popular options for curl_setopt() shows how to send data out to the web as opposed to just retrieving it. This requires a little more work, but only a little!

First, create the file posttest.php in your web server’s public directory. Type into the file this code:

<?php
var_dump($_POST);
?>

That simply takes the HTTP POST data that has come in, and spits it back out again. Now, create this new script:

<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,"http://localhost/posttest.php");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, "Hello=World&Foo=Bar&Baz=Wombat");

curl_exec ($curl);
curl_close ($curl);
?>

If you are running your posttest.php file on a remote server, change “localhost” to the server URL. There are two new values for curl_setopt() in there, but otherwise the script should be clear.

The two new values, CURLOPT_POST and CURLOPT_POSTFIELDS, make our session prepare to send data over HTTP post and assign the data to send respectively. CURLOPT_POST just takes a 1 to enable to POST usage, but CURLOPT_POSTFIELDS needs a properly formatted data string to send. The string you use for the third parameter with CURLOPT_POSTFIELDS should be a list of the variables you want to send in the format Variable=Value, with each variable separated by an ampersand &. Thus, the above script sends three variables over: Hello, Foo, and Baz, with values World, Bar, and Wombat respectively.

Once the values are sent, Curl captures the response from the server, and prints it out directly. Our posttest.php script dumps what it got through HTTP POST, so your output should be this:

array(3) {
["Hello"]=>
string(5) "World"
["Foo"]=>
string(3) "Bar"
["Baz"]=>
string(6) "Wombat"
}

As you can see, our three variables were sent across perfectly, and the task really was not hard at all.

Author’s Note: The field data you pass in as the third parameter with CURLOPT_POSTFIELDS should not have any spaces or special characters in. Spaces should be replaced with %20 – you can have this and other special characters automatically replaced by using urlencode() on the string.

We have only looked at a few basic scripts, but it should be clear that Curl’s manner of making Internet protocols look easy is very helpful, and will let you add some advanced functionality to your scripts.

初学者学习PHP开发应该掌握的几段精华代码

初学者学习PHP开发应该掌握的几段精华代码

转于 :网页教学网
经典循环例子

<HTML>
<HEAD>
<TITLE>经典循环例子</TITLE>
</HEAD>
<BODY>
<?
for($counter = 1; $counter <= 6; $counter++)        //循环6次
{
print(“<B>counter is $counter</B><BR>\n”);    //打印6次
}    
?>
</BODY>
</HTML>



for的高级运用

<HTML>
<HEAD>
<TITLE>for的高级运用</TITLE>
</HEAD>
<BODY>
<?
/* 
** 打印必要的说明文字 
*/
print(“<B>距离星期一还有几天?</B>\n”);
print(“<OL>\n”);
for($currentDate = date(“U”);             //定义$currentDate时间格式
date(“l”, $currentDate) != “Monday”;     //判断是不是当前系统时间是Monday
$currentDate += (60 * 60 * 24))        //当前时间加上1天
{
/* 
** 打印时间名称 
*/
print(“<LI>” . date(“l”, $currentDate) . “\n”);
}

print(“</OL>\n”);
?>
</BODY>
</HTML>


函数的简单调用:

<HTML>
<HEAD>
<TITLE>简单的函数</TITLE>
</HEAD>
<BODY>
<FONT SIZE=5>
<?
function printBold($inputText)            //定义function printBold()
{
print(“<B>” . $inputText . “</B>”);    ////打印$inputText
}
print(“这行没有加重!<BR>\n”);            //直接打印字符串
printBold(“这行加重了!!!”);            //调用function printBold()函数
print(“<BR>\n”);
print(“这行没有加重!<BR>\n”);            //直接打印字符串
?>
</FONT>
</BODY>
</HTML>

有返回值的函数

<HTML>
<HEAD>
<TITLE>有返回值的函数</TITLE>
</HEAD>
<BODY>
<FONT SIZE=5>
<?
function makeBold($inputText)        //定义function makeBold()函数
{
$boldedText = “<B>”;
$boldedText .= $inputText;
$boldedText .= “</B>”;
return($boldedText);        //返回变量$boldedText
}
print(“这行没有加重!!!<BR>\n”);    //直接打印字符串    
print(makeBold(“这行被加重了!!!”) . “<BR>\n”);//调用function makeBold()函数
print(“这行没有加重!!!<BR>\n”);    //直接打印字符串
?>
</SIZE>
</BODY>
</HTML>


有默认参数的函数

<HTML>
<HEAD>
<TITLE>有默认参数的函数</TITLE>
</HEAD>
<BODY>
<FONT SIZE=5>
<?
function printColored($Text, $Color=”black”)        //定义function函数
{
print(“<FONT COLOR=\”$Color\”>$Text</FONT>”);    //获取字符串的内容和颜色
}
printColored(“这是黑颜色的字!”);            //调用function函数
print(“<BR><BR>\n”);
printColored(“这是蓝颜色的字!”, “blue”);            //调用function函数
print(“<BR>\n”);
?>
</SIZE>
</BODY>
</HTML>


用的规算法判断是否是整数

<HTML>
<HEAD>
<TITLE>判断整数</TITLE>
</HEAD>
<BODY>
<?
function checkInteger($Number)
{
if($Number > 1)
{
/* 整数减1仍然是整数 */
return(checkInteger($Number-1));
}
elseif($Number < 0)
{
/* 对于一个负数,*/
/* 可以分析它的绝对值*/
return(checkInteger((-1)*$Number-1));//取绝对值,把负数按整数分析
}
else
{
if(($Number > 0) AND ($Number < 1))
{
return(“当然不是”);
}
else
{
/* 0 和 1 是整数       */
/* 根据相关数学定义 */
return(“是的”);
}
}
}
print(“<B>0是整数吗?</B>” . 
checkInteger(0) . “<BR>\n”);
print(“<B>7是整数吗?</B> ” . 
checkInteger(7) . “<BR>\n”);
print(“<B>3.5呢?</B>” . checkInteger(3.5) . “<BR>\n”);
print(“<B>那么-5呢?</B>” . checkInteger(-5) . “<BR>\n”);
print(“<B>还有-9.2?</B>” . checkInteger(-9.2) . “<BR>\n”);
?>
</BODY>
</HTML>

初始化数组

<HTML>
<HEAD>
<TITLE>初始化数组</TITLE>
</HEAD>
<FONT SIZE=5>
<?
$monthName = array(1=>”January”, “February”, “March”,//初始化一个数组
“April”, “May”, “June”, “July”, “August”,
“September”, “October”, “November”, “December”);
print(” 英语的“5月”是<B> $monthName[5] </B>。<BR>\n”);//打印数组中的第6个元素
?>
</FONT>
</BODY>
</HTML>

获取数组中的元素

<HTML>
<HEAD>
<TITLE>获取数组中的元素</TITLE>
</HEAD>
<?
$monthName = array(
/*定义$monthName[1]到$monthName[12]*/
1=>”January”, “February”, “March”,
“April”, “May”, “June”, 
“July”, “August”, “September”, 
“October”, “November”, “December”,
/*定义$monthName[“Jan”]到$monthName[“Dec”]*/
“Jan”=>”January”, “Feb”=>”February”,
“Mar”=>”March”, “Apr”=>”April”, 
“May”=>”May”, “Jun”=>”June”, 
“Jul”=>”July”, “Aug”=>”August”,
“Sep”=>”September”, “Oct”=>”October”, 
“Nov”=>”November”, “Dec”=>”December”,
/*定义$monthName[“Jan”]到$monthName[“Dec”]*/
“January”=>”January”, “February”=>”February”,
“March”=>”March”, “April”=>”April”, 
“May”=>”May”, “June”=>”June”, 
“July”=>”July”, “August”=>”August”,
“September”=>”September”, “October”=>”October”, 
“November”=>”November”, “December”=>”December”
);
/*打印相关的元素*/
print(“Month <B>5</B> is <B>” . $monthName[5]. “</B><BR>\n”);
print(“Month <B>Aug</B> is <B>” . $monthName[“Aug”] . “</B><BR>\n”);
print(“Month <B>June</B> is <B>” . $monthName[“June”] . “</B><BR>\n”);
?>
</BODY>
</HTML>

创建一个多维数组

<HTML>
<HEAD>
<TITLE>创建一个多维数组</TITLE>
</HEAD>
<?
$Cities = array(                //二维数组array()
“华北地区”=>array(
“北京市”,
“天津市”,
“石家庄”
),
“西北地区”=>array(
“西安”,
“拉萨”
)
);
print(“华北地区: “.$Cities[“华北地区”][0]);    //打印$Cities[“华北地区”][0]
?>
</BODY>
</HTML>

PHP 4.0实现表格状打印

<HTML>
<HEAD>
<TITLE>实现表格状打印</TITLE>
</HEAD>
<BODY>
<?
/* 
** 数据表格化 
*/

print(“<TABLE bgcolor=’ffccoo’ BORDER=\”1\”>\n”); // 表格开始


for($Row=1; $Row <= 12; $Row ++)
{
print(“<TR>\n”); // 开始行

// do each column
for($Column=1; $Column <= 12; $Column ++)
{
print(“<TD>”);//开始列
print($Row * $Column);//表格元素乘积
print(“</TD>”);
}

print(“</TR>\n”); // 行结束

}

print(“</TABLE>\n”); // 表格结束

?>
</BODY>
</HTML>


查看系统的一些变量

<HTML>
<HEAD>
<TITLE>查看PHP的环境变量</TITLE>
</HEAD>
<BODY>
<?
print(“你正在用文件的名字为: “);
print(__FILE__);
print(” <BR>\n”);
print(“<hr>”);
print(“你的操作系统为: “);
print(PHP_OS);
print(“<hr>”);
print(“你的php的版本为: “);
print(PHP_VERSION)
?>
</BODY>
</HTML>


打开本地或者远程文件

<HTML>
<HEAD>
<TITLE>打开本地或者远程文件</TITLE>
</HEAD>
<BODY>
<?
print(“<H3>通过http协议打开文件</H3>\n”);
// 通过 http 协议打开文件
if(!($myFile = fopen(“d:web/web/php/test/data.txt”, “r”)))
{
print(“文件不能打开”);
exit;
}
while(!feof($myFile))                //循环
{
// 按行读取文件中的内容
$myLine = fgetss($myFile, 255);
print(“$myLine <BR>\n”);
}
// 关闭文件的句柄
fclose($myFile);
?>
</BODY>
</HTML>

打开文件的几种方式比较

<HTML>
<HEAD>
<TITLE>读取文件内容</TITLE>
</HEAD>
<BODY>
<?
// 打开文件同时打印文件的每一个字符
if($myFile = fopen(“data.txt”, “r”))
{
while(!feof($myFile))
{
$myCharacter = fgetc($myFile);
print($myCharacter);
}
fclose($myFile);
}    
?>
<? print(“<hr>”);?>
<?
// 打开文件同时打印文件的每一行
if($myFile = fopen(“data.txt”, “r”))
{
while(!feof($myFile))
{
$myLine = fgets($myFile, 255);
print($myLine);
}
fclose($myFile);
}    
?>
<? print(“<hr>”);?>
<?
/* 打开文件同时打印文件的每一行,
同时去掉取回字符串中的 HTML 语言
*/
if($myFile = fopen(“data.txt”, “r”))
{
while(!feof($myFile))
{
$myLine = fgetss($myFile, 255);
print($myLine);
}
fclose($myFile);
}    
?>
</BODY>
</HTML>

访问文件常见属性

<HTML>
<HEAD>
<TITLE>访问文件常见属性</TITLE>
</HEAD>
<BODY>
<BR>
<?
print(“文件的所有者(UID 值):”);
print(fileowner(“data.txt”).”<br>”);
print(“文件的大小:”);
print(filesize(“data.txt”).”<br>”);
print(“文件的类型:”);
print(filetype(“data.txt”).”<br>”);
?>
</BODY>
</HTML>

调用文本文件内容

<HTML>
<HEAD>
<TITLE>调用文本文件内容</TITLE>
</HEAD>
<BODY>
<CENTER>
<?
// 打开文件同时,打印每一行
$myFile = file( “data.txt”);
for($index = 0; $index < count($myFile); $index++)
{
print($myFile[$index].”<BR>”);
}
?>
</CENTER>
</BODY>
</HTML>

创建目录函数

<HTML>
<HEAD>
<TITLE>创建目录函数</TITLE>
</HEAD>
<BODY>
<?
if(mkdir(“myDir1”, 0777))        //创建目录的函数
{
print(“目录创建成功”);        //目录建立成功
}
else
{
print(“目录建立失败!”);        //目录建立失败
}
?>
</BODY>
</HTML>

浏览目录

<HTML>
<HEAD>
<TITLE>浏览目录</TITLE>
</HEAD>
<BODY>
<?
// 使用表格浏览目录的结构
print(“<TABLE BORDER=\”1\”>\n”);
// 创建表格的头
print(“<TR><font color=’red’>\n”);
print(“<TH>文件名</TH>\n”);
print(“<TH>文件的大小</TH>\n”);
print(“</font></TR>\n”);
$myDirectory = opendir(“.”);        // 建立操作目录的句柄 
// 读出目录中的每一个子项
while($entryName = readdir($myDirectory))
{
print(“<TR>”);
print(“<TD>$entryName</TD>”);
print(“<TD ALIGN=\”right\”>”);
print(filesize($entryName));
print(“</TD>”);
print(“</TR>\n”);
}
closedir($myDirectory);            // 关闭目录
print(“</TABLE>\n”);
?>
</BODY>
</HTML>

PHP相关信息

<HTML>
<HEAD>
<TITLE>PHP相关信息</TITLE>
</HEAD>
<BODY>
<?
phpinfo();
?>
</BODY>
</HTML>

常用的数值判断函数

<HTML>
<HEAD>
<TITLE>常用的数值判断函数</TITLE>
</HEAD>
<BODY>
<?
//判断数组
$colors = array(“red”, “blue”, “green”);
if(is_array($colors))
{
print(“colors is an array”.”<br>”);
}
//双精度数判断
$Temperature = 15.23;
if(is_double($Temperature))
{
print(“Temperature is a double”.”<br>”);
}
//整数判断
$PageCount = 2234;
if(is_integer($PageCount))
{
print(“$PageCount is an integer”.”<br>”);
}
//对象判断
class widget
{
var $name;
var $length;
}
$thing = new widget;
if(is_object($thing))
{
print(“thing is an object”.”<br>”);
}
//字符判断
$Greeting = “Hello”;
if(is_string($Greeting))
{
print(“Greeting is a string”.”<br>”);
}
?>
</BODY>
</HTML>

文件上传界面

<HTML> 
<HEAD> 
<TITLE>文件上传界面</TITLE> 
</HEAD> 
<BODY><TABLE><CENTER> 
<? 
if($UploadAction){
$UploadAction=0; 
$TimeLimit=60;        
/*设置超时限制时间默认时间为 30s,设置为0时为不限时 */ 
set_time_limit($TimeLimit); 
If(($Upfile != “none”)&& 
($Upfile != “”)) 

$Filepath=”d:\web\web\php\test”;                            //上载文件存放路径
$FileName=$Filepath.$Upfile_name; 
if($Upfile_size <1024)                        //上载文件大小 
{$FileSize = (string)$Upfile_size . “字节”;} 
elseif($Upfile_size <(1024 * 1024)) 
{
$FileSize = number_format((double)($Upfile_size / 1024), 1) . ” KB”;

else 

$FileSize = number_format((double)($Upfile_size/(1024*1024)),1).”MB”; 

if(!file_exists($FileName)) 

if(copy($Upfile,$FileName)) 
{unlink($Upfile); 
echo “<br><br>\n”;         
echo “文件 $Upfile_name 已上载成功!”;
echo “<br><br>\n”;
echo “文件位置:$FileName”;
echo “<br><br>\n”;
echo “文件大小:$FileSize”;
echo “<br><br>\n”;

else 
{echo “文件 $Upfile_name上载失败!”; } 

else 
{echo “文件 $Upfile_name已经存在!”; } 

else 
{echo “你没有选择任何文件上载!”; } 
set_time_limit(30);                            //恢复默认超时设置 
}
?> 
<FORM ENCTYPE = “multipart/form-data” NAME = “SubmitForm” 
ACTION = “default.php” METHOD = “POST”> 
<INPUT TYPE = “hidden” NAME = “MAX_FILE_SIZE” VALUE =”1000000″> 
<INPUT TYPE = “hidden” NAME = “UploadAction” VALUE = “1”> 
<TR><TD><INPUT NAME = “Upfile” TYPE = “file” SIZE = “30”></TD> 
</TR><TR><TD><INPUT NAME = “submit” VALUE = “提交” TYPE = “submit”>
<INPUT NAME = “reset” VALUE = “重置” TYPE = “reset”></TD> 
</TR></FORM></CENTER></TABLE>
</BODY> 
</HTML>


pear 的安装

PEAR的安装
作者: EastSon

go-pear.org
go-pear.org是一个WEB站点,这个站点很特殊,里面就只有一个文件,只一个单独的PHP脚本,你可以下载并且执行它。这个文件将执行最近的稳定发行包。go-pear是交互平台,可以让你你在你的服务器上面用命令行来获得PEAR
PHP发行包里面有一个特殊的PEAR安装包,另一方面go-pear提供了一个最新稳定版的PEAR发行包。当然go-pear不知道你的目录结构,便可以计算出,来完成PEAR的安装过程。

前提:
因为go-pear是用PHP写的一个脚本,因此你必须在服务器上有一个PHP CGICLI程序来执行这个脚本。默认情况下CLI程序已经随着PHP模块安装了。试着运行php v 来看一下是否可用:

PHP 5.0.0 (cli), Copyright (c) 1997-2004 The PHP GroupZend Engine v2.0, Copyright (c) 1998-2004 Zend Technologies

注:在我的Windows平台上PHP5.1.6上面要使用php –v 来执行这个命令,下面有好多命令一样。
默认情况下php命令行程序在UNIX下安装于 /usr/local/bin Windows下安装于 C:\php 。在WindowsPHPCLI版程序也许叫做php-cli


得到PEAR
如果你的PHP安装包没有包含PEAR,你可以使用go-pear做为通程序来获得PEAR。前提是你需要一个已安装的GLICGI版本的PHP
你可以下载go-pear脚本并且执行它,像下面这样在命令行中执行:
$lynx source http://go-pear.org | php
这个脚本从http://go-pear.org获得脚本内容,并由PHP来执行。
如果你的系统上lynx无效,可以用其它的方法来直接获得go-pear:
$wget O- http://go-pear.org | php 使用GNUS wget
fetch o http://go-pear.org |php 使用fetchFreeBSD
GET http:/go-pear.org | php 使用Perl LWPGET工具。
Windows平台,你可以使用PHPURL流来获得,这个要求url_incluesphp.ini中没有被禁用。
C:\>php-cli r “include(‘http://go-pear.org’);”
还有一种就是直接用浏览器打开http://go-pear.org,把首页另存为go-pear.php然后在命令行中运行。
C:\php go-pear.php

输出也许像下面这样:

Welcome to go-pear!



Go-pear will install the ‘pear’ command and all the files needed by


it. This command is your tool for PEAR installation and maintenance.


Go-pear also lets you download and install the PEAR packages bundled


with PHP: DB, Net_Socket, Net_SMTP, Mail, XML_Parser, PHPUnit.


If you wish to abort, press Control-C now, or press Enter to continue:

注:在我的php5.1.6环境中,有一个c:\php下有go-pear.bat 我直接运行,出现选择systemlocal直接回车就行了。
按回车继续,出现下面的信息:

HTTP proxy (http://user:password@proxy.myhost.com:port), or Enter for none:

输入代理信息,如果直接上网,直接按回车就行了。
如果设置了HTTP代码环境,go-pear将检查你的http_proxy环境变量,并使用你指定的HTTPproxy来下载PEAR包,如果不是,只需要直接回车就可以了。
现在,到了最关键的地方:

Below is a suggested file layout for your new PEAR installation. To change individual locations, type the number in front of the directory. Type ‘all’ to change all of then, or simply press Enter toaccept these locations.
1.  Installation prefix          :/usr/local
2. Binaries directory : $prefix/bin
3. PHP code directory : $prefix/share/pear
4.  Documentation base directory : $php_dir/docs
5.  Data base directory          : $php_dir/data
6.  Tests base directory         : $php_dir/tests1-
6, ‘all’ or Enter to continue:

每一个设置都会设定一个值(prefix,bin_dir,php_dir,doc_dir,data_dir,test_dir )
下面是这些设置的说明:
Installation prefix 你安装PEAR的根目录。下面的五个选项将使用它作为根目录。
Binaries directory. 程序和PEAR包中PHP脚本安装的地方。pear 将在这里执行。记得要把这个路径加到人的PATH环境中去。
PHP code directory   PHP代码安装位置。这个路径必须在php.ini include_path中包含。
Documentation base directory 文档的基本目录。,默认情况下是$php_dir/doc,每一个包的文档做为$doc_dr/Package/file来安装。
Database directory    PEAR安装程序保存数据文件的地方。
Tests base directory 包旧的测试脚本安装的地方。包的名字也添加到这个路径。

当设置完这些路径,按回车确定:

The following PEAR packages are bundled with PHP: DB, Net_Socket, Net_SMTP,Mail, XML_Parser, PHPUnit2.Would you like to install these as well? [Y/n] :

根据配置,go-paer决定在哪里安装包,直接按回车继续:

Loading zlib: ok
Downloading package: PEAR………….ok
Downloading package: Archive_Tar……ok
Downloading package: Console_Getopt….ok
Downloading package: XML_RPC……….ok
Bootstrapping: PEAR……………….(remote) ok
Bootstrapping: Archive_Tar…………(remote) ok
Bootstrapping: Console_Getopt………(remote) ok
Downloading package: DB……………ok
Downloading package: Net_Socket…….ok
Downloading package: Net_SMTP………ok
Downloading package: Mail………….ok
Downloading package: XML_Parser…….ok
Downloading package: PHPUnit2………ok
Extracting installer………………ok
install ok:
PEAR 1.3.1install ok:
Archive_Tar 1.2install ok:
Console_Getopt 1.2install ok:
XML_RPC 1.1.0install ok:
DB 1.6.4install ok:
Net_Socket 1.0.2install ok:
Net_SMTP 1.2.6install ok:
Mail 1.1.3install ok:
XML_Parser 1.2.0install ok:
PHPUnit2 2.0.0beta2 The ‘pear’ command is now at your service at /usr/local/bin/pear

至此PEAR也就安装成功

说明一下:我自己用的是Windows系统,PHP是5.1.6
在我的PHP目录下只有一个go-pear.bat,还有一个PEAR目录,里面有一个go-pear.phar(这个应该是就是书上说的go-pear.php)
我用php C:/php/pear/go-pear.phar,倒还真执行了,
其实直接执行go-pear.bat
会出选择system或local,这个好像是为了让选择PEAR的安装配置,好像是可以装多个
直接回车后就到配置PEAR的环境的地方了,估计这里是做一下确认吧
我的确认后就直接开始安装了
但安装完后DB,XML_parser等都没装上去

我是自己招待命令 pear install DB命令安装上去的

安装成功后会在C:/php目录下产生一个pear.bat,这个文件就是pear程序,好多操作都要通过这个程序来完成。

另外就是要修改php.ini中的include_path!1!!!!