PHP

浏览模式: 标准 | 列表 | 图文
Cookie常识

Cookie常识

在制作 网页的时候,不可避免的会用到Cookie,无论是登录也好,保存状态也好,或多或少,你都会在使用Cookie这个小甜饼。

然而甜饼并不是这么好吃的,吃的过多也会有问题的,如果你的网站COOKIE数量过多,或许你的浏览器就直接打不开这个网页(这点好象是和SERVER端有关,apache接受客户端的COOKIE数量和长度也有限制)

对于用户来说,如果没有做限制的话,那么COOKIE过多会导致后一个新的COOKIE会覆盖掉前面的COOKIE。。

那么,究竟应该有多少COOKIE呢?

以下内容来自DBA Notes网站:

Cookie 是个很有趣的话题。根据 RFC 2109 的描述,每个客户端最多保持 300 个 Cookie,针对每个域名最多 20 个 Cookie (实际上多数浏览器现在都比这个多,比如 Firefox 是 50 个) ,每个 Cookie 最多 4K,注意这里的 4K 根据不同的浏览器可能不是严格的 4096 。别扯远了,对于 Cookie 最重要的就是,尽量控制 Cookie 的大小,不要塞入一些无用的信息。

所以,不要把你想知道的用户行为都采用COOKIE来保存,否则造成的后果恐怕是非常大。在一些大型网站,目前对于用户的行为已经开始逐步采用数据库来控制,这样可以记录用户的一些操作,对于用户的行为分析也能够达到的一定的效果,缺点是加大了数据库的压力。而且对于未登录网站的用户来说,他的行为将变得毫无意义

想象:将用户的一些普通行为采用Cookie保存,重要信息记录数据库。比如用户浏览过的网页记入cookie,而用户停留时间最长的网页则考虑记入数据库(当然,对于那种开着网页不关的人就无法对付了,但仍然可以通过客户端的document.scroll的高度来进行判断,再通过ajax提交 )意义不是特别大。对于一些象购物车之类的,确实可以考虑存入数据库,否则一旦网页误关闭了对于用户的体验可能并不是很好(给用户一个可选项:cookie或者数据库,但好象有点傻)。。。。。。

随便谈谈吧。。

Snoopy更新

Snoopy更新

snoopy是在系统不支持curl的情况下所采用的抓取网络信息最有用的工具之一,因为他可以模拟POST,GET等方法,而无须让你再向以前一样用fsockopen,写上一大堆代码。

这样的一个类库,在目前被PHP的使用者广泛应用着,本来以为他就这样的一直不再更新下去,不料最近还是有了一些改动,当然这些改动都是一些BUG fix,而且是安全方面的,建议下载后更新。

更新情况:

Posted By: mohrt
Date: 2008-10-22 22:54
Summary:
Snoopy 1.2.4 security fix

A security vulnerability was fixed in the latest 1.2.4 version of Snoopy. It was possible to send shell commands through https url fetches that are not properly sanitized by the PHP program using Snoopy.

下载页面为:

http://sourceforge.net/project/showfiles.php?group_id=2091

haohappy的努力

国内的PHP程序员对于haohappy应该算是比较熟悉的一位吧,很早的PHP手册翻译,他就参与了其中,《Programming PHP》第二版,就是他进行翻译的,而且他在phpchina上开了专版,说是提交了多少个勘误的,可以送一本修订版或者另一本PHP的杂志,然而我在提交了十多个BUG后,因为工作关系被我放弃了。

不过那段时间,我确实是对照了原版和他的翻译版差不多看了一遍。虽然有一些翻译在语义上和我有些区别,但这毕竟是没有办法的事情。每个人对于一件事物的理解都会有偏差,无所谓谁对谁错(当然也可能确实是我理解错了)。

对于PHP的贡献,他不止这一点,他在看到目前PHP手册没人翻译后,终于忍不住了,开始下决心对手册再次进行翻译:http://blog.csdn.net/Haohappy2004/archive/2008/12/13/3511730.aspx,http://blog.csdn.net/Haohappy2004/archive/2008/12/14/3514421.aspx;

想期待他翻译的朋友要等一段时间了,在这段时间内,大家可以去CU找honestQiao的新版本进行下载:http://bbs.chinaunix.net/thread-999247-1-1.html,或者找本站的置顶贴进行下载。

等新版的翻译好了,我也会同步到本地。一来可以自用,二来可以为使用网通的朋友们下载进行提速。哈哈

13ef0658b637852e1dbfbf5ed241d0cd

海龙CMS1.1 beta发布

海龙CMS1.1 beta发布

