2009/04 24
用途: 当业务需要调用一个比较耗时外部资源时使用, 最常见的是从外部API获取相关内容

使用方法:
1. 建立外部资源脚本。 如示例中使用t.sh。 当然, 也可以直接使用curl等命令行
2. 准备好参数, 提供给pipe脚本
2. 使用popen调用脚本。 调用之后,就不用关心了。
3. 开始其他的和pipe不相关的逻辑处理
4. 其他处理完成之后, 使用fgets等方式,获取popen的数据


示例代码:

php程序:
# get argument for pipe here if it has.

#start pipe
echo 'call popen start: '. date("H:i:s"), "\n";
$pipe = popen(dirname(__FILE__) . '/t.sh', 'r');
echo 'call popen end: '. date("H:i:s"), "\n";

#Other code here
sleep(5);
echo "Here is my code. time: " . date("H:i:s"), "\n";

#read pipe result
while ($s = fgets($pipe,1024)) {
    echo $s;
}


pipe脚本:
echo 1, `date +%T`;
sleep 1;
echo 2, `date +%T`;
sleep 10;
echo 3, `date +%T`;


输出如下:
call popen start: 10:16:40
call popen end: 10:16:40
Here is my code. time: 10:16:45
1, 10:16:40
2, 10:16:41
3, 10:16:51


代码方面, 我们有三个sleep。
php中一个 sleep 5,
sh中两个sleep, 10+1
如果使用串行的方式, 那么用时应该是10+1+5 = 16秒。
而使用pipe方式, 用时仅为:max(php, pipe) = max(5,11) = 11秒。

PS:很抱歉,空间服务商看起来不喜欢popen这个字眼, 所以只能将起替换成全角的了。请在使用时,替换一下吧:)
Defined tags for this entry:

Posted by rollenc

Last modified on 2010-04-06 23:19
2009/03 19
vim的确是个好东西。 简单又快捷。针对在Vim编辑PHP文件,以下是在Ubuntu中的Vim安装及配置:

1. sudo apt-get install vim
2. sudo vi /etc/vim/vimrc
根据vimrc中的提示,Uncommenting一些需要的配置。 支持PHP主要需要解除注释的有以下几处:

'打开语法高亮
syntax on



'记录上次文件的编辑位置
if has("autocmd")
au BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$")
\| exe "normal! g'\"" | endif
endif



'自动识别文件类型
if has("autocmd")
filetype indent on
endif



Defined tags for this entry: ,

Posted by rollenc

Last modified on 2009-03-19 10:14
2009/03 10
PHP全球聚会在加拿大举行, 目前已经有一些PPT和文档出来了。
先睹为快:
Defined tags for this entry:

Posted by rollenc

Last modified on 2009-03-10 14:51
2008/12 20
40条PHP代码的优化技巧
40 Tips for optimizing your php Code
原文地址:http://reinholdweber.com/?p=3

这篇文章发布于去年, 不过还有很大的参考意义。 同样也备注一些东西。

1. If a method can be static, declare it static. Speed improvement is by a factor of 4.
如果一个方法可静态化,就对它做静态声明。速率可提升至4倍。

2. echo is faster than print.
echo 比 print 快。

3. Use echo’s multiple parameters instead of string concatenation.
使用echo的多重参数代替字符串连接。
实例:( echo $a1, $a2; )

