顯示具有 PHP 標籤的文章。 顯示所有文章
顯示具有 PHP 標籤的文章。 顯示所有文章

2011/03/23

在開始上傳前檢查檔案大小(IE僅能檢查圖片)

這篇其實不是單純只能檢查圖片而已,連一般檔案都可以檢查。目前還沒在Safari瀏覽器上實驗過就是了。
2011/3/24 04:18 剛確認了IE如果是圖片以外的檔案,確實要用額外的方式處理。

[JavaScript] 在開始上傳前檢查圖片檔案大小
最近有此功能需求,因此查了些相關的資料,最後在不使用 Flash 及 ActiveX 等技術的情況下,只用JavaScript完成了多瀏覽器的功能實作,在此分享。

目前已測試過的瀏覽器:IE 6 , IE 7 , IE 8 , Firefox , Chrome;另外 Firefox 與 Chrome 的版本須為支援 Html 5 的版本。


以下為 HTML (此部分與 Bryan(不來ㄣ)大大的版本相同 ):
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=big5">
    <title>上傳</title>
</head>
<body>
    <form action="upload.asp" method="POST" name="FileForm" enctype="multipart/form-data">
    <div align="center">
        圖片:
    <input type="file" name="file1" size="20" id="file1" />
    <input type="button" value="確定上傳" onclick="checkFile()" /></div>
    </form>
</body>
</html>


以下為 JavaScript:
<script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
    var fileSize = 0; //檔案大小
    var SizeLimit = 1024; //上傳上限,單位:byte
    function checkFile() {
    var f = document.getElementById("file1");
    //FOR IE
    if ($.browser.msie) {
            var img = new Image();
            img.onload = checkSize;
            img.src = f.value;
        }
        //FOR Firefox,Chrome
        else {
            fileSize = f.files.item(0).size;
            checkSize();
        }
    }
    //檢查檔案大小
    function checkSize() {
        //FOR IE FIX
        if ($.browser.msie) {
            fileSize = this.fileSize;
        }
        if (fileSize > SizeLimit) {
            Message((fileSize / 1024).toPrecision(4), (SizeLimit / 1024).toPrecision(2));
        } else {
            document.FileForm.submit();
        }
    }
    function Message(file, limit) {
        var msg = "您所選擇的檔案大小為 " + file + " kB\n已超過上傳上限 " + limit + " kB\n不允許上傳!"
        alert(msg);
    }
</script>

參考資料:
topcat 姍舞之間的極度凝聚 - [轉貼]上傳檔案前,JavaScript檢查檔案格式、大小:http://www.dotblogs.com.tw/topcat/archive/2009/02/20/7250.aspx (Bryan(不來ㄣ)大大的版本 – For IE)
簡單過生活 - Check 上傳檔案大小:http://iammic.pixnet.net/blog/post/11866034 (iammic大大的版本 – For IE[ActiveX] & Firefox , Chrome)

2010/09/22 更新:
在 o 大大的指正後,將標題略為修改為針對圖片檔案的上傳之檔案大小的檢查,以避免因標題誤導了想找資料的訪客。
另外,在支援 HTML 5 的 Firefox 與 Chrome 的瀏覽器版本上,是可正確抓到各類型檔案大小的;而 IE 瀏覽器仍須透過 Flash 或 ActiveX 等技術才能取得圖片類型以外的檔案大小,在此作以上更正。

2010/11/17

[PHP]解決網站被 SQL injection 攻擊

其實這個安全性的問題,在目前台灣網站都存在這樣的問題,大家平常用 $_POST,$_GET 用得很順利,但是沒有想過帳號密碼被 SQL injection 破解,當網站被破解了,基本上你損失就是相當嚴重,網路上也有很多攻擊方式,不過這方法是最常被拿出來講的,我自己有一套解決方式,除了比較重要的地方,就是輸入帳號密碼的地方要加強防護之外,加上數字驗證碼,還要 check 帳號的特性,我底下是我驗證帳號密碼機制

if($user_name == '' || $user_passwd == ''){
ErrMsg("帳號或密碼不得空白");
}
if (!preg_match('/^\w+$/', $user_name)){
ErrMsg("請勿攻擊本站台");
}


上面可以解決帳號只能輸入數字加上英文,然後底下在過濾很多特殊字元加上 addslashes 或者是用 mysql_escape_string()

