Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Wednesday, August 8, 2012

Is there any PHP function to convert current age to date?


before or on today - 18 years
after today - 19 years

before or on today - 50 years
after today - 51 years

dob <= (today -18 years) and dob > (today - 51 years)

$lower = date('Y-m-d', strtotime('today -18 years'));
$upper = date('Y-m-d', strtotime('today -51 years'));
$query = "SELECT FirstName FROM users WHERE dob >= '$lower' AND dob < '$upper';";


Note that if you plan on dates before 1970 (52-ish), you should likely use DateTime instead of date and sttrtotime (I actually only use DateTime in actual code, but date/strtotime make for much briefer examples).

An example of 85 years ago with DateTime:


$d = new DateTime('today -85 years');
$s = $d->format('Y-m-d'); //1927-06-03 as of 3 June 2012

Thursday, July 14, 2011

十大流行PHP开发框架介绍

第10位 Speedphp


Speedphp是国产框架,特别推荐初学者使用和学习,中文手册让初学者阅读起来也很容易。当然可以用来做各种复杂度的项目。同时他也支持新浪应用引擎(SAE)。

第9位 DooPHP


DooPHP自称为最快的PHP框架,对于高在线需求的网站不妨考虑一下DooPHP,不过目前面临文档过少,社区支持困难的问题。如果你是一位追求速度的高级的PHP开发者,也可以试试究竟有没有作者自称的那么快。

第8位 Drupal


Drupal,你可以把他当作一个CMS来使用,功能强大到让你难以想象,可是你又可以当作框架。做二次开发的好东西,如果你想做欧美外包,不了解Drupal是绝对不行的。值得一提的是,Drupal的社区氛围非常好,你几乎可以在官方论坛上解决任何问题。

Tuesday, April 26, 2011

Yii CJSON

[cc lang="php"] $this->layout=false;
header('Content-type: application/json');
echo CJSON::encode(array('id'=>$project->id, 'content'=>$project->content, 'pass_way'=>$project->pass_way, 'total'=>$count, 'bs'=>$project->multiple
));
Yii::app()->end(); [/cc]

Thursday, March 31, 2011

PHP pcntl_fork

[cc lang="php"]
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
// we are the parent
pcntl_wait($status); //Protect against Zombie children
} else {
// we are the child

echo "download files ...\n";
$cmd = "/usr/bin/wget --user-agent=\"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;)\" \\
--header=\"Accept:text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\" \\
--header=\"Accept-Language: en-us,en;q=0.5\" \\
--header=\"Accept-Encoding: gzip,deflate\" \\
--header=\"Accept-Charset: GBK,utf-8;q=0.7,*;q=0.7\" \\
--header=\"Keep-Alive: 300\" -O /dev/null -i list.txt -o wget.log";
exec($cmd);
echo "done\n";
declare(ticks = 1);

pcntl_signal(SIGUSR1, function ($signal) {
echo 'HANDLE SIGNAL ' . $signal . PHP_EOL;
});

posix_kill(posix_getpid(), SIGUSR1);
die();
}
[/cc]

Friday, March 11, 2011

Caching WordPress with Varnish

WordPress is a fantastic application that lets you get a website up and running in a matter of minutes. Not only that, but you require absolutely no knowledge of how to code to do so. As with many web applications though, it needs a little help in getting it to perform better. Lots of these dynamic apps breaks caching by using lots of cookies and setting headers like Cache-Control and Pragma. For a better in-depth tutorial on caching, read this article.

Requirements



  • Web server running on a different port than the standard one (TCP/80)

  • Varnish installed


Configuration


The standard location for Varnish’s configuration file is located at/etc/varnish/default.vcl. You will find below the configuration I use on this blog. See the comments to get a better understanding of what’s what. Also, make sure varnish will listen on port TCP/80 (use the -a flag when you start the daemon).
# Send all requests to your webserver
backend default {
.host = "127.0.0.1";
.port = "8080";
}

sub vcl_recv {
# If we don't set this, in our webserver's logs, we'll get varnish's IP instead
# of the real client's IP
if (req.http.x-forwarded-for) {
set req.http.X-Forwarded-For =
req.http.X-Forwarded-For ", " client.ip;
} else {
set req.http.X-Forwarded-For = client.ip;
}
if (req.request != "GET" && req.request != "HEAD") {
return (pass);
}
# Unless we're in the admin/login section, remove all cookies
if (!(req.url ~ "wp-(login|admin)")) {
unset req.http.cookie;
}
return (lookup);
}

