手机浏览 RSS 2.0 订阅 膘叔的简单人生 , 腾讯云RDS购买 | 超便宜的Vultr , 免费部署 N8N 的 Zeabur 注册 | 登陆
浏览模式: 标准 | 列表分类:PHP

使用CURL函数发送数据时的注意事项

PHP函数库里面,提到CURL,恐怕很多人都会翘起大拇指吧,确实,这个函数库太牛叉了

CURL其实是调用的CURL的lib,随着PHP版本的升高,curl所需的lib版本也随之提高。

关于CURL所必须的类库和安装说明,手册上有详细介绍:

XML/HTML代码
  1. Requirements  
  2.   
  3. In order to use PHP's cURL functions you need to install the libcurl package. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.  
  4.   
  5. Installation  
  6.   
  7. To use PHP's cURL support you must also compile PHP --with-curl[=DIR] where DIR is the location of the directory containing the lib and include directories. In the "include" directory there should be a folder named "curl" which should contain the easy.h and curl.h files. There should be a file named libcurl.a located in the "lib" directory. Beginning with PHP 4.3.0 you can configure PHP to use cURL for URL streams --with-curlwrappers.   
  8.   
  9. Note to Win32 Users: In order to enable this module on a Windows environment, libeay32.dll and ssleay32.dll must be present in your PATH.   
  10. You don't need libcurl.dll from the cURL site.   

然后在使用的时候也很方便,只需要初始化一下,设置一下postfields或者GET啥啥的,最后exec一下就行了。关键是别忘了close.

例子代码如下:

PHP代码
  1. $ch = curl_init("http://www.example.com/");  
  2. $fp = fopen("example_homepage.txt""w");  
  3.   
  4. curl_setopt($ch, CURLOPT_FILE, $fp);  
  5. curl_setopt($ch, CURLOPT_HEADER, 0);  
  6.   
  7. curl_exec($ch);  
  8. curl_close($ch);  
  9. fclose($fp);  

以上例子代码有点特殊,是因为他把网页内容进行了下载,同时生成一个文件。这是默认调用GET的方法。

其实,CURL更多的是用来处理POST数据、上传文件等功能

例子如下:

PHP代码
  1. <?   
  2. /*  
  3. * Author: Ron  
  4. * Released: August 4, 2007  
  5. * Description: An example of the disguise_curl() function in order to grab contents from a website while remaining fully camouflaged by using a fake user agent and fake headers.  
  6. */   
  7.   
  8. $url = 'http://www.ericgiguere.com/tools/http-header-viewer.html';   
  9.   
  10. // disguises the curl using fake headers and a fake user agent.   
  11. function disguise_curl($url)   
  12. {   
  13.   $curl = curl_init();   
  14.   
  15.   // Setup headers - I used the same headers from Firefox version 2.0.0.6   
  16.   // below was split up because php.net said the line was too long. :/   
  17.   $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";   
  18.   $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";   
  19.   $header[] = "Cache-Control: max-age=0";   
  20.   $header[] = "Connection: keep-alive";   
  21.   $header[] = "Keep-Alive: 300";   
  22.   $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";   
  23.   $header[] = "Accept-Language: en-us,en;q=0.5";   
  24.   $header[] = "Pragma: "// browsers keep this blank.   
  25.   
  26.   curl_setopt($curl, CURLOPT_URL, $url);   
  27.   curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');   
  28.   curl_setopt($curl, CURLOPT_HTTPHEADER, $header);   
  29.   curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com');   
  30.   curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');   
  31.   curl_setopt($curl, CURLOPT_AUTOREFERER, true);   
  32.   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);   
  33.   curl_setopt($curl, CURLOPT_TIMEOUT, 10);   
  34.   
  35.   $html = curl_exec($curl); // execute the curl command   
  36.   curl_close($curl); // close the connection   
  37.   
  38.   return $html// and finally, return $html   
  39. }   
  40.   
  41. // uses the function and displays the text off the website   
  42. $text = disguise_curl($url);   
  43. echo $text;   
  44. ?>   

上面是一个比较完整的实现。特别需要注意的是header头部的发送,最初看手册的时候,我一以为CURLOPT_HTTPHEADER所需的数组是键值对应的,即:

PHP代码
  1. $header = array('Keep-Alive'=>'300');  

现实的残酷告诉我,不应该这么用,而是象上面的例子那样,每条header为数组的一个记录。

切记切记啊

Tags: curl, curlopt, httpheader, libcurl, charset

不要轻信 PHP_SELF

原文地址:http://www.phpv.net/html/1639.html,作者:手气不错

未删节版本

开门见山,考虑下面的代码(原文连接有详细的解释)

PHP代码
  1. <html>  
  2.     <body>  
  3.         <?php  
  4.             if (isset($_REQUEST['submitted']) && $_REQUEST['submitted'] == '1') {  
  5.                 echo "Form submitted!";  
  6.             }  
  7.         ?>  
  8.         <form action="<?php echo $_SERVER['PHP_SELF']; ?>">  
  9.             <input type="hidden" name="submitted" value="1" />  
  10.             <input type="submit" value="Submit!" />  
  11.         </form>  
  12.     </body>  
  13. </html>  

