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

重写PHP的fgetcsv函数

内容来自虫少侠的enjoyphp.com,因为很多时候我们都使用了fgetcsv,只是我们有时候都还在使用file,再explode处理,相反却忽略了这个系统函数,然而,用虫少侠的话来说,这个函数还是有BUG的,主要是在处理中文上,因此就有了这个函数:

function fgetcsv_reg(& $handle, $length = null, $d = ',', $e = '"') {
    $d = preg_quote($d);
    $e = preg_quote($e);
    $_line = "";
    $eof=false;
    while ($eof != true) {
        $_line .= (empty ($length) ? fgets($handle) : fgets($handle, $length));
        $itemcnt = preg_match_all('/' . $e . '/', $_line, $dummy);
        if ($itemcnt % 2 == 0)
            $eof = true;
    }
    $_csv_line = preg_replace('/(?: |[ ])?$/', $d, trim($_line));
    $_csv_pattern = '/(' . $e . '[^' . $e . ']*(?:' . $e . $e . '[^' . $e . ']*)*' . $e . '|[^' . $d . ']*)' . $d . '/';
    preg_match_all($_csv_pattern, $_csv_line, $_csv_matches);
    $_csv_data = $_csv_matches[1];
    for ($_csv_i = 0; $_csv_i < count($_csv_data); $_csv_i++) {
        $_csv_data[$_csv_i] = preg_replace('/^' . $e . '(.*)' . $e . '$/s', '$1', $_csv_data[$_csv_i]);
        $_csv_data[$_csv_i] = str_replace($e . $e, $e, $_csv_data[$_csv_i]);
    }
    return empty ($_line) ? false : $_csv_data;
}

原文来自:http://www.enjoyphp.com/2009/lamp/php-lamp/php-fgetcsv/

 

Tags: fgetcsv

郁闷:php console与web的问题

最近在做个小东西,想用PHP跑console,生成一个文件,然后由WEB去调用这个文件。可是却一直失败。

命令行下,用crontab跑,因为WEB是在Safemode下面,但我需要Exec,因此crontab调用php的时候,我就指定了phpini,类似/php -c phpinifilepath phpfilename,于是这样可以了。

但生成出来的文件被WEB调用后。一直显示是失败。郁闷了。。

纯记录,无意义

Tags: php, cli, web

PHPChina活动涉及PPT在线观看

上周六的phpchina搞的活动可以通过echo谈xhprof,cache and long-polling查看,其中echo的ppt可以在线观看了,当然你也可以下载到本地。

 

 

不得不说的是,ppt上可以展现的内容确实有点少,如果身在上海,没有去听echo讲课,确实有点遗憾。

PPT下载在这里:web_perf.pdf

Tags: phpchina, pea, xhprof, cache, long-polling

PHP 技巧:file_get_contents的超时处理

话说,从PHP5开始,file_get_content已经支持context了(手册上写着:5.0.0 Added the context support. ),也就是说,从5.0开始,file_get_contents其实也可以POST数据,关于这个,我在通过file_get_contents来 Post数据的实例也有所介绍。

今天说的这篇是讲超时的,确实在跨服务器提交的时候,不可避免的会遇到超时的情况,这个时候怎么办?set_time_limit是没有用的,只有用context中的timeout时间来控制。相反,我们不是要抑止,而是要管理。比如在超时返回错误后,进行一次尝试,就象js中的settimeout那样,对函数重新处理。错误超过3次或者5次后,我们就确实的认为无法连接服务器而彻底放弃。这,是一个好办法,应该值得推荐使用。其实。不全是file_get_contents,只要支持context的都应该加上,避免超时浪费时间。这样可以被支持的函数大致有:fsocketopen(该函数的最后一个参数。好象比较推荐在读stream的时候,使用stream_time_out函数进行控制),fopen(也是从PHP5开始加入context支持),file(PHP5加入支持),curl(curl有自已的变量CURLOPT_TIMEOUT)等 。

下面开始看原文吧:http://xinsync.xju.edu.cn/index.php/archives/6840。

因为要用php去向我的虚拟主机管理系统发送开通空间等的请求,需要Post传值,由于开通空间过程很慢,同时需要延时处理。以下找到了一下 file_get_contents的超时处理,网上有人用2个方法解决:

在使用file_get_contents函数的时候,经常会出现超时的情况,在这里要通过查看一下错误提示,看看是哪种错误,比较常见的是读取超 时,这种情况大家可以通过一些方法来尽量的避免或者解决。这里就简单介绍两种:

一、增加超时的时间限制

这里需要注意:set_time_limit只是设置你的PHP程序的超时时间,而不是file_get_contents函数读取URL的超时时 间。
我一开始以为set_time_limit也能影响到file_get_contents,后来经测试,是无效的。真正的修改 file_get_contents延时可以用resource $context的timeout参数:

PHP代码
  1. $opts = array(  
  2.     'http'=>array(  
  3.         'method'=>"GET",  
  4.         'timeout'=>60,  
  5.     )  
  6. );  
  7.    
  8. $context = stream_context_create($opts);  
  9.    
  10. $html =file_get_contents('http://www.example.com', false, $context);  
  11. fpassthru($fp);  
二、一次有延时的话那就多试几次