sub vcl_pipe {
return (pipe);
}

sub vcl_pass {
return (pass);
}

sub vcl_hash {
set req.hash += req.url;
if (req.http.host) {
set req.hash += req.http.host;
} else {
set req.hash += server.ip;
}
return (hash);
}

sub vcl_hit {
if (!obj.cacheable) {
return (pass);
}
return (deliver);
}

sub vcl_miss {
return (fetch);
}

sub vcl_fetch {
if (!beresp.cacheable) {
return (pass);
}
if (beresp.http.Set-Cookie) {
return (pass);
}
if (!(req.url ~ "wp-(login|admin)")) {
unset req.http.cookie;
}
return (deliver);
}

sub vcl_deliver {
# Remove bad headers
remove resp.http.X-Varnish;
remove resp.http.Via;
remove resp.http.Age;
remove resp.http.X-Powered-By;
remove resp.http.Cache-Control;
remove resp.http.Pragma;
return (deliver);
}

Restart Varnish to load the new configuration.

Testing the recipe


Open up varnishstat in your terminal. You should see some stats. Ctrl-F5 a few times your site in your favorite browser. That way, you’re telling your browser to bypass its own cache and ask the site for fresh items. The first time you access your site, you will get lots of misses, but after that, you should get lots of cache hits.
Hitrate ratio:        9        9        9
Hitrate avg:     0.7302   0.7302   0.7302
22         0.00         0.16 Client connections accepted
132         0.00         0.95 Client requests received
100         0.00         0.72 Cache hits
5         0.00         0.04 Cache hits for pass
25         0.00         0.18 Cache misses

As you can see, I’m getting about 4 times more cache hits than misses. This way, Varnish will server all the static items and will let your webserver take care of all the dynamic content. Hope this helps a bit.

 

Wednesday, January 26, 2011

Kohana 3 - .htaccess that Works on DreamHost

I’m currently hosting my sites on DreamHost because … well let me just put it this way: we’re both cheap. It works out. But what doesn’t work out are the default .htaccess rules that come bundled with Kohana. So to fix this, swap the line [cci lang="apache"]RewriteRule .* index.php/$0 [PT][/cci] found in your .htaccess with one of the following options:

[cc lang="text"]# Option 1
RewriteRule .* index.php?/$0 [PT,L,QSA]

# Option 2
RewriteRule .* index.php?kohana_uri=$0 [PT,L,QSA][/cc]

Monday, January 24, 2011

Saturday, November 27, 2010

PHP二维数组排序函数

[cc lang="php"]
// 二维数组排序函数
function sysSortArray($ArrayData,$KeyName1,$SortOrder1 = "SORT_ASC",$SortType1 = "SORT_REGULAR")
{
if(!is_array($ArrayData))
{
return $ArrayData;
}
// Get args number.
$ArgCount = func_num_args();
// Get keys to sort by and put them to SortRule array.
for($I = 1;$I < $ArgCount;$I ++)
{
$Arg = func_get_arg($I);
if(!eregi("SORT",$Arg))
{
$KeyNameList[] = $Arg;
$SortRule[] = '$'.$Arg;
}
else
{
$SortRule[] = $Arg;
}
}
// Get the values according to the keys and put them to array.
foreach($ArrayData AS $Key => $Info)
{
foreach($KeyNameList AS $KeyName)
{
${$KeyName}[$Key] = $Info[$KeyName];
}
}

// Create the eval string and eval it.
$EvalString = 'array_multisort('.join(",",$SortRule).',$ArrayData);';
eval ($EvalString);
return $ArrayData;
} [/cc]

PHP组合排列数组函数