看似准确无误的代码,但是暗藏着危险。让我们将其保存为 foo.php ,然后放到 PHP 环境中使用

foo.php/%22%3E%3Cscript%3Ealert('xss')%3C/script%3E%3Cfoo

访问,会发现弹出个 Javascript 的 alert -- 这很明显又是个 XSS 的注入漏洞。究其原因,发现是在

echo $_SERVER['PHP_SELF'];

这条语句上直接输出了未过滤的值。追根数源,我们看下 PHP 手册的描述

'PHP_SELF'

The filename of the currently executing script, relative to the document root.
For instance, $_SERVER['PHP_SELF'] in a script at the address
http://example.com/test.php/foo.bar would be /test.php/foo.bar. The __FILE__
constant contains the full path and filename of the current (i.e. included) file.
If PHP is running as a command-line processor this variable contains the script
name since PHP 4.3.0. Previously it was not available.

原因很明确了,原来是 $_SERVER['PHP_SELF'] 虽然“看起来”是服务器提供的环境变量,但这的确和 $_POST 与 $_GET 一样,是可以被用户更改的。

其它类似的变量有很多,比如 $_COOKIE 等(如果用户想“把玩”他们的 cookie,那我们也是没有办法)。解决方案很简单,使用 strip_tagshtmlentities 等此类函数过滤或者转义。

echo htmlentities($_SERVER['PHP_SELF']);

-- Split --

上述的例子让我们需要时刻保持谨慎 coding 的心态。Chris Shiflett 在他的 Blog 总结的相当直白,防止 XSS 的两个基本的安全思想就是

Filter input
Escape output

我将上面翻译成 “过滤输入,转义输出”。详细的内容,可以参考他 Blog 的这篇文章,此处略。

Tags: php, php_self

随便写写

PHP代码
  1. <?php  
  2.   
  3. Class Aspire      
  4. {  
  5.     private $outPut = '';  
  6.     static public function cin ( $str ){  
  7.         ifstrToLower$str ) == 'sweat'){  
  8.             self::$outPut = 'Gains';  
  9.         }else{  
  10.             self::$outPut = 'Without Something';  
  11.         }  
  12.     }  
  13.   
  14.     static public function cout (){  
  15.         echo( self::$outPut );  
  16.         self::$outPut = NULL;  
  17.     }  
  18. }  
  19. Aspire::cin('sweat');  
  20. Aspire::cout();  
  21. Aspire::cin('laugh');  
  22. Aspire::cout();  
  23. ?>  

Tags: php, class

PHP5的 SPL [转摘]

很少看到介绍SPL的文章,难得看到一篇,转摘,记录一下,原文地址:http://www.phpobject.net/blog/read.php/140.htm

PHP SPL笔记
目录
第一部分 简介
1. 什么是SPL?
2. 什么是Iterator?
第二部分 SPL Interfaces
3. Iterator界面
4. ArrayAccess界面
5. IteratorAggregate界面
6. RecursiveIterator界面
7. SeekableIterator界面
8. Countable界面
第三部分 SPL Classes
9. SPL的内置类
10. DirectoryIterator类
11. ArrayObject类
12. ArrayIterator类
13. RecursiveArrayIterator类和RecursiveIteratorIterator类
14. FilterIterator类
15. SimpleXMLIterator类
16. CachingIterator类
17. LimitIterator类
18. SplFileObject类
第一部 简介
1. 什么是SPL?
SPL是Standard PHP Library(PHP标准库)的缩写。
根据官方定义,它是“a collection of interfaces and classes that are meant to solve standard problems”。但是,目前在使用中,SPL更多地被看作是一种使object(物体)模仿array(数组)行为的interfaces和 classes。
2. 什么是Iterator?
SPL的核心概念就是Iterator。这指的是一种Design Pattern,根据《Design Patterns》一书的定义,Iterator的作用是“provide an object which traverses some aggregate structure, abstracting away assumptions about the implementation of that structure.”
wikipedia中说,"an iterator is an object which allows a programmer to traverse through all the elements of a collection, regardless of its specific implementation".……"the iterator pattern is a design pattern in which iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation".
通俗地说,Iterator能够使许多不同的数据结构,都能有统一的操作界面,比如一个数据库的结果集、同一个目录中的文件集、或者一个文本中每一行构成的集合。
如果按照普通情况,遍历一个MySQL的结果集,程序需要这样写:

PHP代码
  1. // Fetch the "aggregate structure"  
  2. $result = mysql_query("SELECT * FROM users");  
  3. // Iterate over the structure  
  4. while ( $row = mysql_fetch_array($result) ) {  
  5.    // do stuff with the row here  
  6. }  


读出一个目录中的内容,需要这样写:

PHP代码
  1. // Fetch the "aggregate structure"  
  2. $dh = opendir('/home/harryf/files');  
  3. // Iterate over the structure  
  4. while ( $file = readdir($dh) ) {  
  5.    // do stuff with the file here  
  6. }  