4. Set the maxvalue for your for-loops before and not in the loop.
在执行for循环之前确定最大循环数,不要每循环一次都计算最大值。
实例: for($i=0,$i
5. Unset your variables to free memory, especially large arrays.
注销那些不用的变量尤其是大数组,以便释放内存。

6. Avoid magic like __get, __set, __autoload
尽量避免使用__get,__set,__autoload。
注:这一个问题在php5.2版本中得到了比较好的优化。

7. require_once() is expensive
require_once()代价昂贵。

8. Use full paths in includes and requires, less time spent on resolving the OS paths.
在包含文件时使用完整路径,解析操作系统路径所需的时间会更少。
实例: require dirname(__FILE__) . "/../config.php";

9. If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time()
如果你想知道脚本开始执行(译注:即服务器端收到客户端请求)的时刻,使用$_SERVER[‘REQUEST_TIME’]要好于time()。

10. See if you can use strncasecmp, strpbrk and stripos instead of regex.
检查是否能用strncasecmp,strpbrk,stripos函数代替正则表达式完成相同功能。

11. str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4.
str_replace函数比preg_replace函数快,但strtr函数的效率是str_replace函数的四倍。

12. If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.
如果一个字符串替换函数,可接受数组或字符作为参数,并且参数长度不太长,那么可以考虑额外写一段替换代码,使得每次传递参数是一个字符,而不是只写一行 代码接受数组作为查询和替换的参数。

13. It’s better to use select statements than multi if, else if, statements.
使用选择分支语句(译注:即switch case)好于使用多个if,else if语句。

14. Error suppression with @ is very slow.
用@屏蔽错误消息的做法非常低效。

15. Turn on apache’s mod_deflate
打开apache的mod_deflate模块。

16. Close your database connections when you’re done with them.
数据库连接当使用完毕时应关掉。

17. $row[’id’] is 7 times faster than $row[id].
$row[‘id’]的效率是$row[id]的7倍。

18. Error messages are expensive.
错误消息代价昂贵。

19. Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time.
尽量不要在for循环中使用函数,比如for ($x=0; $x < count($array); $x)每循环一次都会调用count()函数。

20. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
在方法中递增局部变量,速度是最快的。几乎与在函数中调用局部变量的速度相当。

21. Incrementing a global variable is 2 times slow than a local var.
递增一个全局变量要比递增一个局部变量慢2倍。

22. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.
递增一个对象属性(如:$this->prop++)要比递增一个局部变量慢3倍。

23. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
递增一个未预定义的局部变量要比递增一个预定义的局部变量慢9至10倍。

24. Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
仅定义一个局部变量而没在函数中调用它,同样会减慢速度(其程度相当于递增一个局部变量)。PHP大概会检查看是否存在全局变量。

25. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.
方法调用看来与类中定义的方法的数量无关,因为我(在测试方法之前和之后都)添加了10个方法,但性能上没有变化。

26. Methods in derived classes run faster than ones defined in the base class.
派生类中的方法运行起来要快于在基类中定义的同样的方法。

27. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.
调用带有一个参数的空函数,其花费的时间相当于执行7至8次的局部变量递增操作。类似的方法调用所花费的时间接近于15次的局部变量递增操作。

28. Surrounding your string by ‘ instead of " will make things interpret a little faster since php looks for variables inside "…" but not inside ‘…’. Of course you can only do this when you don’t need to have variables in the string.
用单引号代替双引号来包含字符串,这样做会更快一些。因为PHP会在双引号包围的字符串中搜寻变量,单引号则不会。当然,只有当你不需要在字符串中包含变 量时才可以这么做。
注: 实际上,不要注意这么多。 这两者并没有明显差别。0.1%不到。

29. When echoing strings it’s faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments.
输出多个字符串时,用逗号代替句点来分隔字符串,速度更快。注意:只有echo能这么做,它是一种可以把多个字符串当作参数的“函数”
注:重复强调第3条?

30. A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts. Apache解析一个PHP脚本的时间要比解析一个静态HTML页面慢2至10倍。尽量多用静态HTML页面,少用脚本。

31. Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times.
除非脚本可以缓存,否则每次调用时都会重新编译一次。引入一套PHP缓存机制通常可以提升25%至100%的性能,以免除编译开销。

32. Cache as much as possible. Use memcached - memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request.
尽量做缓存,可使用memcached。memcached是一款高性能的内存对象缓存系统,可用来加速动态Web应用程序,减轻数据库负载。运算码 (OP code)缓存也很有用,使得脚本不必为每个请求做重新编译。

33. When working with strings and you need to check that the string is either of a certain length you’d understandably would want to use the strlen() function. This function is pretty quick since it’s operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.
当操作字符串并需要检验其长度是否满足某种要求时,你想当然地会使用strlen()函数。此函数执行起来相当快,因为它不做任何计算,只返回在zval 结构(C的内置数据结构,用于存储PHP变量)中存储的已知字符串长度。但是,由于strlen()是函数,多多少少会有些慢,因为函数调用会经过诸多步 骤,如字母小写化(译注:指函数名小写化,PHP不区分函数名大小写)、哈希查找,会跟随被调用的函数一起执行。在某些情况下,你可以使用isset() 技巧加速执行你的代码。

Ex.(举例如下)
if (strlen($foo) < 5) { echo "Foo is too short"; }
vs.(与下面的技巧做比较)
if (!isset($foo{5})) { echo "Foo is too short"; }

Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it’s execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string’s length.
调用isset()恰巧比strlen()快,因为与后者不同的是,isset()作为一种语言结构,意味着它的执行不需要函数查找和字母小写化。也就是 说,实际上在检验字符串长度的顶层代码中你没有花太多开销。

34. When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don’t go modifying your C or Java code thinking it’ll suddenly become faster, it won’t. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend’s PHP optimizer. It is still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.
当执行变量$i的递增或递减时,$i++会比++$i慢一些。这种差异是PHP特有的,并不适用于其他语言,所以请不要修改你的C或Java代码并指望它 们能立即变快,没用的。++$i更快是因为它只需要3条指令(opcodes),$i++则需要4条指令。后置递增实际上会产生一个临时变量,这个临时变 量随后被递增。而前置递增直接在原值上递增。这是最优化处理的一种,正如Zend的PHP优化器所作的那样。牢记这个优化处理不失为一个好主意,因为并不 是所有的指令优化器都会做同样的优化处理,并且存在大量没有装配指令优化器的互联网服务提供商(ISPs)和服务器。

35. Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.
并不是事必面向对象(OOP),面向对象往往开销很大,每个方法和对象调用都会消耗很多内存。

36. Do not implement every data structure as a class, arrays are useful, too.
并非要用类实现所有的数据结构,数组也很有用。

37. Don’t split methods too much, think, which code you will really re-use.
不要把方法细分得过多,仔细想想你真正打算重用的是哪些代码?

38. You can always split the code of a method later, when needed.
当你需要时,你总能把代码分解成方法。

39. Make use of the countless predefined functions.
尽量采用大量的PHP内置函数。

40. If you have very time consuming functions in your code, consider writing them as C extensions.
如果在代码中存在大量耗时的函数,你可以考虑用C扩展的方式实现它们。

41. Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview.
评估检验(profile)你的代码。检验器会告诉你,代码的哪些部分消耗了多少时间。Xdebug调试器包含了检验程序,评估检验总体上可以显示出代码 的瓶颈。

42. mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%.
mod_gzip可作为Apache模块,用来即时压缩你的数据,并可让数据传输量降低80%。、
注: 重复第15条, mod_deflate和mod_zip是同样的东西

43. Excellent Article (http://phplens.com/lens/php-book/optimizing-debugging-php.php)about optimizing php by John Lim
另一篇优化PHP的精彩文章,由John Lim撰写。

在本blog中, 也有其他的一些优化建议。不免有重复的地方。
这也是优化所需要的。 代码的优化必须时刻提醒,时刻牢记。
强化为一种习惯,固有的思维,在日常的开发中定型下来。
PHP优化技巧 - PHP Optimization Tricks
优化php脚本 翻译

Defined tags for this entry: ,

Posted by rollenc

Last modified on 2008-12-20 23:15
2008/08 15
今天尝试使用curl请求lighttpd数据,发现总是报错(417) Expectation Failed。
经查,是lighttp不支持curl默认发送的头信息: Expect: 100-continue.

解决方式:

在curl中指定发送一个空的Except头信息即可解决。
代码:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));

