PHPRPC范例代码

Standard
1
2
3
4
5
6
7
8
//rpc_sayhi.php
require_once('./phprpc/php/phprpc_server.php');
function SayHi($name){
        return 'Hi! '.$name;
}
$phprpc=new PHPRPC_Server();
$phprpc->add('SayHi');
$phprpc->start();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/*sayhi.js*/
 $(document).ready(function(){
         $('#submit').click(
                 function(){
                         $('#waiting').show();
                         $('.clear_rs').trigger("click");
                         getRPC();
                 }
         );
         $('.clear_rs').click(
                 function(){
                         $('.clear_rs').hide();
                         $('#hi_name_p').hide('slow');
                 }
         );
 }
 )
 function getRPC(){
         var rpc = new PHPRPC_Client('http://yemaosheng.com/rpc_sayhi.php', ['SayHi']);
                 rpc.SayHi($('#q').val(),function(result){
                      $('#hi_name_p,.clear_rs').show('slow');
                           $('#waiting').hide();
                           $('#hi_name_p').html(result);
                   });
   }
1
2
3
4
5
6
7
8
<! index.html-->
<script src="jquery.js" type="text/javascript"></script>
<script src="phprpc_client.js" type="text/javascript"></script>
<script src="sayhi.js" type="text/javascript"></script>
<input id="q" maxlength="20" name="q" size="20" type="text" />
<input id="submit" maxlength="20" name="submit" size="20" type="button" value="Say Hi!" />
<img id="waiting" style="display:none;" src="http://bawbaw.hu.googlepages.com/indicator.gif" alt="" />  
<input class="clear_rs" style="display:none;" maxlength="20" name="clear_rs2" size="20" type="button" value="Clear" />

PHPRPC官方网站: http://www.phprpc.org

PHP APC文件上传进度条实现范例

Standard
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
//upload.php (文件上传表单,提交到target.php)
<?php $id = $_GET['id']; ?>
<form enctype="multipart/form-data" id="upload_form" action="target.php" method="POST">
  <input type="hidden" name="APC_UPLOAD_PROGRESS" id="progress_key"  value="<?php echo $id?>"/>
  <input type="file" id="test_file" name="test_file"/><br/>
  <input onclick="window.parent.startProgress(); return true;" type="submit" value="Upload!"/>
</form>
 
//target.php (接收upload.php上传表单提交页面)
<?php 
set_time_limit(600);
if($_SERVER['REQUEST_METHOD']=='POST') {
  move_uploaded_file($_FILES["test_file"]["tmp_name"],
  dirname($_SERVER['SCRIPT_FILENAME'])."/UploadTemp/" . $_FILES["test_file"]["name"]);//UploadTemp文件夹位于此脚本相同目录下
  echo "<p>File uploaded.  Thank you!</p>";
}
 
//getprogress.php (用来得到文件上传状态信息,让js来调用)
<?php
session_start();
if(isset($_GET['progress_key'])) {
  $status = apc_fetch('upload_'.$_GET['progress_key']);
  echo ($status['current']/$status['total'])*100;
}
?>
 
//progress.php (调用getprogress.php和upload.php,显示进度条)
<?php
$id = md5(uniqid(rand(), true));
?>
<html>
<head><title>Upload Example</title></head>
<body>
<script language="javascript">
var xmlHttp;
var proNum=0;
var loop=0;
 
var Try = {
 these: function() {
 var returnValue;
  for (var i = 0; i < arguments.length; i++) {
   var lambda = arguments[i];
   try {
    returnValue = lambda();
    break;
   } catch (e) {}
  }
  return returnValue;
 }
}
 
function createXHR(){
 return Try.these(
  function() {return new XMLHttpRequest()},
  function() {return new ActiveXObject('Msxml2.XMLHTTP')},
  function() {return new ActiveXObject('Microsoft.XMLHTTP')}
 ) || false;
}
 
var xmlHttp;
 
function sendURL() {
 xmlHttp=createXHR();
 var url="getprogress.php?progress_key=<?php echo $id;?>";
 xmlHttp.onreadystatechange = doHttpReadyStateChange;
 xmlHttp.open("GET",url,true);
 xmlHttp.send(null);  
}
 
function doHttpReadyStateChange() {
 if (xmlHttp.readyState == 4){
  proNum=parseInt(xmlHttp.responseText);
  document.getElementById("progressinner").style.width = proNum+"%";
  document.getElementById("showNum").innerHTML = proNum+"%";
  if ( proNum < 100){
   setTimeout("getProgress()", 100);
  }
 }
}
 