读出一个文本文件的内容,需要这样写:

PHP代码
  1. // Fetch the "aggregate structure"  
  2. $fh = fopen("/home/hfuecks/files/results.txt""r");  
  3. // Iterate over the structure  
  4. while (!feof($fh)) {  
  5.    $line = fgets($fh);  
  6.    // do stuff with the line here  
  7. }  


上面三段代码,虽然处理的是不同的resource(资源),但是功能都是遍历结果集(loop over contents),因此Iterator的基本思想,就是将这三种不同的操作统一起来,用同样的命令界面,处理不同的资源。
第二部分 SPL Interfaces
3. Iterator界面
SPL规定,所有部署了Iterator界面的class,都可以用在foreach Loop中。Iterator界面中包含5个必须部署的方法:
        * current()
          This method returns the current index’s value. You are solely
          responsible for tracking what the current index is as the
         interface does not do this for you.
        * key()
          This method returns the value of the current index’s key. For
          foreach loops this is extremely important so that the key
          value can be populated.
        * next()
          This method moves the internal index forward one entry.
        * rewind()
          This method should reset the internal index to the first element.
        * valid()
          This method should return true or false if there is a current
          element. It is called after rewind() or next().

下面就是一个部署了Iterator界面的class示例:

PHP代码
  1. /** 
  2. * An iterator for native PHP arrays, re-inventing the wheel 
  3. * 
  4. * Notice the "implements Iterator" - important! 
  5. */  
  6. class ArrayReloaded implements Iterator {  
  7.    /** 
  8.    * A native PHP array to iterate over 
  9.    */  
  10.  private $array = array();  
  11.    /** 
  12.    * A switch to keep track of the end of the array 
  13.    */  
  14.  private $valid = FALSE;  
  15.    /** 
  16.    * Constructor 
  17.    * @param array native PHP array to iterate over 
  18.    */  
  19.  function __construct($array) {  
  20.    $this->array = $array;  
  21.  }  
  22.    /** 
  23.    * Return the array "pointer" to the first element 
  24.    * PHP's reset() returns false if the array has no elements 
  25.    */  
  26.  function rewind(){  
  27.    $this->valid = (FALSE !== reset($this->array));  
  28.  }  
  29.    /** 
  30.    * Return the current array element 
  31.    */  
  32.  function current(){  
  33.    return current($this->array);  
  34.  }  
  35.    /** 
  36.    * Return the key of the current array element 
  37.    */  
  38.  function key(){  
  39.    return key($this->array);  
  40.  }  
  41.    /** 
  42.    * Move forward by one 
  43.    * PHP's next() returns false if there are no more elements 
  44.    */  
  45.  function next(){  
  46.    $this->valid = (FALSE !== next($this->array));  
  47.  }  
  48.    /** 
  49.    * Is the current element valid? 
  50.    */  
  51.  function valid(){  
  52.    return $this->valid;  
  53.  }  
  54. }  

使用方法如下:

PHP代码
  1. // Create iterator object  
  2. $colors = new ArrayReloaded(array ('red','green','blue',));  
  3. // Iterate away!  
  4. foreach ( $colors as $color ) {  
  5.  echo $color."\n";  
  6. }  

你也可以在foreach循环中使用key()方法:

PHP代码
  1. // Display the keys as well  
  2. foreach ( $colors as $key => $color ) {  
  3.  echo "$key: $color";  
  4. }  

除了foreach循环外,也可以使用while循环,

PHP代码
  1. // Reset the iterator - foreach does this automatically  
  2. $colors->rewind();  
  3. // Loop while valid  
  4. while ( $colors->valid() ) {  
  5.    echo $colors->key().": ".$colors->current()." 
  6. ";  
  7.    $colors->next();  
  8. }  

根据测试,while循环要稍快于foreach循环,因为运行时少了一层中间调用。
4. ArrayAccess界面
部署ArrayAccess界面,可以使得object像array那样操作。ArrayAccess界面包含四个必须部署的方法:
        * offsetExists($offset)
          This method is used to tell php if there is a value
          for the key specified by offset. It should return
          true or false.
        * offsetGet($offset)
          This method is used to return the value specified
          by the key offset.
        * offsetSet($offset, $value)
          This method is used to set a value within the object,
          you can throw an exception from this function for a
          read-only collection.
        * offsetUnset($offset)
          This method is used when a value is removed from
          an array either through unset() or assigning the key
          a value of null. In the case of numerical arrays, this
          offset should not be deleted and the array should
          not be reindexed unless that is specifically the
          behavior you want.

下面就是一个部署ArrayAccess界面的实例:

PHP代码
  1. /** 
  2. * A class that can be used like an array 
  3. */  
  4. class Article implements ArrayAccess {  
  5.  public $title;  
  6.  public $author;  
  7.  public $category;   
  8.  function __construct($title,$author,$category) {  
  9.    $this->title = $title;  
  10.    $this->author = $author;  
  11.    $this->category = $category;  
  12.  }  
  13.  /** 
  14.  * Defined by ArrayAccess interface 
  15.  * Set a value given it's key e.g. $A['title'] = 'foo'; 
  16.  * @param mixed key (string or integer) 
  17.  * @param mixed value 
  18.  * @return void 
  19.  */  
  20.  function offsetSet($key$value) {  
  21.    if ( array_key_exists($key,get_object_vars($this)) ) {  
  22.      $this->{$key} = $value;  
  23.    }  
  24.  }  
  25.  /** 
  26.  * Defined by ArrayAccess interface 
  27.  * Return a value given it's key e.g. echo $A['title']; 
  28.  * @param mixed key (string or integer) 
  29.  * @return mixed value 
  30.  */  
  31.  function offsetGet($key) {  
  32.    if ( array_key_exists($key,get_object_vars($this)) ) {  
  33.      return $this->{$key};  
  34.    }  
  35.  }  
  36.  /** 
  37.  * Defined by ArrayAccess interface 
  38.  * Unset a value by it's key e.g. unset($A['title']); 
  39.  * @param mixed key (string or integer) 
  40.  * @return void 
  41.  */  
  42.  function offsetUnset($key) {  
  43.    if ( array_key_exists($key,get_object_vars($this)) ) {  
  44.      unset($this->{$key});  
  45.    }  
  46.  }  
  47.  /** 
  48.  * Defined by ArrayAccess interface 
  49.  * Check value exists, given it's key e.g. isset($A['title']) 
  50.  * @param mixed key (string or integer) 
  51.  * @return boolean 
  52.  */  
  53.  function offsetExists($offset) {  
  54.    return array_key_exists($offset,get_object_vars($this));  
  55.  }  
  56. }  

使用方法如下:

PHP代码
  1. // Create the object  
  2. $A = new Article('SPL Rocks','Joe Bloggs''PHP');  
  3. // Check what it looks like  
  4. echo 'Initial State:';  
  5. print_r($A);  
  6. echo "\n";  
  7. // Change the title using array syntax  
  8. $A['title'] = 'SPL _really_ rocks';  
  9. // Try setting a non existent property (ignored)  
  10. $A['not found'] = 1;  
  11. // Unset the author field  
  12. unset($A['author']);  
  13. // Check what it looks like again  
  14. echo 'Final State:';  
  15. print_r($A);  
  16. echo "\n";  

运行结果如下:
    Initial State:
    Article Object
    (
       [title] => SPL Rocks
       [author] => Joe Bloggs
       [category] => PHP
    )
    Final State:
    Article Object
    (
       [title] => SPL _really_ rocks
       [category] => PHP
    )

可以看到,$A虽然是一个object,但是完全可以像array那样操作。
你还可以在读取数据时,增加程序内部的逻辑:

PHP代码
  1. function offsetGet($key) {  
  2.    if ( array_key_exists($key,get_object_vars($this)) ) {  
  3.      return strtolower($this->{$key});  
  4.    }  
  5.  }  

5. IteratorAggregate界面
但是,虽然$A可以像数组那样操作,却无法使用foreach遍历,除非部署了前面提到的Iterator界面。
另一个解决方法是,有时会需要将数据和遍历部分分开,这时就可以部署IteratorAggregate界面。它规定了一个getIterator()方法,返回一个使用Iterator界面的object。
还是以上一节的Article类为例:

PHP代码
  1. class Article implements ArrayAccess, IteratorAggregate {  
  2. /** 
  3.  * Defined by IteratorAggregate interface 
  4.  * Returns an iterator for for this object, for use with foreach 
  5.  * @return ArrayIterator 
  6.  */  
  7.  function getIterator() {  
  8.    return new ArrayIterator($this);  
  9.  }  



使用方法如下:

PHP代码
  1. $A = new Article('SPL Rocks','Joe Bloggs''PHP');  
  2. // Loop (getIterator will be called automatically)  
  3. echo 'Looping with foreach:';  
  4. foreach ( $A as $field => $value ) {  
  5.  echo "$field : $value";  
  6. }  
  7. echo '';  
  8. // Get the size of the iterator (see how many properties are left)  
  9. echo "Object has ".sizeof($A->getIterator())." elements";  

显示结果如下:
    Looping with foreach:
    title : SPL Rocks
    author : Joe Bloggs
    category : PHP
    Object has 3 elements

6. RecursiveIterator界面
这个界面用于遍历多层数据,它继承了Iterator界面,因而也具有标准的current()、key()、next()、 rewind()和valid()方法。同时,它自己还规定了getChildren()和hasChildren()方法。The getChildren() method must return an object that implements RecursiveIterator.
7. SeekableIterator界面
SeekableIterator界面也是Iterator界面的延伸,除了Iterator的5个方法以外,还规定了seek()方法,参数是元素的位置,返回该元素。如果该位置不存在,则抛出OutOfBoundsException。
下面是一个是实例:

PHP代码
  1. class PartyMemberIterator implements SeekableIterator  
  2. {  
  3.     public function __construct(PartyMember $member)  
  4.     {  
  5.         // Store $member locally for iteration  
  6.     }  
  7.     public function seek($index)  
  8.     {  
  9.         $this->rewind();  
  10.         $position = 0;  
  11.         while ($position < $index && $this->valid()) {  
  12.             $this->next();  
  13.             $position++;  
  14.         }  
  15.         if (!$this->valid()) {  
  16.             throw new OutOfBoundsException('Invalid position');  
  17.         }  
  18.     }  
  19.     // Implement current(), key(), next(), rewind()  
  20.     // and valid() to iterate over data in $member  
  21. }  

8. Countable界面
这个界面规定了一个count()方法,返回结果集的数量。
第三部分 SPL Classes
9. SPL的内置类
SPL除了定义一系列Interfaces以外,还提供一系列的内置类,它们对应不同的任务,大大简化了编程。
查看所有的内置类,可以使用下面的代码:

PHP代码
  1. // a simple foreach() to traverse the SPL class names  
  2. foreach(spl_classes() as $key=>$value)  
  3. {  
  4.     echo $key.' -> '.$value.'';  
  5. }  

10. DirectoryIterator类
这个类用来查看一个目录中的所有文件和子目录:
 

PHP代码
  1. try{  
  2.   /*** class create new DirectoryIterator Object ***/  
  3.     foreach ( new DirectoryIterator('./'as $Item )  
  4.         {  
  5.         echo $Item.'';  
  6.         }  
  7.     }  
  8. /*** if an exception is thrown, catch it here ***/  
  9. catch(Exception $e){  
  10.     echo 'No files Found!';  
  11. }  


查看文件的详细信息:
 

PHP代码
  1. foreach(new DirectoryIterator('./' ) as $file )  
  2.     {  
  3.     if$file->getFilename()  == 'foo.txt' )  
  4.         {  
  5.         echo ' getFilename() '; var_dump($file->getFilename()); echo ' ';  
  6.     echo ' getBasename() '; var_dump($file->getBasename()); echo ' ';  
  7.         echo ' isDot() '; var_dump($file->isDot()); echo ' ';  
  8.         echo ' __toString() '; var_dump($file->__toString()); echo ' ';  
  9.         echo ' getPath() '; var_dump($file->getPath()); echo ' ';  
  10.         echo ' getPathname() '; var_dump($file->getPathname()); echo ' ';  
  11.         echo ' getPerms() '; var_dump($file->getPerms()); echo ' ';  
  12.         echo ' getInode() '; var_dump($file->getInode()); echo ' ';  
  13.         echo ' getSize() '; var_dump($file->getSize()); echo ' ';  
  14.         echo ' getOwner() '; var_dump($file->getOwner()); echo ' ';  
  15.         echo ' $file->getGroup() '; var_dump($file->getGroup()); echo ' ';  
  16.         echo ' getATime() '; var_dump($file->getATime()); echo ' ';  
  17.         echo ' getMTime() '; var_dump($file->getMTime()); echo ' ';  
  18.         echo ' getCTime() '; var_dump($file->getCTime()); echo ' ';  
  19.         echo ' getType() '; var_dump($file->getType()); echo ' ';  
  20.         echo ' isWritable() '; var_dump($file->isWritable()); echo ' ';  
  21.         echo ' isReadable() '; var_dump($file->isReadable()); echo ' ';  
  22.         echo ' isExecutable( '; var_dump($file->isExecutable()); echo ' ';  
  23.         echo ' isFile() '; var_dump($file->isFile()); echo ' ';  
  24.         echo ' isDir() '; var_dump($file->isDir()); echo ' ';  
  25.         echo ' isLink() '; var_dump($file->isLink()); echo ' ';  
  26.         echo ' getFileInfo() '; var_dump($file->getFileInfo()); echo ' ';  
  27.         echo ' getPathInfo() '; var_dump($file->getPathInfo()); echo ' ';  
  28.         echo ' openFile() '; var_dump($file->openFile()); echo ' ';  
  29.         echo ' setFileClass() '; var_dump($file->setFileClass()); echo ' ';  
  30.         echo ' setInfoClass() '; var_dump($file->setInfoClass()); echo ' ';  
  31.         }  
  32. }  


除了foreach循环外,还可以使用while循环:

PHP代码
  1.     /*** create a new iterator object ***/  
  2.     $it = new DirectoryIterator('./');  
  3.     /*** loop directly over the object ***/  
  4.     while($it->valid())  
  5.     {  
  6.         echo $it->key().' -- '.$it->current().' ';  
  7.         /*** move to the next iteration ***/  
  8.         $it->next();  
  9.     }  

如果要过滤所有子目录,可以在valid()方法中过滤:

PHP代码
  1. /*** create a new iterator object ***/  
  2. $it = new DirectoryIterator('./');  
  3. /*** loop directly over the object ***/  
  4. while($it->valid())  
  5. {  
  6.     /*** check if value is a directory ***/  
  7.     if($it->isDir())  
  8.     {  
  9.        /*** echo the key and current value ***/  
  10.        echo $it->key().' -- '.$it->current().'';  
  11.     }  
  12.     /*** move to the next iteration ***/  
  13.     $it->next();  
  14.  }  

11. ArrayObject类
这个类可以将Array转化为object。
 

PHP代码
  1. /*** a simple array ***/  
  2. $array = array('koala''kangaroo''wombat''wallaby''emu''kiwi''kookaburra''platypus');  
  3. /*** create the array object ***/  
  4. $arrayObj = new ArrayObject($array);  
  5. /*** iterate over the array ***/  
  6. for($iterator = $arrayObj->getIterator();  
  7.    /*** check if valid ***/  
  8.    $iterator->valid();  
  9.    /*** move to the next array member ***/  
  10.    $iterator->next())  
  11.     {  
  12.     /*** output the key and current array value ***/  
  13.     echo $iterator->key() . ' => ' . $iterator->current() . '';  
  14.     }  


增加一个元素:
    $arrayObj->append('dingo');

对元素排序:
    $arrayObj->natcasesort();

显示元素的数量:
    echo $arrayObj->count();

删除一个元素:
    $arrayObj->offsetUnset(5);

某一个元素是否存在:
     if ($arrayObj->offsetExists(3))
        {
           echo 'Offset Exists';
        }

更改某个位置的元素值:
     $arrayObj->offsetSet(5, "galah");

显示某个位置的元素值:
    echo $arrayObj->offsetGet(4);

12. ArrayIterator类
这个类实际上是对ArrayObject类的补充,为后者提供遍历功能。
示例如下:
 

PHP代码
  1. /*** a simple array ***/  
  2. $array = array('koala''kangaroo''wombat''wallaby''emu''kiwi''kookaburra''platypus');  
  3. try {  
  4.     $object = new ArrayIterator($array);  
  5.     foreach($object as $key=>$value)  
  6.     {  
  7.         echo $key.' => '.$value.'';  
  8.     }  
  9. }  
  10. catch (Exception $e)  
  11. {  
  12.     echo $e->getMessage();  
  13. }  
  14.   
  15. //rayIterator类也支持offset类方法和count()方法:  
  16.   
  17.     /*** a simple array ***/  
  18. $array = array('koala''kangaroo''wombat''wallaby''emu''kiwi''kookaburra''platypus');  
  19. try {  
  20.     $object = new ArrayIterator($array);  
  21.     /*** check for the existence of the offset 2 ***/  
  22.     if($object->offSetExists(2))  
  23.     {  
  24.         /*** set the offset of 2 to a new value ***/  
  25.         $object->offSetSet(2, 'Goanna');  
  26.     }  
  27.    /*** unset the kiwi ***/  
  28.    foreach($object as $key=>$value)  
  29.    {  
  30.         /*** check the value of the key ***/  
  31.         if($object->offSetGet($key) === 'kiwi')  
  32.         {  
  33.             /*** unset the current key ***/  
  34.             $object->offSetUnset($key);  
  35.         }  
  36.         echo ''.$key.' - '.$value.''."\n";  
  37.     }  
  38. }  
  39. catch (Exception $e)  
  40. {  
  41.     echo $e->getMessage();  
  42. }  


    ?>
   

13. RecursiveArrayIterator类和RecursiveIteratorIterator类
ArrayIterator类和ArrayObject类,只支持遍历一维数组。如果要遍历多维数组,必须先用 RecursiveIteratorIterator生成一个Iterator,然后再对这个Iterator使用 RecursiveIteratorIterator。

PHP代码
  1. $array = array(  
  2.    array('name'=>'butch''sex'=>'m''breed'=>'boxer'),  
  3.    array('name'=>'fido''sex'=>'m''breed'=>'doberman'),  
  4.    array('name'=>'girly','sex'=>'f''breed'=>'poodle')  
  5. );  
  6. foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $key=>$value)  
  7. {  
  8.     echo $key.' -- '.$value.'';  
  9. }  