Defined tags for this entry: ,

Posted by rollenc

Last modified on 2008-08-15 23:33
2008/06 14
原文: 40 signs you really are a lousy PHP programmer
很欣慰,我能在我身上看到的,仅有2条:
8. don't use test-driven development [YE, I AM SORRY. I love test-driven development. Before using, it is need a heavy refactor for the whole project. So, I am not using test-driven ]
29. don't have one single configuration file [Why I need it? I use separate configure file into db configure, form configure, const configure, path configure and other configure. I think it is beeter than one single file. ]
Defined tags for this entry:

Posted by rollenc

Last modified on 2008-07-21 09:29
2007/09 18
原文参见: http://download.eclipse.org/tools/pdt/downloads/
update地址: http://download.eclipse.org/tools/pdt/updates/
依赖: wst

SHIT!我使用update安装不了,系统告诉我:
Unable to complete action for feature "PDT Feature" due to errors.
The File "/tmp/1611919292/eclipse/.update/1190120959966/1190120959970/eclipse20065.tmp" is not a valid JAR file. [error in opening zip file]
error in opening zip file
The File "/tmp/1611919292/eclipse/.update/1190120959966/1190120959970/eclipse20065.tmp" is not a valid JAR file. [error in opening zip file]
error in opening zip file

昏死!无条件放弃,还是坚持 phpeclipse!
Defined tags for this entry: ,

Posted by rollenc

Last modified on 2007-09-19 11:37
2007/08 31
Security Enhancements and Fixes in PHP 5.2.4:

* Fixed a floating point exception inside wordwrap() (Reported by Mattias Bengtsson)
* Fixed several integer overflows inside the GD extension (Reported by Mattias Bengtsson)
* Fixed size calculation in chunk_split() (Reported by Gerhard Wagner)
* Fixed integer overflow in str[c]spn(). (Reported by Stanislav Malyshev)
* Fixed money_format() not to accept multiple %i or %n tokens. (Reported by Stanislav Malyshev)
* Fixed zend_alter_ini_entry() memory_limit interruption vulnerability. (Reported by Stefan Esser)
* Fixed INFILE LOCAL option handling with MySQL extensions not to be allowed when open_basedir or safe_mode is active. (Reported by Stanislav Malyshev)
* Fixed session.save_path and error_log values to be checked against open_basedir and safe_mode (CVE-2007-3378) (Reported by Maksymilian Arciemowicz)
* Fixed a possible invalid read in glob() win32 implementation (CVE-2007-3806) (Reported by shinnai)
* Fixed a possible buffer overflow in php_openssl_make_REQ (Reported by zatanzlatan at hotbrev dot com)
* Fixed an open_basedir bypass inside glob() function (Reported by dr at peytz dot dk)
* Fixed a possible open_basedir bypass inside session extension when the session file is a symlink (Reported by c dot i dot morris at durham dot ac dot uk)
* Improved fix for MOPB-03-2007.
* Corrected fix for CVE-2007-2872.
Defined tags for this entry:

Posted by rollenc

Last modified on 2007-08-31 13:27
2007/08 17
如果机器支持apache配置文件.htaccess(一般虚拟机都是支持的),但是并不容许你修改php.ini文件时,你可以使用以下代码来修改一些变量:
只适用于php做为apache的module的情况
  
php_value include_path ".:/usr/local/lib/php;" 
 
  
php_value include_path ".:/usr/local/lib/php" 
 
但是,不要使用
  
php_value error_reporting   E_ALL
 
这样的内容,因为E_ALL是php.ini中定义的常量,在apache中是无效的,任何没有定义的常量都被会解释为0或者空值。
因此以上内容将被解释为不报告任何错误,而不是所有错误。
如果php是做为cgi加载的,那么你可以通过ini_set来实现
$include_path = ini_get('include_path');
ini_set('include_path', $include_path.':/home/rollenc/myphplib'); //注意Linux目录分割符是 : 和windows使用的 ; 不同
Defined tags for this entry: ,

Posted by rollenc

Last modified on 2010-04-06 23:22
2007/07 18
Drupal通过C风格的字符串输出格式实现了对sql语句的安全过滤。
使用方法:

db_query("SELECT n.nid FROM {node} n WHERE n.type = '%s'", $type);//正确做法
//这不等于以下语句,使用sprintf并不能避免mysql注入。
db_query(sprintf("SELECT n.nid FROM {node} n WHERE n.type = '%s'", $type)); //不正确


drupal db_query核心代码如下:

/**
 * Indicates the place holders that should be replaced in _db_query_callback().
 */
define('DB_QUERY_REGEXP', '/(%d|%s|%%|%f|%b)/');

/**
 * Runs a basic query in the active database.
 *
 * User-supplied arguments to the query should be passed in as separate
 * parameters so that they can be properly escaped to avoid SQL injection
 * attacks.
 *
 * @param $query
 *   A string containing an SQL query.
 * @param ...
 *   A variable number of arguments which are substituted into the query
 *   using printf() syntax. Instead of a variable number of query arguments,
 *   you may also pass a single array containing the query arguments.

 *   Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose
 *   in '') and %%.
 *
 *   NOTE: using this syntax will cast NULL and FALSE values to decimal 0,
 *   and TRUE values to decimal 1.
 *
 * @return
 *   A database query result resource, or FALSE if the query was not
 *   executed correctly.
 */
function db_query($query) {
  $args = func_get_args();
  array_shift($args);
  $query = db_prefix_tables($query);
  if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
    $args = $args[0];
  }
  _db_query_callback($args, TRUE);
  $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
  return _db_query($query);
}

/**
 * Helper function for db_query().
 */
function _db_query_callback($match, $init = FALSE) {
  static $args = NULL;
  if ($init) {
    $args = $match;
    return;
  }

  switch ($match[1]) {
    case '%d': // We must use type casting to int to convert FALSE/NULL/(TRUE?)
      return (int) array_shift($args); // We don't need db_escape_string as numbers are db-safe
    case '%s':
      return db_escape_string(array_shift($args));
    case '%%':
      return '%';
    case '%f':
      return (float) array_shift($args);
    case '%b': // binary data
      return db_encode_blob(array_shift($args));
  }
}