if( !get_magic_quotes_gpc() )
{
if( is_array($_GET) )
{
while( list($k, $v) = each($_GET) )
{
if( is_array($_GET[$k]) )
{
while( list($k2, $v2) = each($_GET[$k]) )
{
$_GET[$k][$k2] = addslashes($v2);
}
@reset($_GET[$k]);
}
else
{
$_GET[$k] = addslashes($v);
}
}
@reset($_GET);
}

if( is_array($_POST) )
{
while( list($k, $v) = each($_POST) )
{
if( is_array($_POST[$k]) )
{
while( list($k2, $v2) = each($_POST[$k]) )
{
$_POST[$k][$k2] = addslashes($v2);
}
@reset($_POST[$k]);
}
else
{
$_POST[$k] = addslashes($v);
}
}
@reset($_POST);
}

if( is_array($_COOKIE) )
{
while( list($k, $v) = each($_COOKIE) )
{
if( is_array($_COOKIE[$k]) )
{
while( list($k2, $v2) = each($_COOKIE[$k]) )
{
$_COOKIE[$k][$k2] = addslashes($v2);
}
@reset($_COOKIE[$k]);
}
else
{
$_COOKIE[$k] = addslashes($v);
}
}
@reset($_COOKIE);
}
}

上面那段,可以避免利用特殊字元做 SQL injection 攻擊,這部份程式碼是我去 trace PHPBB2 code 裡面寫的^^。

文章來源:[PHP]解決網站被 SQL injection 攻擊

2010/11/01

PHP Check and Validate

<?php

class check{

var $bench_start = 0;

function check(){
}

function check_int($value){
$help = (int)$value;
if(strcmp($help, $value)){
return false;
}
else{
return true;
}
}

function check_empty($value, $type = 1){
if($type == 0){
if(empty($value)){
return true;
}
else{
return false;
}
}
else{
if(!empty($value) || $value == "0"){
return true;
}
else{
return false;
}
}
}

function get_max($value_arr){
$max = $value_arr[0];
$i = 0;
$arr_index = $i;
foreach($value_arr as $val){
if($val > $max){
$max = $val;
$arr_index = $i;
}
$i++;
}
$return["arr_index"] = $arr_index;
$return["max_val"] = $max;
return $return;
}

function get_min($value_arr){
$min = $value_arr[0];
$i = 0;
$arr_index = $i;
foreach($value_arr as $val){
if($val < $min){
$min = $val;
$arr_index = $i;
}
$i++;
}
$return["arr_index"] = $arr_index;
$return["min_val"] = $min;
return $return;
}

function max($value, $max){
if($value > $max){
return false;
}
else{
return true;
}
}

function min($value, $min){
if($value < $min){
return false;
}
else{
return true;
}
}

function max_strlen($string, $max){
if(strlen($string) > $max){
return false;
}
else{
return true;
}
}

function min_strlen($string, $min){
if(strlen($string) < $min){
return false;
}
else{
return true;
}
}

function check_email($value){
$reg_exp="^($-!#\$%&'*+./0-9=?A-Z^_`a-z{|}~�])+@($-!#\$%&'*+/0-9=?A-Z^_`a-z{|}~�]+\\.)+$a-zA-Z]{2,6}\$";
$is_valid = eregi($reg_exp, $value);
if(!$is_valid){
return false;
}
else{
return true;
}
}

function check_plz($value, $check_strlen = 1){
$help = $value;
$first_letter = substr($value, 0, 1);
$is_null = false;
if(!strcmp($first_letter, "0")){
$is_null = true;
}
$plz= (int)$value;
if($is_null){
$plz = "0".$plz;
}
switch($check_strlen){
case 1:
if(strcmp($plz, $help) || strlen($plz) <5){
return false;
}
else{
return true;
}
break;
case 0:
if(strcmp($plz, $help)){
return false;
}
else{
return true;
}
break;
default:
echo "False type for check_strlen";
}
}

function sum($val_array = array(), $sum_val){
$sum = 0;
foreach($val_array as $val){
$sum += $val;
}
if($sum == $sum_val){
return true;
}
else{
return false;
}
}

function check_date($date){
$d = explode(".", $date);
if(strlen(@$d$2]) > 2){
@$d$2] = substr($d$2], strlen($d$2]) - 2 , 2);
}
if(checkdate(@$d$1], @$d$0], @$d$2])){
return true;
}
else{
return false;
}
}