14. FilterIterator类
FilterIterator类可以对元素进行过滤,只要在accept()方法中设置过滤条件就可以了。
示例如下:

PHP代码
  1.         /*** a simple array ***/  
  2.     $animals = array('koala''kangaroo''wombat''wallaby''emu''NZ'=>'kiwi''kookaburra''platypus');  
  3.     class CullingIterator extends FilterIterator{  
  4.     /*** The filteriterator takes  a iterator as param: ***/  
  5.     public function __construct( Iterator $it ){  
  6.       parent::__construct( $it );  
  7.     }  
  8.     /*** check if key is numeric ***/  
  9.     function accept(){  
  10.       return is_numeric($this->key());  
  11.     }  
  12.     }/*** end of class ***/  
  13.     $cull = new CullingIterator(new ArrayIterator($animals));  
  14.     foreach($cull as $key=>$value)  
  15.         {  
  16.         echo $key.' == '.$value.'';  
  17.         }  
  18.     ?>  
  19. //下面是另一个返回质数的例子:  
  20.      
  21.     class PrimeFilter extends FilterIterator{  
  22.     /*** The filteriterator takes  a iterator as param: ***/  
  23.     public function __construct(Iterator $it){  
  24.       parent::__construct($it);  
  25.     }  
  26.     /*** check if current value is prime ***/  
  27.     function accept(){  
  28.     if($this->current() % 2 != 1)  
  29.         {  
  30.         return false;  
  31.         }  
  32.     $d = 3;  
  33.     $x = sqrt($this->current());  
  34.     while ($this->current() % $d != 0 && $d < $x)  
  35.         {  
  36.         $d += 2;  
  37.         }  
  38.      return (($this->current() % $d == 0 && $this->current() != $d) * 1) == 0 ? true : false;  
  39.     }  
  40.     }/*** end of class ***/  
  41.     /*** an array of numbers ***/  
  42.     $numbers = range(212345,212456);  
  43.     /*** create a new FilterIterator object ***/  
  44.     $primes = new primeFilter(new ArrayIterator($numbers));  
  45.     foreach($primes as $value)  
  46.         {  
  47.         echo $value.' is prime.';  
  48.         }  