有时候失败是因为网络等因素造成,没有解决办法,但是可以修改程序,失败时重试几次,仍然失败就放弃,因为file_get_contents()如果失 败将返回 FALSE,所以可以下面这样编写代码:
PHP代码
  1. $cnt=0;  
  2. while($cnt < 3 && ($str=@file_get_contents('http...'))===FALSE) $cnt++;  
以上方法对付超时已经OK了。那么Post呢?细心点有人发现了’method’=>”GET”, 对!是不是能设置成post呢?百度找了下相关资料,还真可以!而且有人写出了山寨版的post传值函数,如下:
PHP代码
  1. function Post($url$post = null)  
  2. {  
  3.     $context = array();  
  4.    
  5.     if (is_array($post)) {  
  6.         ksort($post);  
  7.    
  8.         $context['http'] = array (  
  9.             'timeout'=>60,  
  10.             'method' => 'POST',  
  11.             'content' => http_build_query($post'''&'),  
  12.          );  
  13.     }  
  14.    
  15.     return file_get_contents($url, false, stream_context_create($context));  
  16. }  
  17.    
  18. $data = array (  
  19.     'name' => 'test',  
  20.     'email' => 'test@gmail.com',  
  21.     'submit' => 'submit',  
  22.  );  
  23.    
  24.  echo Post('http://www.example.com'$data);  

OK , 上面函数完美了,既解决了超时控制又解决了Post传值。再配合康盛的改良版RC4加密解密算法,做一个安全性很高的webservice就简单多了。

通过以上函数的组合,终于实现了PHP和我的ASP版虚拟主机管理软件的通信。.net相信也很容易了,因为已经有了.net版本的 authcode类。未来再做一个java版的就天下大同了。

--EOF--

我只能说这样的处理好是好,只是还得注意文件头的Set_time_out,否则整个文件都得超时了。呵呵

 

 

Tags: settimelimit, timeout, filegetcontents, context

drupal的db_query安全过滤

这篇 文章已经是07年的了,不过,我一直没有关注过drupal的db类,所以对于这方面我也根本 就没有在意过。8过,我在我的siterpc中,我也是采用了sprintf的写法,不是为了安全,而是为了格式化。因为在siterpc里我们几乎不接受外部变量,所有的变量都是由我们自己传入,所以对于安全方便忽略了很多。但还是用sprintf来格式化SQL语句了。

因此看到这篇drupal的db_query安全过滤,突然发现,可以让我的代码少写很多了。(参数可变时请使用vsprintf)

以下是原文 :

Drupal通过C风格的字符串输出格式实现了对sql语句的安全过滤。
使用方法:

PHP代码
  1. db_query("SELECT n.nid FROM {node} n WHERE n.type = '%s'"$type);//正确做法  
  2. //这不等于以下语句,使用sprintf并不能避免mysql注入。  
  3. db_query(sprintf("SELECT n.nid FROM {node} n WHERE n.type = '%s'"$type)); //不正确  
drupal db_query核心代码如下:
PHP代码
  1. /** 
  2.  * Indicates the place holders that should be replaced in _db_query_callback(). 
  3.  */  
  4. define('DB_QUERY_REGEXP''/(%d|%s|%%|%f|%b)/');  
  5.   
  6. /** 
  7.  * Runs a basic query in the active database. 
  8.  * 
  9.  * User-supplied arguments to the query should be passed in as separate 
  10.  * parameters so that they can be properly escaped to avoid SQL injection 
  11.  * attacks. 
  12.  * 
  13.  * @param $query 
  14.  *   A string containing an SQL query. 
  15.  * @param ... 
  16.  *   A variable number of arguments which are substituted into the query 
  17.  *   using printf() syntax. Instead of a variable number of query arguments, 
  18.  *   you may also pass a single array containing the query arguments. 
  19.  
  20.  *   Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose 
  21.  *   in '') and %%. 
  22.  * 
  23.  *   NOTE: using this syntax will cast NULL and FALSE values to decimal 0, 
  24.  *   and TRUE values to decimal 1. 
  25.  * 
  26.  * @return 
  27.  *   A database query result resource, or FALSE if the query was not 
  28.  *   executed correctly. 
  29.  */  
  30. function db_query($query) {  
  31.   $args = func_get_args();  
  32.   array_shift($args);  
  33.   $query = db_prefix_tables($query);  
  34.   if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax  
  35.     $args = $args[0];  
  36.   }  
  37.   _db_query_callback($args, TRUE);  
  38.   $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback'$query);  
  39.   return _db_query($query);  
  40. }  
  41.   
  42. /** 
  43.  * Helper function for db_query(). 
  44.  */  
  45. function _db_query_callback($match$init = FALSE) {  
  46.   static $args = NULL;  
  47.   if ($init) {  
  48.     $args = $match;  
  49.     return;  
  50.   }  
  51.   
  52.   switch ($match[1]) {  
  53.     case '%d'// We must use type casting to int to convert FALSE/NULL/(TRUE?)  
  54.       return (int) array_shift($args); // We don't need db_escape_string as numbers are db-safe  
  55.     case '%s': 
  56.       return db_escape_string(array_shift($args)); 
  57.     case '%%':  
  58.       return '%'; 
  59.     case '%f': 
  60.       return (float) array_shift($args); 
  61.     case '%b': // binary data  
  62.       return db_encode_blob(array_shift($args));  
  63.   }  
  64. }  
简单的对一些输入做了处理。参考: http://drupal.org/node/101496

原文来自于:http://www.luochunhui.com/id/315

Tags: drupal, php, escape_string