[cc lang="php"]
private function combination($ar, $num) {
$control = range(0, $num-1);
$k = false;
$total = count($ar);
while($control[0] < $total-($num-1)) {
$t = array();
for($i=0; $i <$num; $i++) $t[] = $ar[$control[$i]];
$r[] = $t;

for($i=$num-1; $i>=0; $i--) {
$control[$i]++;
for($j=$i; $j <$num-1; $j++) $control[$j+1] = $control[$j]+1;
if($control[$i] < $total-($num-$i-1)) break;
}
}
return $r;
} private function combination($ar, $num) {
$control = range(0, $num-1);
$k = false;
$total = count($ar);
while($control[0] < $total-($num-1)) {
$t = array();
for($i=0; $i <$num; $i++) $t[] = $ar[$control[$i]];
$r[] = $t;

for($i=$num-1; $i>=0; $i--) {
$control[$i]++;
for($j=$i; $j <$num-1; $j++) $control[$j+1] = $control[$j]+1;
if($control[$i] < $total-($num-$i-1)) break;
}
}
return $r;
}[/cc]

Wednesday, October 13, 2010

精通php的十大要点

1. 在合适的时候使用PHP - Rasmus Lerdorf

没有谁比PHP的创建者Rasmus Lerdorf明白PHP用在什么地方是更合理的, 他于1995年发布了PHP这门语言,从那时起,PHP就像燎原之火,烧遍了整个开发阵营,改变了互联网的世界。 可是, Rasmus并不是因此而创建PHP的 PHP是为了解决web开发者的实际问题而诞生的。
和许多开源项目一样,PHP变得流行,流行的动机并不能用正常的哲学来进行解释,甚至流行得有些孤芳自赏。它完全可以作为一个案例,一个解决各种web问题的工具需求所引起的案例,因此当PHP刚出现的时候,这种工具需求全部聚焦到PHP的身上。

但是,你不能奢望PHP可以解决所有问题。Lerdorf是第一个承认PHP只是一种工具的人,并且PHP也有很多力所不能及的情况。
根据工作的不同来选择合适的工具。我跑了很多家公司,为了说服他们部署和使用PHP,但是这并不意味着PHP对所有问题都适用。它只是可以一个解决大部分问题的front-end脚步语言。

作为一个web开发者,尝试用PHP解决所有问题是不科学的,同时也会浪费你的时间。当PHP玩不转的时候,不要犹豫,试用一下其他的语言吧。

服务器端PHP多进程编程实战

最近比较PHP跟python, Erlang 的特性,发现PHP有很多人们不常用到的特性。用PHP CLI可以实现很多不错的应用。比如做爬虫, 长期运行的计算脚本, 完全可以取代其他语言来做 服务器的运维。这对于熟悉PHP的人来说如虎添翼。

为什么PHP多进程很好? 网游服务器大部分都使用多线程而不是多进程的原因也在于进程比线程更加稳定。而且多线程适合现在多核服务器的应用场景,更能发挥多核运算的能力。进程的维护可以用很多操作系统级别的工具。Message Queue解决了多大部分线程通信问题。所以PHP多进程很适合做服务器端的计算密集型的应用。

据一家越南IT公司介绍,他们成功的把PHP后台多进程用在法律文件的分发、处理银行账户的金额这样的企业级的应用上。

PHP加Shell实现多进程

看到这个标题,大家可能要说我没常识,php根本不支持多线程啊,没错,php本身是不支持多线程,但是别忘了php的好搭档,apache和linux可是支持的,呵呵,lamp才是最佳组合,还在使用win服务器的现在知道为什么要用linux吧?好久没在phpchina说教了,今天水一帖,写个简单的代码演示下如何借助shell脚本实现多线程。

先写个简单的php代码,这里为了让脚本执行时间更长,方便看效果,sleep一下,呵呵!先看下test.php的代码:

[cc lang='php' line_numbers='false']
for ($i=0;$i<10;$i++) {
echo $i;
sleep(10);
}
[/cc]
在看下shell脚本的代码,非常简单

[cc lang='bash' line_numbers='false']#!/bin/bash
for i in 1 2 3 4 5 6 7 8 9 10
do
/usr/bin/php -q /var/www/html/test.php &
done[/cc]
注意到在请求php代码的那行有一个&符号吗,这个是关键,不加的话是不能进行多线程的,&表示讲服务推送到后台执行,因此,在shell的每次的循环中不必等php的代码全部执行完在请求下一个文件,而是同时进行的,这样就实现了多线程,下面运行下shell看下效果,这里你将看到10个test.php进程再跑,再利用linux的定时器,定时请求这个shell,在处理一些需要多线程的任务,例如,批量下载时,非常好用!

Tuesday, October 12, 2010

Emacs PHP 数组缩进问题解决