function german_chars($string){
$string = str_replace("A", "&Auml;", $string);
$string = str_replace("O", "&Ouml;", $string);
$string = str_replace("U", "&Uuml;", $string);
$string = str_replace("a", "&auml;", $string);
$string = str_replace("o", "&ouml;", $string);
$string = str_replace("u", "&uuml;", $string);
$string = str_replace("s", "&szlig;", $string);
$string = str_replace("e", "&eacute;", $string);
return $string;
}

function is_hostname($url){
// (type of stream )(domain ).(tld )
$reg_exp = "/^(http:\/\/|https:\/\/|ftp:\/\/|ftps:\/\/)*($a-z]{1,}$\w-.]{0,}).($a-z]{2,6})$/i";
if(!preg_match($reg_exp, $url, $result)){
return false;
}
return true;
}

function is_url($url){
// (type of stream )(domain ).(tld )(scriptname or dirs )
$reg_exp = "/^(http:\/\/|https:\/\/|ftp:\/\/|ftps:\/\/)($a-z]{1,}$\w-.]{0,}).($a-z]{2,6})(\/{1}$\w_]{1}$\/\w-&?=_%]{0,}(.{1}$\/\w-&?=_%]{0,})*)*$/i";
if(!preg_match($reg_exp, $url, $result)){
return false;
}
return true;
}

function base_convert($num, $from){
$result["binary"] = base_convert($num, $from, 2);
$result["octal"] = base_convert($num, $from, 8);
$result["decimal"] = base_convert($num, $from, 10);
$result["hex"] = base_convert($num, $from, 16);
return $result;
}

function random_nr($min = 0, $max = 100000000000000){
return (mt_rand($min, $max));
}

function random_text($prefix = "generate_random_id"){
return md5(uniqid($prefix));
}

function microtime(){
$time = microtime();
$time = explode(" ", $time);
return $time[1] + $time[0];
}

function start_benchmark(){
$GLOBALS["bench_start_time"] = check::microtime();
}

function stop_benchmark(){
$GLOBALS["bench_end_time"] = check::microtime();
$time = $GLOBALS["bench_end_time"] - $GLOBALS["bench_start_time"];
$time = explode(".", $time);
$time[1] = substr($time[1], 0, 4);
$days = 0;
$hours = 0;
$mins = 0;
$seconds = $time[0];
while($seconds > 60){
$mins++;
$seconds -= 60;
}
while($mins > 60){
$hours++;
$mins -= 60;
}
while($hours > 24){
$days++;
$hours -= 24;
}
$durability = $days." 耗時 ".$hours." 時 ".$mins." 分 ".$seconds.".".$time[1]." 秒";
echo "<br><b>腳本時間: ".$durability."</b>";
}

function debug($array, $blank=0, $echo_class=0){
$multi = false;
if(is_object($array) && !$echo_class){
echo "<b>調試的對象: ".get_class($array)."</b><br>";
$multi = true;
}
if(is_array($array) && !$echo_class){
echo "<b>調試一個陣列</b><br>";
$multi = true;
}
if(!$multi && !$echo_class){
echo "<b>單變數調試</b><br>";
echo $array;
}
else{
$blanks = "";
for($i=0; $i<$blank; $i++){
$blanks .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
}
while(list($key, $val) = each ($array)){
if(is_array($val) || is_object($val)){
if(is_object($val)){
echo $blanks.$key." => "."<b>".$val." ".get_class($val)."</b><br>";
}
else{
echo $blanks.$key." => "."<b>".$val."</b><br>";
}
debug($val, $blank+1, 1);
}
else{
echo $blanks.$key." => ".$val."<br>";
}
}
}
}

function object_info($object){
$methods = get_class_methods(get_class($object));
$vars = get_class_vars(get_class($object));
echo "<b>概述對象類:".get_class($object)."</b><br>";
echo "<b>父類:".get_parent_class($object)."</b><br>";
echo "<b>概述方法類:<br></b>";
foreach($methods as $method){
echo "&nbsp;&nbsp;&nbsp;&nbsp;".$method."<br>";
}
echo "<b>概述變量類: (名稱 => 預設值)<br></b>";
foreach($vars as $var => $val){
echo "&nbsp;&nbsp;&nbsp;&nbsp;".$var." => ".$val."<br>";
}
}
}
?>