function getProgress(){
 loop++;
 document.getElementById("showNum2").innerHTML = loop;
 sendURL();
}
var interval;
function startProgress(){
 document.getElementById("progressouter").style.display="block";
 setTimeout("getProgress()", 100);
}
</script>
 
<iframe id="theframe" name="theframe"
src="upload.php?id=<?php echo($id); ?>"
style="border: none; height: 100px; width: 400px;" >
</iframe>
<br/><br/>
<div id="progressouter" style=
"width: 500px; height: 20px; border: 6px solid red; display:none;">
<div id="progressinner" style=
"position: relative; height: 20px; background-color: purple; width: 0%; ">
</div>
</div><div id='showNum'></div><br>
<div id='showNum2'></div>
</body>
</html>

PHP用GD生成验证码

Standard
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
-----------validatecode.php------------
<?
//session_start();
function random($len)
{
$srcstr="ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
mt_srand();
$strs="";
for($i=0;$i<$len;$i++){
$strs.=$srcstr[mt_rand(0,35)];
}
return strtoupper($strs);
}
$str=random(4); //随机生成的字符串
//$_SESSION["code"] = $str; 也可以用session来做
setcookie("code", $str, time()+60000, "/", ".yemaosheng.com");
$width = 120; //验证码图片的宽度
$height = 35; //验证码图片的高度
@header("Content-Type:image/png");
 
$im=imagecreate($width,$height);
//背景色
$back=imagecolorallocate($im,0xFF,0xFF,0xFF);
//字体色
$font=imagecolorallocate($im,287,330,347);
//$font_color=imagecolorallocate($im,287,330,347);
$font_color=imagecolorallocate($im,mt_rand(50,120),mt_rand(50,120),mt_rand(50,120));
//绘模糊作用的点
mt_srand();
for($i=0;$i<500;$i++)
{
imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),imagecolorallocate($im,mt_rand(1,255),mt_rand(1,255),mt_rand(1,255)));
}
 
$font_file = $_SERVER['DOCUMENT_ROOT'].'/img/res/font2.ttf';
/*变化文件颜色及角度大小*/
imagettftext($im, mt_rand(15,28), mt_rand(-30,30), 5, 30, $font_color, $font_file, substr($str,0,1));
imagettftext($im, mt_rand(15,28), mt_rand(-30,30), 35, 30, $font_color, $font_file, substr($str,1,1));
imagettftext($im, mt_rand(15,28), mt_rand(-30,30), 65, 30, $font_color, $font_file, substr($str,2,1));
imagettftext($im, mt_rand(15,28), mt_rand(-30,30), 95, 30, $font_color, $font_file, substr($str,3,1));
imagerectangle($im,0,0,$width-1,$height-1,$font); //画边框 int imagerectangle ( resource image, int x1, int y1, int x2, int y2, int col)
imagepng($im);
imagedestroy($im);
?>
-----------html------------
<form name="form1" method="post" action='get.php'>
<input name="validatecode" type="text" value="" /><img src="validatecode.php" />验证码
<input name="submit" type="submit" value="Submit" />
</form>
-----------get.php------------
<?php
if(strtolower($_COOKIE['code'])==strtolower($_POST['validatecode']))
{
echo "ok";
}
?>

PHP分页函数

Standard
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
if(!function_exists(pageft)){
function pageft($totle,$displaypg=20,$url=''){
global $page,$firstcount,$pagenav,$_SERVER;
$GLOBALS["displaypg"]=$displaypg;
if(!$page) { $page=1; }
if(!$url){
$url=$_SERVER["REQUEST_URI"];
}
//URL分析:
$parse_url=parse_url($url);
$url_query=$parse_url["query"]; //单独取出URL的查询字串
if($url_query){
$url_query=ereg_replace("(^|&)page=$page","",$url_query);
//将处理后的URL的查询字串替换原来的URL的查询字串:
$url=str_replace($parse_url["query"],$url_query,$url);
//在URL后加page查询信息,但待赋值:
if($url_query){
$url.="&page";
}else{
$url.="page";
}
}else {
$url.="?page";
}
$lastpg=ceil($totle/$displaypg); //最后页,也是总页数
$page=min($lastpg,$page);
$prepg=$page-1; //上一页
$nextpg=($page==$lastpg ? 0 : $page+1); //下一页
$firstcount=($page-1)*$displaypg;
//开始分页导航条代码:
$pagenav="显示第 <B>".($totle?($firstcount+1):0)."</B>-<B>".min($firstcount+$displaypg,$totle)."</B> 条记录,共 $totle 条记录<BR>";
//如果只有一页则跳出函数:
if($lastpg<=1) return false;
$pagenav.=" <a href='$url=1'>首页</a> ";
if($prepg){
$pagenav.=" <a href='$url=$prepg'>前页</a> ";
}else{
$pagenav.=" 前页 ";
}
if($nextpg){
$pagenav.=" <a href='$url=$nextpg'>后页</a> ";
}else{
$pagenav.=" 后页 ";
}
$pagenav.=" <a href='$url=$lastpg'>尾页</a> ";
//下拉跳转列表,循环列出所有页码:
$pagenav.=" 到第 <select name='topage' size='1' onchange='window.location=\"$url=\"+this.value'>\n";
for($i=1;$i<=$lastpg;$i++){
if($i==$page){
$pagenav.="<option value='$i' selected>$i</option>\n";
}else{
$pagenav.="<option value='$i'>$i</option>\n";
}
}
$pagenav.="</select> 页,共 $lastpg 页";
}
}
 