海龙CMS是基于ThinkPHP框架的一个PHP应用,目前看来是相对简陋了一些,但这也紧紧局限于表面,毕竟没有专业的美工,能做到这样也算是不错了,程序支持模版的切换,所以,如果你的美工够好,你一定能够做出比海龙官方更漂亮的网站。

此次更新了以下内容:

1.1 Beta
取消了产品管理
取消了产品搜索
采用Rbac进行权限控制
采用SinaEditor编辑器,支持图片和附件上传
文章分类支持到三级分类
修改了模板变量的处理方式
整合了yhustc工具箱(可到TP论坛搜索yhustc工具箱以查看详细资料)
可生成HTML(只需要后台配置一下就好了)


1.0 Final
完成了基本的文章管理、页面管理、产品管理
产品支持多字段模糊查询

演示地址:http://www.hailongol.com/hlcms/
官方下载:http://www.hailongol.com/HailongCMS.rar

本站分流:hailongcms.rar

Minify的简单介绍

上篇从老王的博客里抓了点东西,在文末我提到了minify,然后我又从nio的博客中找到minify的资料,同样贴给大家,具体的英文更新,还是可以从:http://code.google.com/p/minify/来进行获取,下面的是nio的翻译。。。

原文网址:http://nio.infor96.com/archives/862

内容如下:

Minify 是使用 PHP5 开发的用于合并压缩 js/css 文件的应用程序。合并压缩之后的结果可通过 HTTP gzip/deflate 及一些相关头,优化客户端缓存。可参考 Yahoo 的 Rules for High Performance Web Sites。

Minify 的安装使用很简单,下载最新版本,解压,将 min 目录复制到发布目录下,然后访问 http://example.com/min/,在显示的界面中加入你想合并压缩的 js/css 路径,点击 'Update' 之后会为你生成一个 url,如:

http://localhost/min/b=googletesting/js&f=mootools.js,iAction.js,iAjax.js,global.js

接下来你就可以将这个 url 放到你的页面中了。这样可以使请求数减少,传输的字节数也小了很多。而且 Minify 支持服务器端 cache,即将合并压缩的结果 cache 到服务器端文件中,下次访问就不需要再重新做合并压缩的操作了。如果需要组合的文件很多,url 就会变得很长,Minify 支持 group,可以将这些文件分组,这样 url 中只需指定 g=group名字 就可以了。

总之,Minify 很实用 :)


以下是最新更新的内容:

Version 2.1.0 (2008-09-18)

  • "min" default application for quick deployment
  • Minify URI Builder app & bookmarklet for quickly creating minify URIs
  • Relative URIs in CSS file are fixed automatically by default
  • "debug" mode for revealing original line #s in combined files
  • Better IIS support
  • Improved minifier classes:
    • JS: preserves IE conditional comments
    • CSS: smaller output, preserves more hacks and valid CSS syntax, shorter line lengths, other bug fixes
    • HTML: smaller output, shorter line lengths, other bug fixes
  • Default Cache-Control: max-age of 30 minutes
  • Conditional GETs supported even when max-age sent
  • Experimental memcache cache class (default is files)
  • Minify_Cache_File has flock()s (by default)
  • Workaround for Windows mtime reporting bug

2f06a09fb29a6e9e478c0cbd44cc95dc

dfbf186ae496a036a33eb2ce933feabd

利用PHP裁剪图片

利用PHP裁剪图片

其实,用PHP裁剪图片的原理是很简单的,无非就是用javascript画出一个方块,计算一下四个角的顶点,然后从原图中按照这四个点的坐标把当中的图切出来。

网上有现成的例子:http://www.coderhome.net/zifa/?p=351,不过里面的JS库用的是mootools的,如果要看,请直接到该网上去看,以后,等有空了,用jQuery的模拟一下,呵呵。
jQuery的插件还是很好开发的

Good and Bad PHP Code

Good and Bad PHP Code

by Kevin Yank

The following is republished from the Tech Times #165.

When interviewing a PHP developer candidate for a job at SitePoint, there is one question that I almost always ask, because their answer tells me so much about the kind of programmer they are. Here’s the question: “In your mind, what are the differences between good PHP code and bad PHP code?”

The reason I like this question is because it tests more than just a candidate’s encyclopedic knowledge of PHP’s functions. Zend’s PHP certification does a good job of that (as does the test that Yahoo! issues to applicants for its PHP developer jobs, apparently).

Rather, the answer to this question tells me whether a PHP developer has, for example, experienced the pain of working with poorly-written code inherited from a careless predecessor, and whether he or she will go the extra mile to save the rest of the team from that same pain.

I don’t have a set notion of the perfect answer to the question, but I do know the kinds of things I’m hoping to hear. Just off the top of my head:

Good PHP code should be structured. Long chunks of code can be broken up into functions or methods that achieve sub-tasks with simple code, while non-obvious snippets should be commented to make their meaning plain. As much as possible, you should separate frontend HTML/CSS/JavaScript code from the server-side logic of your applications. PHP’s object oriented programming features give you some especially powerful tools to break up your applications into sensible units.

Good PHP code should be consistent. Whether that means setting rules for the names of variables and functions, adopting standard approaches to recurring tasks like database access and error handling, or simply making sure all of your code is indented the same way, consistency makes your code easier for others to read.

Good PHP code should be portable. PHP has a number of features, such as magic quotes and short tags, that can break fragile code when they are switched on or off. If you know what you’re doing, however, you can write code that works by adapting to its environment.

Good PHP code should be secure. While PHP offers excellent performance and flexibility out of the box, it leaves important issues like security entirely in the hands of the developer. A deep understanding of potential security holes like Cross-Site Scripting (XSS), Cross-Site Request Forgeries (CSRF), code injection vulnerabilities, and character encoding loopholes is essential for a professional PHP developer these days.

Once a candidate has answered this question, I usually have a pretty good idea of whether they’ll be hired or not. Of course, there’s always the possibility that an interviewee simply isn’t able to articulate these types of things, so we also have our candidates sit a PHP developer exam.

Many of the questions in this exam seem straightforward on the surface, but they give candidates plenty of opportunity to show how much they care about the little details.

The following “bad” code is a highly simplified example of the sort of thing we might put in our PHP developer exam. The question might be something like “How would you rewrite this code to make it better?”

<?php
echo("<p>Search results for query: " .
$_GET['query'] . ".</p>");
?>

<?php
echo("<p>Search results for query: " . $_GET['query'] . ".</p>");
?>

The main problem in this code is that the user-submitted value ($_GET['query']) is output directly to the page, resulting in a Cross Site Scripting (XSS) vulnerability. But there are plenty of other ways in which it can be improved.

So, what sort of answer are we hoping for?

Good:

<?php
echo("<p>Search results for query: " .
htmlspecialchars($_GET['query']) . ".</p>");
?>


<?php
echo("<p>Search results for query: " .
htmlspecialchars($_GET['query']) . ".</p>");
?>

This is the least we expect. The XSS vulnerability has been remedied using htmlspecialchars to escape dangerous characters in the submitted value.

Better:

<?php
if (isset($_GET['query']))
{
echo '<p>Search results for query: ',
htmlspecialchars($_GET['query'], ENT_QUOTES), '.</p>';
}
?>


<?php
if (isset($_GET['query'])) {
echo '<p>Search results for query: ',
htmlspecialchars($_GET['query'], ENT_QUOTES), '.</p>';
}
?>

Now this looks like someone we might want to hire:

* The “short” opening PHP tag (<?) has been replaced with the more portable (and XML-friendly) <?php form.
* Before attempting to output the value of $_GET['query'], isset is used to verify that it actually has a value.
* The unnecessary brackets (()) around the value passed to echo have been removed.
* Strings are delimited by single quotes instead of double quotes to avoid the performance hit of PHP searching for variables to interpolate within the strings.
* Rather than using the string concatenation operator (.) to pass a single string to the echo statement, the strings to be output by echo are separated by commas for a tiny performance boost.
* Passing the ENT_QUOTES argument to htmlspecialchars to ensure that single quotes (') are also escaped isn’t strictly necessary in this case, but it’s a good habit to get into.

Somewhat distressingly, the number of PHP developers looking for work that are able to give a fully satisfactory answer to this sort of question—at least here in Melbourne—are few and far between. We spent a good three months interviewing for this latest position before we found someone with whom we were happy!

So, how would you do when asked a question like this one? Are there any factors that make PHP code good or bad that you feel I’ve left out? And what else would you look for in a PHP developer?

PHP的XSS攻击过滤函数

PHP的XSS攻击过滤函数

XSS攻击在最近很是流行,往往在某段代码里一不小心就会被人放上XSS攻击的代码,看到国外有人写上了函数,咱也偷偷懒,悄悄的贴上来。。。
原文如下:
The goal of this function is to be a generic function that can be used to parse almost any input and render it XSS safe. For more information on actual XSS attacks, check out http://ha.ckers.org/xss.html. Another excellent site is the XSS Database which details each attack and how it works.

<?php
function RemoveXSS($val) {
// remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
// this prevents some character re-spacing such as <java\0script>
// note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
$val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);

// straight replacements, the user should never need these since they're normal characters
// this prevents like <IMG SRC=@avascript:alert('XSS')>
$search = 'abcdefghijklmnopqrstuvwxyz';
$search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$search .= '1234567890!@#$%^&*()';
$search .= '~`";:?+/={}[]-_|\'\\';
for ($i = 0; $i < strlen($search); $i++) {
// ;? matches the ;, which is optional
// 0{0,7} matches any padded zeros, which are optional and go up to 8 chars

// @ @ search for the hex values
$val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
// @ @ 0{0,7} matches '0' zero to seven times
$val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
}

// now the only remaining whitespace attacks are \t, \n, and \r
$ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
$ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
$ra = array_merge($ra1, $ra2);

$found = true; // keep replacing as long as the previous round replaced something
while ($found == true) {
$val_before = $val;
for ($i = 0; $i < sizeof($ra); $i++) {
$pattern = '/';
for ($j = 0; $j < strlen($ra[$i]); $j++) {
if ($j > 0) {
$pattern .= '(';
$pattern .= '(&#[xX]0{0,8}([9ab]);)';
$pattern .= '|';
$pattern .= '|(&#0{0,8}([9|10|13]);)';
$pattern .= ')*';
}
$pattern .= $ra[$i][$j];
}
$pattern .= '/i';
$replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
$val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
if ($val_before == $val) {
// no replacements were made, so exit the loop
$found = false;
}
}
}
return $val;
}