<?php
/**
* Validation class for validation of misc strings
*
* @author Sven Wagener <wagener_at_indot_de>
* @include Funktion:_include_
*/
class validate{
var $country_code;
var $string;

/**
* Regular expressions for postcode of the following countries
* at = austria
* au = australia
* ca = canada
* de = german
* ee = estonia
* nl = netherlands
* it = italy
* pt = portugal
* se = sweden
* uk = united kingdom
* us = united states
**/
var $pattern_postcode=array(
'at'=>'^$0-9]{4,4},
'au'=>'^$2-9]$0-9]{2,3},
'ca'=>'^$a-zA-Z].$0-9].$a-zA-Z].\s$0-9].$a-zA-Z].$0-9].',
'de'=>'^$0-9]{5,5},
'ee'=>'^$0-9]{5,5},
'nl'=>'^$0-9]{4,4}\s$a-zA-Z]{2,2},
'it'=>'^$0-9]{5,5},
'pt'=>'^$0-9]{4,4}-$0-9]{3,3},
'se'=>'^$0-9]{3,3}\s$0-9]{2,2},
'uk'=>'^($A-Z]{1,2}$0-9]{1}$0-9A-Z]{0,1}) ?($0-9]{1}$A-Z]{1,2}),
'us'=>'^$0-9]{5,5}$\-]{0,1}$0-9]{4,4}'

);

var $pattern_email='^($a-zA-Z0-9_\-\.]+)@((\$0-9]{1,3}\.$0-9]{1,3}\.$0-9]{1,3}\.)|(($a-zA-Z0-9\-]+\.)+))($a-zA-Z]{2,4}|$0-9]{1,3})(\]?)$ ';
var $pattern_ip='($0-9]{1,3}\.$0-9]{1,3}\.$0-9]{1,3}\.$0-9]{1,3})';
var $pattern_url='^(http|ftp)://(www\.)?.+\.(com|net|org);

/**
* The constructor of the validation class
* @param string $string the string which have to be validated
* @desc The constructor of the validation class
*/
function validate($string){
$this->string=$string;
}

/**
* Validates the string if it consists of alphabetical chars
* @param int $num_chars the number of chars in the string
* @param string $behave defines how to check the string: min, max or exactly number of chars
* @desc Validates the string if it consists of alphabetical chars
*/
function alpha($num_chars,$behave){
if($behave=="min"){
$pattern="^$a-zA-Z]{".$num_chars.",}$";
}else if ($behave=="max"){
$pattern="^$a-zA-Z]{0,".$num_chars."}$";
}else if ($behave=="exactly"){
$pattern="^$a-zA-Z]{".$num_chars.",".$num_chars."}$";
}
return ereg($pattern,$this->string);
}

/**
* Validates the string if it consists of lowercase alphabetical chars
* @param int $num_chars the number of chars in the string
* @param string $behave defines how to check the string: min, max or exactly number of chars
* @desc Validates the string if it consists of lowercase alphabetical chars
*/
function alpha_lowercase($num_chars,$behave){
if($behave=="min"){
$pattern="^$a-z]{".$num_chars.",}$";
}else if ($behave=="max"){
$pattern="^$a-z]{0,".$num_chars."}$";
}else if ($behave=="exactly"){
$pattern="^$a-z]{".$num_chars.",".$num_chars."}$";
}
return ereg($pattern,$this->string);

}

/**
* Validates the string if it consists of uppercase alphabetical chars
* @param int $num_chars the number of chars in the string
* @param string $behave defines how to check the string: min, max or exactly number of chars
* @desc Validates the string if it consists of uppercalse alphabetical chars
*/
function alpha_uppercase($num_chars,$behave){
if($behave=="min"){
$pattern="^$A-Z]{".$num_chars.",}$";
}else if ($behave=="max"){
$pattern="^$A-Z]{0,".$num_chars."}$";
}else if ($behave=="exactly"){
$pattern="^$A-Z]{".$num_chars.",".$num_chars."}$";
}
return ereg($pattern,$this->string);

}

/**
* Validates the string if it consists of numeric chars
* @param int $num_chars the number of chars in the string
* @param string $behave defines how to check the string: min, max or exactly number of chars
* @desc Validates the string if it consists of numeric chars
*/
function numeric($num_chars,$behave){
if($behave=="min"){
$pattern="^$0-9]{".$num_chars.",}$";
}else if ($behave=="max"){
$pattern="^$0-9]{0,".$num_chars."}$";
}else if ($behave=="exactly"){
$pattern="^$0-9]{".$num_chars.",".$num_chars."}$";
}
return ereg($pattern,$this->string);
}

/**
* Validates the string if it consists of alphanumerical chars
* @param int $num_chars the number of chars in the string
* @param string $behave defines how to check the string: min, max or exactly number of chars
* @desc Validates the string if it consists of alphanumerical chars
*/
function alpha_numeric($num_chars,$behave){
if($behave=="min"){
$pattern="^$0-9a-zA-Z]{".$num_chars.",}$";
}else if ($behave=="max"){
$pattern="^$0-9a-zA-Z]{0,".$num_chars."}$";
}else if ($behave=="exactly"){
$pattern="^$0-9a-zA-Z]{".$num_chars.",".$num_chars."}$";
}
return ereg($pattern,$this->string);
}

/**
* Validates the string if its a valid postcode
* @param string $country_code the country code for the country of the postcode (de,en)
* @desc Validates the string if its a valid postcode
*/
function postcode($country_code){
if(array_key_exists($country_code,$this->pattern_postcode)){
return ereg($this->pattern_postcode$country_code],$this->string);
}else{
return false;
}
}

