菜单

session,cookie之数据库存储,文件存储,测试等

2010年12月8日 - php

session,cookie文件,数据库存储,直接上代码:

代码下载

测试代码cookie:

<?php
if($_SERVER[‘REQUEST_METHOD’]==’POST’){
if($_POST[‘coo_value’]){
if(intval($_POST[‘coo_time’])>0){
setcookie (“coo_name”, $_POST[‘coo_value’], time() + intval($_POST[‘coo_time’]));
}else{
setcookie (“coo_name”, $_POST[‘coo_value’]);
}
}
header(‘Location:’.$_SERVER[‘REQUEST_URI’]);
}
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Cookie Test</title>
<style type=”text/css”>
body{ font-size:12px; font-family:Arial, Helvetica, sans-serif;}
fieldset legend{ font-size:13px;}
fieldset legend,fieldset p label{ font-weight:bold;}
fieldset p label{ width:160px; float:left;}
input{ border:1px solid #999;}
</style>
<script type=”text/javascript”>
function checkNumber(event,objThis)
{
var eventKey = document.all ? event.keyCode : event.which;
if(!(eventKey>=48&&eventKey<=57) && eventKey != 8 )
return false;
}
</script>
</head>
<body>
<div id=”main”>
<div id=”header”>
<fieldset>
<legend>Cookie Info</legend>
<p><label>Cookie array:</label><?php print_r($_COOKIE);?></p>
<p><label>&nbsp;</label><input type=”button” value=”Refresh” onclick=”javascript:window.location.href=window.location.href;” /></p>
</fieldset>
</div>
<div id=”main_content”>
<form action=”” method=”post”>
<fieldset>
<legend>Cookie Form</legend>
<p><label>Set Cookie value:</label><input size=”30″ type=”text” name=”coo_value” value=””/></p>
<p><label>Set Cookie time(seconds):</label><input size=”30″ type=”text” name=”coo_time” value=”” onkeypress=”return checkNumber(event,this);”/></p>
<p><label>&nbsp;</label><input type=”submit” name=”coo_submit” value=”Submit”/></p>
</fieldset>
</form>
</div>
</div>
</body>
</html>

测试代码session:

<?php
//session type (files, db)
$type = isset($_GET[‘type’])?$_GET[‘type’]:’files’;
switch($type){
//save session with files
case ‘files’:
ini_set(‘session.save_handler’,’files’);
if($_SERVER[‘REQUEST_METHOD’]==’POST’){
if($_POST[‘ses_path’]!=”&&is_dir($_POST[‘ses_path’])){
session_save_path($_POST[‘ses_path’]);
}
if(isset($_POST[‘ses_submit’])){
session_start();
if($_POST[‘ses_value’]){
$_SESSION[‘ses_name_files’] = $_POST[‘ses_value’];
}
}elseif(isset($_POST[‘ses_clear’])){
session_start();
session_unset();
}
if($_POST[‘ses_path’]!=”&&is_dir($_POST[‘ses_path’])){
header(‘Location:’.$_SERVER[‘REQUEST_URI’].’?savepath=’.$_POST[‘ses_path’]);
}else{
header(‘Location:’.$_SERVER[‘REQUEST_URI’]);
}
}else{
if($_SERVER[‘REQUEST_METHOD’]==’GET’&&isset($_GET[‘savepath’])){
session_save_path($_GET[‘savepath’]);
}
session_start();
}
break;
//save session with database
case ‘db’:
ini_set(‘session.save_handler’,’user’);
if($_SERVER[‘REQUEST_METHOD’]==’POST’){
if(isset($_POST[‘ses_dbhost’])&&isset($_POST[‘ses_dbname’])&&isset($_POST[‘ses_dbuser’])&&isset($_POST[‘ses_dbpass’])){
$SESS_DBHOST = $_POST[‘ses_dbhost’]; /* database server hostname */
$SESS_DBNAME = $_POST[‘ses_dbname’]; /* database name */
$SESS_DBUSER = $_POST[‘ses_dbuser’]; /* database user */
$SESS_DBPASS = $_POST[‘ses_dbpass’]; /* database password */
$SESS_DBH = “”;
$SESS_LIFE = get_cfg_var(“session.gc_maxlifetime”);
//rewrite session logic
session_set_save_handler(“sess_open”,”sess_close”,”sess_read”,”sess_write”,”sess_destroy”,”sess_gc”);
session_start();
if($_POST[‘ses_value’]){
$_SESSION[‘ses_name_db’] = $_POST[‘ses_value’];
}
if(isset($_POST[‘ses_clear’])){
session_unset();
}
header(‘Location:’.$_SERVER[‘REQUEST_URI’].’&ses_dbhost=’.$_POST[‘ses_dbhost’].’&ses_dbname=’.$_POST[‘ses_dbname’].’&ses_dbuser=’.$_POST[‘ses_dbuser’].’&ses_dbpass=’.$_POST[‘ses_dbpass’]);
}else{
header(‘Location:’.$_SERVER[‘REQUEST_URI’]);
}
}
if(isset($_GET[‘ses_dbhost’])&&isset($_GET[‘ses_dbname’])&&isset($_GET[‘ses_dbuser’])&&isset($_GET[‘ses_dbpass’])){
$SESS_DBHOST = $_GET[‘ses_dbhost’]; /* database server hostname */
$SESS_DBNAME = $_GET[‘ses_dbname’]; /* database name */
$SESS_DBUSER = $_GET[‘ses_dbuser’]; /* database user */
$SESS_DBPASS = $_GET[‘ses_dbpass’]; /* database password */
$SESS_DBH = “”;
$SESS_LIFE = get_cfg_var(“session.gc_maxlifetime”);
//rewrite session logic
//ini_set(‘session.save_handler’,’user’);
session_module_name(‘user’);
session_set_save_handler(“sess_open”,”sess_close”,”sess_read”,”sess_write”,”sess_destroy”,”sess_gc”);
session_start();
}
break;
default:
break;
}
//date_default_timezone_set(‘Asia/Shanghai’);
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Session Test</title>
<style type=”text/css”>
body{ font-size:12px; font-family:Arial, Helvetica, sans-serif;}
fieldset legend{ font-size:13px;}
fieldset legend,fieldset p label{ font-weight:bold;}
fieldset p label{ width:200px; float:left;}
input{ border:1px solid #999;}
</style>
</head>
<body>
<div id=”main”>
<div id=”header”>
<fieldset>
<legend>Session Type</legend>
<select onchange=”javascript:window.location.href=this.value”>
<option value=”session.php” <?php if($type==’files’)echo ‘selected=”selected”‘;?>>files</option>
<option value=”session.php?type=db” <?php if($type==’db’)echo ‘selected=”selected”‘;?>>db</option>
</select>
</fieldset>
<fieldset>
<legend>Session Info</legend>
<p><label>Session ID:</label><?php echo ‘<font color=”blue”>’.session_id().'</font>’;?>&nbsp;</p>
<?php if($type==’files’){?>
<p><label>Session Save Path:</label><?php echo session_save_path();?>&nbsp;<?php if(is_writable(session_save_path())){echo ‘<font color=”green”>Can be written</font>’;}elseif(session_save_path()){echo ‘<font color=”red”>Can not write</font>’;};?></p>
<?php }?>
<p><label>Session array:</label><?php if(isset($_SESSION)){print_r($_SESSION);}else{echo ‘<font color=”red”>Please input DB info.</font>’;}?></p>
<p><label>&nbsp;</label><input type=”button” value=”Refresh” onclick=”javascript:window.location.href=window.location.href;” /></p>
</fieldset>
</div>
<div id=”main_content”>
<?php if($type==’files’){?>
<form action=”session.php” method=”post”>
<fieldset>
<legend>Session Form</legend>
<p><label>Set Session Path:</label><input size=”50″ type=”text” name=”ses_path” value=”<?php if($_SERVER[‘REQUEST_METHOD’]==’GET’&&isset($_GET[‘savepath’])){echo $_GET[‘savepath’];}?>”/>&nbsp;<?php if($_SERVER[‘REQUEST_METHOD’]==’GET’&&isset($_GET[‘savepath’])){if(!is_dir($_GET[‘savepath’])){echo ‘<font color=”red”>Path Error</font>’;}}?></p>
<p><label>Set Session value:</label><input size=”50″ type=”text” name=”ses_value” value=””/></p>
<p><label>&nbsp;</label><input type=”submit” name=”ses_submit” value=”Submit”/></p>
<p><label>&nbsp;</label><input type=”submit” name=”ses_clear” value=”Clear Session”/></p>
</fieldset>
</form>
<?php }?>
<?php if($type==’db’){?>
<form action=”session.php?type=db” method=”post”>
<fieldset>
<legend>Session db settings</legend>
<p><label>Database server hostname:</label><input size=”50″ type=”text” name=”ses_dbhost” value=”<?php if($_SERVER[‘REQUEST_METHOD’]==’GET’&&isset($_GET[‘ses_dbhost’])){echo $_GET[‘ses_dbhost’];}?>”/></p>
<p><label>database user:</label><input size=”50″ type=”text” name=”ses_dbuser” value=”<?php if($_SERVER[‘REQUEST_METHOD’]==’GET’&&isset($_GET[‘ses_dbuser’])){echo $_GET[‘ses_dbuser’];}?>”/></p>
<p><label>database password:</label><input size=”50″ type=”text” name=”ses_dbpass” value=”<?php if($_SERVER[‘REQUEST_METHOD’]==’GET’&&isset($_GET[‘ses_dbpass’])){echo $_GET[‘ses_dbpass’];}?>”/></p>
<p><label>database name:</label><input size=”50″ type=”text” name=”ses_dbname” value=”<?php if($_SERVER[‘REQUEST_METHOD’]==’GET’&&isset($_GET[‘ses_dbname’])){echo $_GET[‘ses_dbname’];}?>”/></p>
<p><label>Set Session value:</label><input size=”50″ type=”text” name=”ses_value” value=””/></p>
<p><label>&nbsp;</label><input type=”submit” name=”ses_submit” value=”Submit”/></p>
<p><label>&nbsp;</label><input type=”submit” name=”ses_clear” value=”Clear Session”/></p>
</fieldset>
</form>
<?php }?>
</div>
<div id=”footer”>
<?php if($type==’files’){?>
<fieldset>
<legend>Session File list</legend>
<ul>
<?php
if(is_dir(session_save_path())){
if($handle = @opendir(session_save_path())){
$filearray = array();
while(false!=($file=readdir($handle))){
if($file!=”.”&&$file!=”..”){
$filearray[filemtime(session_save_path().’/’.$file)] = $file;
}
}
krsort($filearray);
if(!empty($filearray)){
foreach($filearray as $key=>$val){
if($val==’sess_’.session_id()){
$val = ‘<font color=”blue”>’.$val.'</font>’;
}
echo ‘<li>’.date(‘Y.m.d H:i:s’,$key).’ —- ‘.$val.'</li>’;
}
}
closedir($handle);
}else{
echo ‘<li style=”color:red;”>Permission denied</li>’;
}
}
?>
</ul>
</fieldset>
<?php }?>
<?php if($type==’db’){?>
<fieldset>
<legend>Session db list</legend>
<table border=”0″ cellspacing=”0″ cellpadding=”0″>
<tr align=”left”>
<th width=”15%”>session key</th>
<th width=”10%”>expiry</th>
<th width=”50%”>value</th>
</tr>
<?php
$qry = “SELECT * FROM session_tbl order by expiry desc”;
if(isset($SESS_DBH)){
$res = @mysql_query($qry, $SESS_DBH);
while(false!==($row = mysql_fetch_assoc($res))){
$style = ”;
if($row[‘sesskey’]==session_id()){
$style = ‘ style=”color:blue;”‘;
}
echo ‘<tr’.$style.’><td>’.$row[‘sesskey’].'</td>’.'<td>’.date(“Y.m.d H:i:s”,$row[‘expiry’]).'</td>’.'<td>’.$row[‘value’].'</td></tr>’;
}
}
?>
</table>
</fieldset>
<?php }?>
</div>
</div>
</body>
</html>
<?php
//session handler
function sess_open($save_path, $session_name) {
global $SESS_DBHOST, $SESS_DBNAME, $SESS_DBUSER, $SESS_DBPASS, $SESS_DBH

if (! $SESS_DBH = @mysql_pconnect($SESS_DBHOST, $SESS_DBUSER, $SESS_DBPASS)) {
echo “Can’t connect to $SESS_DBHOST as $SESS_DBUSER<br />”;
echo “MySQL Error: ” . mysql_error().”<br />”;
echo ‘<a href=”session.php?type=db”>go back</a>’;
die;
}

if (! mysql_select_db($SESS_DBNAME, $SESS_DBH)) {
echo “Unable to select database $SESS_DBNAME”;
die;
}

$qry = “CREATE TABLE IF NOT EXISTS session_tbl(sesskey char(32) not null,expiry int(11) unsigned not null,value text not null,PRIMARY KEY (sesskey))”;
@mysql_query($qry, $SESS_DBH);

return true;
}

function sess_close() {
return true;
}

function sess_read($key) {
global $SESS_DBH, $SESS_LIFE;

$qry = “SELECT value FROM session_tbl WHERE sesskey = ‘$key’ “;
$qid = mysql_query($qry, $SESS_DBH);

if (list($value) = mysql_fetch_row($qid)) {
return $value;
}

return false;
}

function sess_write($key, $val) {
global $SESS_DBH, $SESS_LIFE;

$expiry = time() + $SESS_LIFE; //session timeout
$value = addslashes($val);

$qry = “INSERT INTO session_tbl VALUES (‘$key’, $expiry, ‘$value’)”;
$qid = mysql_query($qry, $SESS_DBH);

if (! $qid) {
$qry = “UPDATE session_tbl SET expiry = $expiry, value = ‘$value’ WHERE sesskey = ‘$key'”;
$qid = mysql_query($qry, $SESS_DBH);
}

return $qid;
}

function sess_destroy($key) {
global $SESS_DBH;

$qry = “DELETE FROM session_tbl WHERE sesskey = ‘$key'”;
$qid = mysql_query($qry, $SESS_DBH);

return $qid;
}

function sess_gc($maxlifetime) {
global $SESS_DBH;

$qry = “DELETE FROM session_tbl WHERE expiry < ” . time();
$qid = mysql_query($qry, $SESS_DBH);

return mysql_affected_rows($SESS_DBH);
}
?>

数据库存储代码:

<?php
$SESS_DBHOST = “yourhost”; /* database server hostname */
$SESS_DBNAME = “yourdb”; /* database name */
$SESS_DBUSER = “youruser”; /* database user */
$SESS_DBPASS = “yourpassword”; /* database password */

$SESS_DBH = “”;
$SESS_LIFE = get_cfg_var(“session.gc_maxlifetime”);

function sess_open($save_path, $session_name) {
global $SESS_DBHOST, $SESS_DBNAME, $SESS_DBUSER, $SESS_DBPASS, $SESS_DBH

if (! $SESS_DBH = mysql_pconnect($SESS_DBHOST, $SESS_DBUSER, $SESS_DBPASS)) {
echo “<li>Can’t connect to $SESS_DBHOST as $SESS_DBUSER”;
echo “<li>MySQL Error: ” . mysql_error();
die;
}

if (! mysql_select_db($SESS_DBNAME, $SESS_DBH)) {
echo “<li>Unable to select database $SESS_DBNAME”;
die;
}

$qry = “CREATE TABLE IF NOT EXISTS session_tbl(sesskey char(32) not null,expiry int(11) unsigned not null,value text not null,PRIMARY KEY (sesskey))”;
@mysql_query($qry, $SESS_DBH);

return true;
}

function sess_close() {
return true;
}

function sess_read($key) {
global $SESS_DBH, $SESS_LIFE;

$qry = “SELECT value FROM session_tbl WHERE sesskey = ‘$key'”;
$qid = mysql_query($qry, $SESS_DBH);

if (list($value) = mysql_fetch_row($qid)) {
return $value;
}

return false;
}

function sess_write($key, $val) {
global $SESS_DBH, $SESS_LIFE;

$expiry = time() + $SESS_LIFE; //过期时间
$value = addslashes($val);

$qry = “INSERT INTO session_tbl VALUES (‘$key’, $expiry, ‘$value’)”;
$qid = mysql_query($qry, $SESS_DBH);

if (! $qid) {
$qry = “UPDATE session_tbl SET expiry = $expiry, value = ‘$value’ WHERE sesskey = ‘$key'”;
$qid = mysql_query($qry, $SESS_DBH);
}

return $qid;
}

function sess_destroy($key) {
global $SESS_DBH;

$qry = “DELETE FROM session_tbl WHERE sesskey = ‘$key'”;
$qid = mysql_query($qry, $SESS_DBH);

return $qid;
}

function sess_gc($maxlifetime) {
global $SESS_DBH;

$qry = “DELETE FROM session_tbl WHERE expiry < ” . time();
$qid = mysql_query($qry, $SESS_DBH);

return mysql_affected_rows($SESS_DBH);
}

//ini_set(‘session.save_handler’,’user’);
session_module_name(‘user’);

session_set_save_handler(
“sess_open”,
“sess_close”,
“sess_read”,
“sess_write”,
“sess_destroy”,
“sess_gc”);

session_start();
?>

发表评论

电子邮件地址不会被公开。 必填项已用*标注