经过这样的过滤后,应该被攻击的机会会少上很多吧?试试看呢?

使用PHP得到所有的HTTP请求头

使用PHP得到所有的HTTP请求头

PHP中一般采用getallheaders来获取头部,但事实上,有些模式下是获取不到的(以前真没有注意过在fastcgi下这个函数不能用,当然我现在也没有测试。是老王说的)

他说:

在PHP里,想要得到所有的HTTP请求头,可以使用getallheaders方法,不过此方法并不是在任何环境下都存在,比如说,你使用fastcgi方式运行PHP的话,就没有这个方法,所以说我们还需要考虑别的方法,幸运的是$_SERVER里有我们想要的东西,它里面键名以HTTP_开头的就是HTTP请求头:

$headers = array();
foreach (
$_SERVER as $key => $value) {
if (
'HTTP_' == substr($key, 0, 5)) {
$headers[str_replace('_', '-', substr($key, 5))] = $value;
}
}


代码很简单,需要说明的是RFC里明确指出了信息头的名字是不区分大小写的。

不过并不是所有的HTTP请求头都是以HTTP_开头的的键的形式存在与$_SERVER里,比如说Authorization,Content-Length,Content-Type就不是这样,所以说为了取得所有的HTTP请求头,还需要加上下面这段代码:

if (isset($_SERVER['PHP_AUTH_DIGEST'])) {
$header['AUTHORIZATION'] = $_SERVER['PHP_AUTH_DIGEST']);
} elseif (isset(
$_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
$header['AUTHORIZATION'] = base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW']));
}
if (isset(
$_SERVER['CONTENT_LENGTH'])) {
$header['CONTENT-LENGTH'] = $_SERVER['CONTENT_LENGTH'];
}
if (isset(
$_SERVER['CONTENT_TYPE'])) {
$header['CONTENT-TYPE'] = $_SERVER['CONTENT_TYPE'];
}


搞定!

网址为:http://hi.baidu.com/thinkinginlamp/blog/item/c0bff01f3beb66f2e1fe0b7e.html

Jadu: 将 PHP 编译成 .NET

新闻来源:itnews.com.au
内容管理公司 Jadu 最近发布了一个工具,可以让 PHP 和 .NET 这对冤家和平共处。他们开发了一个叫做 Phalanger PHP compiler 的工具,可以将 PHP 程序编译成本地 .NET 程序执行。他们还准备将这一工具开源。


据 Jadu CEO Suraj Kika 介绍,这个工具对 PHP 程序进行编译,编译成 .NET 框架下下的本地程序。比如,你想用 WordPress,但你属于微软阵营,你可以将 WordPress 编译成可执行文件,放到 .NET 中并在 Visual Studio 中针对这个编译过的 WordPress 做进一步开发。

这个工具将为 PHP 和 .NET 开发工程师带来职业上的便利,避免在各自对方的技术领域内再培训。Kika 表示,我们会看到大量 PHP 开发者在微软阵营找到客户群。

Kika 还表示,开源和商业软件之间向来泾渭分明,这一工具将让这两个阵营的开发者走到一起。

本文来源:http://www.itnews.com.au/News/90129,jadu-brings-php-and-net-closer-together.aspx
中文翻译:COMSHARP CMS
膘叔:好妖的功能呀,一直以为PHP要想在windows下独立运行,得使用php GTK的,结果现在居然有人编译成.net,真是心有多大,世界有多大呀