$sql="SELECT * FROM tb";
//取得总信息数
$result=mysql_query($sql);
$total=mysql_num_rows($result);
//调用pageft(),每页显示10条信息(使用默认的20时,可以省略此参数),使用本页URL(默认,所以省略掉)。
pageft($total,10,"http://www.yemaosheng.com/index");
//现在产生的全局变量就派上用场了:
$result=mysql_query($sql." limit $firstcount,$displaypg");
$i=1;
while($row=mysql_fetch_array($result)){
$array[]=array("index"=>$i,"date"=>$row['date'],"type"=>$row['type'],"value"=>$row['value']);
$i++;
}
$pagenav;//分页导航条代码
$main_smarty->assign('mainlist', $array);
$main_smarty->assign('pagenum', $pagenav);
$main_smarty->display('x.tpl');
 
----------------smarty template x.tpl----------------
<table>
{section name=sec1 loop=$mainlist}
<tr>
<td width="76"><strong>{$mainlist[sec1].index}</strong></td>
<td width="138">{$mainlist[sec1].date}</td>
<td width="274">{$mainlist[sec1].type}</td>
<td width="114">{$mainlist[sec1].value}</td>
</tr>
{/section}
</table>
<center>{$pagenum}</center>

PHP数据库存储session

Standard

First up, we need to create a table to handle the session data, and here’s how it will look:
CREATE TABLE sessions (ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, SessionID CHAR(26), Data TEXT DEFAULT ”, DateTouched INT);

Now, session operations script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
mysql_connect("localhost", "phpuser", "alm65z");
mysql_select_db("phpdb");
function sess_open($sess_path, $sess_name) {
return true;
}
function sess_close() {
return true;
}
function sess_read($sess_id) {
$result = mysql_query("SELECT Data FROM sessions WHERE SessionID = '$sess_id';");
if (!mysql_num_rows($result)) {
$CurrentTime = time();
mysql_query("INSERT INTO sessions (SessionID, DateTouched) VALUES ('$sess_id', $CurrentTime);");
return '';
} else {
extract(mysql_fetch_array($result), EXTR_PREFIX_ALL, 'sess');
mysql_query("UPDATE sessions SET DateTouched = $CurrentTime WHERE SessionID = '$sess_id';");
return $sess_Data;
}
}
function sess_write($sess_id, $data) {
$CurrentTime = time();
mysql_query("UPDATE sessions SET Data = '$data', DateTouched = $CurrentTime WHERE SessionID = '$sess_id';");
return true;
}
function sess_destroy($sess_id) {
mysql_query("DELETE FROM sessions WHERE SessionID = '$sess_id';");
return true;
}
function sess_gc($sess_maxlifetime) {
$CurrentTime = time();
mysql_query("DELETE FROM sessions WHERE DateTouched + $sess_maxlifetime < $CurrentTime;");
return true;
}
session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
session_start();
$_SESSION['foo'] = "bar";
$_SESSION['baz'] = "wombat";
?>
 
Next, just file store:
function sess_open($sess_path, $sess_name) {
print "Session opened.\n";
print "Sess_path: $sess_path\n";
print "Sess_name: $sess_name\n\n";
return true;
}
function sess_close() {
print "Session closed.\n";
return true;
}
function sess_read($sess_id) {
print "Session read.\n";
print "Sess_ID: $sess_id\n";
return '';
}
function sess_write($sess_id, $data) {
print "Session value written.\n";
print "Sess_ID: $sess_id\n";
print "Data: $data\n\n";
return true;
}
function sess_destroy($sess_id) {
print "Session destroy called.\n";
return true;
}
function sess_gc($sess_maxlifetime) {
print "Session garbage collection called.\n";
print "Sess_maxlifetime: $sess_maxlifetime\n";
return true;
}
session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
session_start();
$_SESSION['foo'] = "bar";
print "Some text\n";
$_SESSION['baz'] = "wombat";
?>