/**
* Validates the string if its a valid email address
* @desc Validates the string if its a valid email adress
*/
function email(){
return ereg($this->pattern_email,$this->string);
}

/**
* Validates the string if its a valid ip address
* @desc Validates the string if its a valid ip address
*/
function ip_address(){
return ereg($this->pattern_ip,$ip);
}

/**
* Validates the string if its a valid URL
* @desc Validates the string if its a valid URL
*/
function url(){
return ereg($this->pattern_url,$ip);
}
}
?>

2009/11/17

PHP Session相關說明

http://blog.chinaunix.net/u/27731/showart_259031.html

cmpan(at)qq.com
流水孟春
lib.cublog.cn

转载请注


1. PHPCOOKIE


cookie 是一种在远程浏览器端储存数据并以此来跟踪和识别用户的机制。
PHP
http协议的头信息里发送cookie, 因此 setcookie() 函数必须在其它信息被输出到浏览器前调用,这和对 header() 函数的限制类似。

1.1
设置cookie:
   
可以用 setcookie() setrawcookie() 函数来设置 cookie。也可以通过向客户端直接发送http头来设置.
1.1.1
使用setcookie()函数设置cookie:
bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure [, bool httponly]]]]]] )
    
name:   cookie
变量名
     value:   cookie
变量的值
     expire: 
有效期结束的时间,
     path:   
有效目录,
     domain:
有效域名,顶级域唯一
     secure: 
如果值为1,cookie只能在https连接上有效,如果为默认值0,httphttps都可以.
例子:
<?php
$value = 'something from somewhere';

setcookie("TestCookie", $value); /* 简单cookie设置 */
setcookie("TestCookie", $value, time()+3600); /* 有效期1个小时 */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", ".example.com", 1); /* 有效目录 /~rasmus,有效域名example.com及其所有子域名 */
?>


设置多个cookie变量: setcookie('var[a]','value');用数组来表示变量,但他的下标不用引号.这样就可以用$_COOKIE[‘var’][‘a’]来读取该COOKIE变量.

1.1.2.
使用header()设置cookie;
header("Set-Cookie: name=$value[;path=$path[;domain=xxx.com[;...]]");
后面的参数和上面列出setcookie函数的参数一样.
比如:


$value = 'something from somewhere';
header("Set-Cookie:name=$value");

1.2 Cookie的读取:

直接用php内置超级全局变量 $_COOKIE就可以读取浏览器端的cookie.
上面例子中设置了cookie"TestCookie",现在我们来读取:


print $_COOKIE['TestCookie'];

COOKIE是不是被输出了?!

1.3 删除cookie
只需把有效时间设为小于当前时间, 和把值设置为空.例如:
setcookie("name","",time()-1);
header()类似.


1.4 常见问题解决:

1) 用setcookie()时有错误提示,可能是因为调用setcookie()前面有输出或空格.也可能你的文档使从其他字符集转换过来,文档后面可能带有BOM签名(就是在文件内容添加一些隐藏的BOM字符).解决的办法就是使你的文档不出现这种情况.还有通过使用ob_start()函数有也能处理一点.
2) $_COOKIEmagic_quotes_gpc影响,可能自动转义
3) 使用的时候,有必要测试用户是否支持cookie
<!--[if !supportLineBreakNewLine]-->


1.5 cookie工作机理:

有些学习者比较冲动,没心思把原理研究,所以我把它放后面.
a) 服务器通过随着响应发送一个
httpSet-Cookie,在客户机中设置一个cookie(多个cookie要多个头).
b) 客户端自动向服务器端发送一个httpcookie,服务器接收读取.


HTTP/1.x 200 OK
X-Powered-By: PHP/5.2.1
Set-Cookie: TestCookie=something from somewhere; path=/
Expires: Thu, 19 Nov 2007 18:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-type: text/html

这一行实现了cookie功能,收到这行后
Set-Cookie: TestCookie=something from somewhere; path=/
浏览器将在客户端的磁盘上创建一个cookie文件,并在里面写入:


TestCookie=something from somewhere;
/

这一行就是我们用setcookie('TestCookie','something from somewhere','/');的结果.也就是用header('Set-Cookie: TestCookie=something from somewhere; path=/');的结果.
<!--[endif]-->








2. PHPSession

session使用过期时间设为0cookie,并且将一个称为session ID的唯一标识符(一长串字符串),在服务器端同步生成一些session文件(可以自己定义session的保存类型),与用户机关联起来.web应用程序存贮与这些session相关的数据,并且让数据随着用户在页面之间传递.

访问网站的来客会被分配一个唯一的标识符,即所谓的会话 ID。它要么存放在客户端的 cookie,要么经由 URL 传递。

会话支持允许用户注册任意数目的变量并保留给各个请求使用。当来客访问网站时,PHP 会自动(如果 session.auto_start 被设为 1)或在用户请求时(由 session_start() 明确调用或 session_register() 暗中调用)检查请求中是否发送了特定的会话 ID。如果是,则之前保存的环境就被重建。

2.1 sessionID的传送

2.1.1 通过cookie传送sessin ID


     使用session_start()调用session,服务器端在生成session文件的同时,生成session ID哈希值和默认值为PHPSESSID的session name,并向客户端发送变量为(默认的是)PHPSESSID(session name),值为一个128位的哈希值.服务器端将通过该cookie与客户端进行交互.
   session变量的值经php内部系列化后保存在服务器机器上的文本文件中,和客户端的变量名默认情况下为
PHPSESSID的coolie进行对应交互.
     即服务器自动发送了http头:header('Set-Cookie: session_name()=session_id(); path=/');
setcookie(session_name(),session_id());
   
当从该页跳转到的新页面并调用session_start(),PHP将检查与给定ID相关联的服务器端存贮的session数据,如果没找到,则新建一个数据集.

2.1.2
通过URL传送session ID
只有在用户禁止使用cookie的时候才用这种方法,因为浏览器cookie已经通用,为安全起见,可不用该方法.
<a href="p.php?<?php print
session_name() ?>=<?php print session_id() ?>">xxx</a>,也可以通过POST来传递session值.


2.2 session基本用法实例

<?php
// page1.php
session_start();
echo 'Welcome to page #1';
/* 创建session变量并给session变量赋值 */
$_SESSION['favcolor'] = 'green';
$_SESSION['animal'] = 'cat';
$_SESSION['time'] = time();

// 如果客户端使用cookie,可直接传递session到page2.php
echo '<br /><a href="page2.php">page 2</a>';

// 如果客户端禁用cookie
echo '<br /><a href="page2.php?' . SID . '">page 2</a>';
/*
 默认php5.2.1下,SID只有在cookie被写入的同时才会有值,如果该session
 对应的cookie已经存在,那么SID将为(未定义)空
 */

?>

<?php
// page2.php
session_start();
print $_SESSION['animal']; // 打印出单个session
var_dump($_SESSION); // 打印出page1.php传过来的session值
?>



2.3 使用session函数控制页面缓存.
    很多情况下,我们要确定我们的网页是否在客户端缓存,或要设置缓存的有效时间,比如我们的网页上有些敏感内容并且要登录才能查看,如果缓存到本地了,可以直接打开本地的缓存就可以不登录而浏览到网页了.

    使用session_cache_limiter('private');可以控制页面客户端缓存,必须在session_start()之前调用.
更多参数见http://blog.chinaunix.net/u/27731/showart.php?id=258087的客户端缓存控制.

    
控制客户端缓存时间 session_cache_expire(int);单位(s).也要在session_start()前调用.

    这只是使用session的情况下控制缓存的方法,我们还可以在header()中控制控制页面的缓存.

2.4 删除session