15. SimpleXMLIterator类
这个类用来遍历xml文件。
示例如下:
 原文的XML在就是变型的,或者说在解释的时候已经坏掉了,所以。我删除了,直接看方法吧:by 膘叔

PHP代码
  1. /*** a new simpleXML iterator object ***/  
  2. try    {  
  3.        /*** a new simple xml iterator ***/  
  4.        $it = new SimpleXMLIterator($xmlstring);  
  5.        /*** a new limitIterator object ***/  
  6.        foreach(new RecursiveIteratorIterator($it,1) as $name => $data)  
  7.           {  
  8.           echo $name.' -- '.$data.'';  
  9.           }  
  10.     }  
  11. catch(Exception $e)  
  12.     {  
  13.     echo $e->getMessage();  
  14.     }  

new RecursiveIteratorIterator($it,1)表示显示所有包括父元素在内的子元素。
显示某一个特定的元素值,可以这样写:

PHP代码
  1. try {  
  2. /*** a new simpleXML iterator object ***/  
  3. $sxi =  new SimpleXMLIterator($xmlstring); 
  4. foreach ( $sxi as $node )  
  5.     {  
  6.     foreach($node as $k=>$v)  
  7.         {  
  8.         echo $v->species.'';  
  9.         }  
  10.     }  
  11. }  
  12. catch(Exception $e)  
  13. {  
  14. echo $e->getMessage();  
  15. }  


相对应的while循环写法为:
 

PHP代码
  1. try {  
  2. $sxe = simplexml_load_string($xmlstring'SimpleXMLIterator');  
  3. for ($sxe->rewind(); $sxe->valid(); $sxe->next())  
  4.     {  
  5.     if($sxe->hasChildren())  
  6.         {  
  7.         foreach($sxe->getChildren() as $element=>$value)  
  8.           {  
  9.           echo $value->species.'';  
  10.           }  
  11.         }  
  12.      }  
  13.    }  
  14. catch(Exception $e)  
  15.    {  
  16.    echo $e->getMessage();  
  17.    }  


最方便的写法,还是使用xpath:
 

PHP代码
  1. try {  
  2.  /*** a new simpleXML iterator object ***/  
  3.  $sxi =  new SimpleXMLIterator($xmlstring);  
  4.  /*** set the xpath ***/  
  5.  $foo = $sxi->xpath('animal/category/species');  
  6.  /*** iterate over the xpath ***/  
  7.  foreach ($foo as $k=>$v)  
  8.      {  
  9.      echo $v.'';  
  10.      }  
  11.  }  
  12. ch(Exception $e)  
  13.  {  
  14.  echo $e->getMessage();  
  15.  }  


下面的例子,显示有namespace的情况:

PHP代码
  1. /*** a new simpleXML iterator object ***/  
  2. try {  
  3.     /*** a new simpleXML iterator object ***/  
  4.     $sxi =  new SimpleXMLIterator($xmlstring);  
  5.     $sxi-> registerXPathNamespace('spec''http://www.exampe.org/species-title');  
  6.     /*** set the xpath ***/  
  7.     $result = $sxi->xpath('//spec:name');  
  8.     /*** get all declared namespaces ***/  
  9.    foreach($sxi->getDocNamespaces('animal'as $ns)  
  10.         {  
  11.         echo $ns.'';  
  12.         }  
  13.     /*** iterate over the xpath ***/  
  14.     foreach ($result as $k=>$v)  
  15.         {  
  16.         echo $v.'';  
  17.         }  
  18.     }  
  19. catch(Exception $e)  
  20.     {  
  21.     echo $e->getMessage();  
  22.     }  


增加一个节点:

PHP代码
  1. try {  
  2.     /*** a new simpleXML iterator object ***/  
  3.     $sxi =  new SimpleXMLIterator($xmlstring);  
  4.     /*** add a child ***/  
  5.     $sxi->addChild('animal''Tiger');  
  6.     /*** a new simpleXML iterator object ***/  
  7.     $new = new SimpleXmlIterator($sxi->saveXML());  
  8.     /*** iterate over the new tree ***/  
  9.     foreach($new as $val)  
  10.         {  
  11.         echo $val.'';  
  12.         }  
  13.     }  
  14. catch(Exception $e)  
  15.     {  
  16.     echo $e->getMessage();  
  17.     }  

增加属性:

PHP代码
  1. try {  
  2.     /*** a new simpleXML iterator object ***/  
  3.     $sxi =  new SimpleXMLIterator($xmlstring);  
  4.     /*** add an attribute with a namespace ***/  
  5.     $sxi->addAttribute('id:att1''good things''urn::test-foo');  
  6.     /*** add an attribute without a  namespace ***/  
  7.     $sxi->addAttribute('att2''no-ns');  
  8.     echo htmlentities($sxi->saveXML());  
  9.     }  
  10. catch(Exception $e)  
  11.     {  
  12.     echo $e->getMessage();  
  13.     }  

16. CachingIterator类
这个类有一个hasNext()方法,用来判断是否还有下一个元素。
示例如下:
 

PHP代码
  1.    /*** a simple array ***/  
  2. $array = array('koala''kangaroo''wombat''wallaby''emu''kiwi''kookaburra''platypus');  
  3. try {  
  4.     /*** create a new object ***/  
  5.     $object = new CachingIterator(new ArrayIterator($array));  
  6.     foreach($object as $value)  
  7.         {  
  8.         echo $value;  
  9.         if($object->hasNext())  
  10.             {  
  11.             echo ',';  
  12.             }  
  13.         }  
  14.     }  
  15. catch (Exception $e)  
  16.     {  
  17.     echo $e->getMessage();  
  18.     }  

17. LimitIterator类
这个类用来限定返回结果集的数量和位置,必须提供offset和limit两个参数,与SQL命令中limit语句类似。
示例如下:

PHP代码
  1.     /*** the offset value ***/  
  2. $offset = 3;  
  3. /*** the limit of records to show ***/  
  4. $limit = 2;  
  5. $array = array('koala''kangaroo''wombat''wallaby''emu''kiwi''kookaburra''platypus');  
  6. $it = new LimitIterator(new ArrayIterator($array), $offset$limit);  
  7. foreach($it as $k=>$v)  
  8.     {  
  9.     echo $it->getPosition().'';  
  10.     }  

另一个例子是:
   

PHP代码
  1. /*** a simple array ***/  
  2. $array = array('koala''kangaroo''wombat''wallaby''emu''kiwi''kookaburra''platypus');  
  3. $it = new LimitIterator(new ArrayIterator($array));  
  4. try  
  5.     {  
  6.     $it->seek(5);  
  7.     echo $it->current();  
  8.     }  
  9. catch(OutOfBoundsException $e)  
  10.     {  
  11.     echo $e->getMessage() . "";  
  12.     }  


18. SplFileObject类
这个类用来对文本文件进行遍历。
示例如下:

PHP代码
  1. try{  
  2.     // iterate directly over the object  
  3.     foreachnew SplFileObject("/usr/local/apache/logs/access_log"as $line)  
  4.     // and echo each line of the file  
  5.     echo $line.'';  
  6. }  
  7. catch (Exception $e)  
  8.     {  
  9.     echo $e->getMessage();  
  10.     }  

返回文本文件的第三行,可以这样写:

PHP代码
  1. try{  
  2.     $file = new SplFileObject("/usr/local/apache/logs/access_log");  
  3.     $file->seek(3);  
  4.     echo $file->current();  
  5. }  
  6. catch (Exception $e)  
  7. {  
  8.     echo $e->getMessage();  
  9. }  


[参考文献]
1. Introduction to Standard PHP Library (SPL), By Kevin Waterson
2. Introducing PHP 5's Standard Library, By Harry Fuecks
3. The Standard PHP Library (SPL), By Ben Ramsey
4. SPL - Standard PHP Library Documentation

 

smarty3即将出来

PHP的模版里,smarty一直就是让人又爱又恨的,功能太强大了,以致于美工们看到他也会感觉头疼,毕竟是又要学一门新的语言了。
这么多年,smarty都是在2.x版本里面徘徊,如今,终于要出3了。
以下是官方的change log:

10/6/2008

- completed compilation of {include} tag, variable scoping same as in smarty2

- added compilation of {capture} tag.

- added error message on none existing template files.

10/4/2008
- added comments in the parser definition y file.

- added array of $smarty_token_names to lexer for use in trigger_template_error function

- change handling of none smarty2 style tags like {if}, {for}....

- lexer/parser optimization

10/3/2008

- create different compiled template files depending if caching and/or security is enabled

- cleaned up compiler

- lexer/parser optimization

10/2/2008

- new method trigger fatal error, displays massage and terminates smarty

- compile error status flag added
The compiler will in case of error continue to parse the template(s) to display all errors. No compiled
templates will be written, Smarty terminates after the compiler exits.

- added error message to function __call in Smarty.class.php

Tags: smarty, version, php, template, smarttemplate