参考: http://drupal.org/node/101496
Defined tags for this entry: ,

Posted by rollenc

Last modified on 2007-07-18 17:50
2007/05 23
Command-line switches
-cp --converterparams dynamic parameters for a converter, separate values with commas
-ct --customtags comma-separated list of non-standard @tags to pass to the converter as valid tags
-d --directory name of a directory(s) to parse directory1,directory2
-dc --defaultcategoryname name to use for the default category. If not specified, uses 'default'
-dh --hidden set equal to on (-dh on) to descend into hidden directories (directories starting with '.'), default is off
-dn --defaultpackagename name to use for the default package. If not specified, uses 'default'
-ed --examplesdir full path of the directory to look for example files from @example tags
-f --filename name of file(s) to parse ',' file1,file2. Can contain complete path and * ? wildcards
-i --ignore file(s) that will be ignored, multiple separated by ','. Wildcards * and ? are ok
-is --ignoresymlinks Explicitly ignore symlinks, both symlinked directories and symlinked files. Valid options are "on" and "offn" default value is "off"
-it --ignore-tags tags to ignore for this parse. @package, @subpackage, @access and @ignore may not be ignored.
-j --javadocdesc use JavaDoc-compliant description (short desc is part of description, and is everything up to first .)
-o --output output information, format:converter:template (HTML:frames:phpedit for example)
-p --pear Parse a PEAR-style repository (package is directory, _members are @access private) on/off default off
-po --packageoutput output documentation only for selected packages. Use a comma-delimited list
-pp --parseprivate parse elements marked private with @access. Valid options are "on" and "off" default value is "off"
-q --quiet do not display parsing/conversion messages. Useful for cron jobs. Valid options are "on" and "off" default value is "off"
-ric --readmeinstallchangelog Specify custom filenames to parse like README, INSTALL or CHANGELOG files
-s --sourcecode generate highlighted sourcecode for every parsed file (PHP 4.3.0+ only) on/off default off
-t --target path where to save the generated files
-ti --title title of generated documentation, default is 'Generated Documentation'
-tb --templatebase base location of all templates for this parse. Note that if -tb /path/to/here, then templates for HTML:frames:default must be in /path/to/here/Converters/HTML/frames/templates/default/templates and the /path/to/here/Converters/HTML/frames/templates/default/templates_c directory must exist, or Smarty will bail on attempting to compile the templates.
-ue --undocumentedelements Enable warnings for undocumented elements. Useful for identifying classes and methods that haven't yet been documented. Valid options are "on" and "offn" default value is "off"


来源于: phpdoc manual
Defined tags for this entry: ,

Posted by rollenc

Last modified on 2007-05-23 15:46
2007/05 23
{@*}” 用于在docblock中表示注释结束符号 */
-, +, #, o” 用来简写<li>, &ul;ul>, 等列表项,但是不支持多层结构,你只能用它们来表示单层列表
#@+and #@-” #@+是模板开始符,在此申明之后的所有申明,都会自动继承此申明的标记。直到出现模板结束符#@-

Defined tags for this entry: ,

Posted by rollenc

Last modified on 2007-05-23 15:43
2007/05 23
  • <b>
  • <code> Use this to surround php code, some converters will highlight it
  • <br>
  • <i>
  • <kbd> denote keyboard input/screen display
  • <li>
  • <ol>
  • <p>
  • <pre>
  • <samp> denote sample or examples (non-php)
  • <ul>
  • <var> denote a variable name
源自 :phpdoc manual
Defined tags for this entry: ,

Posted by rollenc

Last modified on 2007-05-23 15:43
2007/04 20
两域名分别为:
phpapp.cn
phpapplication.cn
这是为php系列的第三个重要域名了。
整个一条php社区线形成了:
function(phpfunction.cn) -> library(phplibrary.cn) -> application(phpapplication.cn)
目前我会重点做一下library。网址:http://www.phplibrary.cn
三马说的,等解决了吃饭的问题,我们要好好做些事情出来!
Defined tags for this entry:

Posted by rollenc

Last modified on 2007-04-20 22:34
2007/04 17
phplibrary上线好几天了,一直没有什么动静。
发布一下,我最近会每天会更新一个library上线,也来希望大家能够多多参与。
Defined tags for this entry:

Posted by rollenc

Last modified on 2007-04-17 17:28

(Page 1 of 4, totaling 50 entries)