要三步实现.
<?php
session_destroy();                                      // 第一步: 删除服务器端session文件,这使用
setcookie(session_name(),'',time()-3600);  // 第二步: 删除实际的session:
$_SESSION = array();                                  // 第三步: 删除$_SESSION全局变量数组
?>

2.5 sessionPHP大型web应用中的使用

对于访问量大的站点,用默认的session存贮方式并不适合,目前最优的方法是用数据库存取session.这时,函数bool session_set_save_handler ( callback open, callback close, callback read, callback write, callback destroy, callback gc )就是提供给我们解决这个问题的方案.
该函数使用的6个函数如下:


1.   bool open() 用来打开会话存储机制,

2.   bool close() 关闭会话存储操作.

3.  mixde read() 从存储中装在session数据时使用这个函数


4.   bool write() 将给定session ID的所有数据写到存储中

5.   bool destroy() 破坏与指定的会话ID相关联的数据


6.   bool gc()  对存储系统中的数据进行垃圾收集

例子见php手册session_set_save_handler() 函数.
如果用类来处理,
session_set_save_handler(
    array('className','open'),
    array('className','close'),
    array('className','read'),
    array('className','write'),
    array('className','destroy'),
    array('className','gc'),
)
调用className类中的6个静态方法.className可以换对象就不用调用静态方法,但是用静态成员不用生成对象,性能更好.

2.6 常用session函数:

bool   session_start(void); 初始化session
bool   session_destroy(void)
: 删除服务器端session关联文件
string session_id()
当前sessionid
string session_name()
当前存取的session名称,也就是客户端保存session IDcookie名称.默认PHPSESSID
array  session_get_cookie_params()
与这个session相关联的session的细节.
string session_cache_limiter()
控制使用session的页面的客户端缓存
ini    session_cache_expire()
控制客户端缓存时间
bool   session_destroy()    
删除服务器端保存session信息的文件
void   session_set_cookie_params ( int lifetime [, string path [, string domain [, bool secure [, bool httponly]]]] )设置与这个session相关联的session的细节
bool session_set_save_handler ( callback open, callback close, callback read, callback write, callback destroy, callback gc )定义处理session的函数,(不是使用默认的方式)
bool session_regenerate_id([bool delete_old_session]) 分配新的session id


2.7 session安全问题
攻击者通过投入很大的精力尝试获得现有用户的有效会话ID,有了会话id,他们就有可能能够在系统中拥有与此用户相同的能力.
因此,我们主要解决的思路是效验session ID的有效性.

<?php


if(!isset($_SESSION['user_agent'])){
    $_SESSION['user_agent'] = $_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT'];
}

/* 如果用户session ID是伪造 */
elseif ($_SESSION['user_agent'] != $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']) {
   
session_regenerate_id();
}
?>



2.8 Session
通过cookie传递和通过SID传递的不同:
php5.2.1session的默认配置的情况下,当生成session的同时,服务器端将在发送header set-cookie同时生成预定义超级全局变量SID(也就是说,写入cookie和抛出SID是等价的.),$_COOKIE['PHPSESSID']存在以后,将不再写入cookie,也不再生成超级全局变量SID,此时,SID将是空的.


2.9 session使用实例


<?php
/**
 * 效验session的合法性
 *
 */

function sessionVerify() {
    if(!isset($_SESSION['user_agent'])){
        $_SESSION['user_agent'] = MD5($_SERVER['REMOTE_ADDR']
        .$_SERVER['HTTP_USER_AGENT']);
    }
    /* 如果用户session ID是伪造,则重新分配session ID */
    elseif ($_SESSION['user_agent'] != MD5($_SERVER['REMOTE_ADDR']
    . $_SERVER['HTTP_USER_AGENT'])) {
        session_regenerate_id();
    }
}

/**
 * 销毁session
 * 三步完美实现,不可漏
 *
 */

function sessionDestroy() {
    session_destroy();
    setcookie(session_name(),'',time()-3600);
    $_SESSION = array();
}
?>



注明:

    session 出现头信息已经发出的原因与cookie一样.
    在php5中,所有php session 的注册表配置选项都是编程时可配置的,一般情况下,我们是不用修改其配置的.要了解php的session注册表配置选项,请参考手册的Session 会话处理函数处.

; session的保存数据的时候,是通过系列化$_SESSION数组来存贮,所以有系列化所拥有的问题,可能有特殊字符的值要用base64_encode函数编码,读取的时候再用base64_decode解码