[cc lang='lisp' ]
(add-hook 'php-mode-hook
(lambda ()
(c-set-style "bsd")
(setq c-indent-level 4)
(setq c-continued-statement-offset 4)
(setq c-brace-offset -4)
(setq c-argdecl-indent 0)
(setq c-label-offset -4)
(setq c-basic-offset 4)
(setq tab-width 4)
(setq indent-tabs-mode nil)
(c-set-offset 'case-label '+)
(c-set-offset 'arglist-close 'c-lineup-arglist-operators)
(c-set-offset 'arglist-intro '+)
(c-set-offset 'arglist-cont-nonempty 'c-lineup-math)))

[/cc]

Saturday, August 28, 2010

Facebook后台技术探秘




今天我们一起来了解Facebook背后的软件,看看作为当今世界上访问量最大的网站之一,Facebook是如何保证5亿用户的系统一直稳定可靠的运行。

Facebook的扩展性挑战

在我们讨论细节之前,这里有一些Facebook已经做的软件规模:

  • Facebook有570000000000每月页面浏览量 (据Google Ad Planner)

  • Facebook的照片量比其他所有图片网站加起来还多(包括Flickr等网站)

  • 每个月超过30亿张照片被上传

  • Facebook的系统服务每秒处理120万张照片,这不包括CDN服务中处理的照片

  • 每月超过25亿条的内容 (状态更新,评论等)被共享

  • Facebook有超过30,000服务器(这个数字是去年的)


Poppen.de网站架构

在了解过世界最大的PHP站点,Facebook的后台技术后,今天我们来了解一个百万级PHP站点的网站架构:Poppen.de。Poppen.de是德国的一个社交网站,相对Facebook、Flickr来说是一个很小的网站,但它有一个很好的架构,融合了很多技术,如 Nigix、MySql、CouchDB、Erlang、Memcached、RabbitMQ、PHP、Graphite、Red5以及Tsung。

Poppen.de目前有200万注册用户数、2万并发用户数、每天20万条私有消息、每天25万登录次数。而项目团队有11个开发人员,两个设计,两个系统管理员。该站点的商业模式采用免费增值模式,用户可以使用搜索用户、给好友发送消息、上载图片和视频等功能。

如果用户想享受不受限制发送消息和上载图片,那么就得根据需要支付不同类型的会员服务,视频聊天及网站其他服务也采用同样的策略。

Saturday, August 21, 2010

How to get current controller name and action name in Yii

To get current controller name/id inside your controller, or view
[cc lang='php']$controllerId = Yii::app()->controller->id;
//or
$controllerId = $this->getId();[/cc]
To get current action name/id being executed, if you are inside [cci]beforeAction()[/cci] or [cci]afterAction()[/cci], use the received CAction argument
[cc lang='php']
//inside beforeAction or afterAction
public function beforeAction($action)
{
$actionId = $action->id;
...
[/cc]
or just elsewhere inside your controller

[cc lang='php']$actionId = $this->getAction()->getId();[/cc]

Tuesday, March 2, 2010

Drupal的theme开发

昨天在drupal7上搞了搞theme,发现alpha2还有一些地方不对。drupal比较麻烦的一个地方是更改了 theme.info 文件非要disable之后再enable才能生效。

drupal6应该还会主流一段时间,感觉drupal7的js太多了,非要那么多js吗?

如果用drupal6来开发一个门户站点效果如何,人员分配如何?我想国内很多设计师达不到这个要求,xhtml,css,js,php,sql 都要懂,xhtml,css,js精通。如果drupal精通,架构一个行业门户或者生活类的站点是非常高效的,至于优化,可以在服务器上下功夫。

Sunday, September 27, 2009

Squid缓存PHP页面方法


header('Cache-Control: max-age=600, must-revalidate');
header('Pragma: cache');
header('Last-Modified: ' . date('D, d M Y H:i:s') . ' GMT');
header('Expires: ' . date ("D, d M Y H:i:s", time() + 600). " GMT");

Monday, September 21, 2009

YII 数据库连接(MySQL)


'class'=>'CDbConnection',
'connectionString'=>'mysql:host=localhost;dbname=yiiblog;unix_socket=/opt/lampp/var/mysql/mysql.sock',
'username'=>'root',
'password'=>'password',
'charset'=>'utf8',

Wednesday, August 5, 2009