简单的php日历类控件代码实例

 更新时间:2016年11月25日 16:28  点击:1759
本文章主要是一个php初学者写的原创的php日历控件 ,可以显示当前日期与今天是星期几,是否为闰年, 可自动选择上一年或下一年,月份日期也是一样的。

简单的php教程日历类控件代码实例
/*

*/
date_default_timezone_set("Etc/GMT-8");

class Calendar{

var $T = array();
var $datesOFmonth = array('1'=>'31','2'=>'28','3'=>'31','4'=>'30','5'=>'31','6'=>'30','7'=>'31','8'=>'31','9'=>'30','10'=>'31','11'=>'30','12'=>'31');
var $Y,$M,$D;

function set($time){
$this->T = getdate($time);
$this->Y = $this->T['year'];
$this->M = $this->T['mon'];
$this->D = date('d',$time);
}

function isRun(){
return ($this->Y%400==0 || ($this->Y%4==0 && $this->Y%100==0)) ? 1 : 0;
}

function first(){
$time = mktime(0,0,0,$this->M,1,$this->Y);
$time = getdate($time);
return $time['wday'];
}

function html(){
$isRun = $this->isRun();
$this->datesOFmonth[2] = $isRun==1 ? 29: 28;
$html .= "<table style='border:solid 1px black;'>n";
$html .= "<tr><th><a href=''>上一月</a></th><th colspan='5'>{$this->Y}年 {$this->M}月</th><th><a href=''>下一月</a></th><tr>n";
$html .= "<tr><td>星期天</td><td>星期一</td><td>星期二</td><td>星期三</td><td>星期四</td><td>星期五</td><td>星期六</td></tr>n";
$html .= "<tr>n";
$first = $this->first();
for($i=0; $i<$first; $i++){
$html .= "<td></td>";
}
$count = $this->datesOFmonth[$this->M]+$first;
for ($i=1; $i<= $this->datesOFmonth[$this->M]; $i++){
$style = $i==$this->D ? ' style="color:red;font-weight:bold;"' : '' ;
$html .= "<td align='center'{$style}>$i</td>";
if (($i==7%$first || ($i+$first)%7==0) && $i<$count){
$html .= "</tr>n<tr>";
}
}
$count = 7-$count%7;
if ($count<7){
for ($i=0; $i<$count; $i++){
$html .= "<td></td>";
}
}
$html .= "</tr>n";
$html .= "</table>n";
return $html;
}
}

$calendar = new Calendar();
$calendar->set(time());
echo $calendar->html();

php教程 生成word文档并下载代码
include("include/conn_mysql教程.php");
  $id=$_GET["id"];
  $sql="select * from  down where id=$id ";
  $result=mysql_query($sql);  
  $row=mysql_fetch_row($result);
  $file2=$row["upload"];
 
function downFile($sFilePath)
{
   if(file_exists($sFilePath)){
       $aFilePath=explode("/",str_replace("\","/",$sFilePath),$sFilePath);
       $sFileName=$aFilePath[count($aFilePath)-1];
       $nFileSize=filesize ($sFilePath);
       header ("Content-Disposition: attachment; filename=" .basename($sFileName) );
       header ("Content-Length: " . $nFileSize);
       header ("Content-type: application/octet-stream");
       mb_convert_encoding(readfile($sFilePath),"utf-8","GB2312");
   }
   else
   {
       echo("文件不存在!");
   }
}

downFile($file2);
/*
这个生成word生成文档程序是从mysql数据库教程读取数据保存文件再用header来发送给浏览器。
*/

这里我们为你提供个简单的php购物车代码哦,从增加购物产品与发生购买了,在商城开发中,这个功能是少不了的,我们不需要数据库,用了txt文本文件来操作用户购物的内容。

增加商品到购物车

 代码如下 复制代码

<?php
//
// add_item.php:
//  Add an item to the shopping cart.
//
session_start();
if (session_is_registered('cart')) {
    session_register('cart');
}

require 'lib.inc.php'; // LoadProducts()

LoadProducts(); // Load products in $master_products_list

// Make $curr_product global
$curr_product = array();

// Loop through all the products and pull up the product
// that we are interested in

 

foreach ($master_products_list as $prod_id => $product) {
    if (trim($prod_id) == trim($_GET[id])) {
        $curr_product = $product;
    }
}


// Register our session
//session_register('cart');
//if(session_is_registered('cart')) echo "已经注册";

 

if ($_POST[ordered]) {  // If they have chosen the product

    array_push($_SESSION[cart][products], array(trim($_POST[id]), $_POST[quantity]));
    $_SESSION[cart][num_items] += $_POST[quantity];
 
}
?>

<html>
<head>
    <title>
    <?php if ($_POST[ordered]) {  ?>
        已经添加 <?php echo $curr_product[name]; ?> 到您的购物篮
    <?php } else {  ?>
        添加 <?php echo $curr_product[name]; ?> 到您的购物篮
    <?php } ?>
    </title>
</head>
<body>
<?php if ($_POST[ordered]) {  ?>
    <h1><?php echo $curr_product[name]; ?>
        添加至购物篮成功</h1>

    <a href="cart.php">返回</a> 商品列表页面.
<?php }  else {  ?>
    <h1>添加 <?php echo $curr_product[name]; ?> 到您的购物篮</h1>

    <form action="<?php echo $PHP_SELF; ?>" method="post">
    商品名称: <?php echo $curr_product[name]; ?>
    <br>
    商品说明: <?php echo $curr_product[desc]; ?>
    <br>
    商品单价: RMB<?php echo $curr_product[price]; ?>
    <br>
    商品数量: <input type="text" size="7" name="quantity">
    <input type="hidden" name="id" value="<?php echo $_GET[id]; ?>">
    <input type="hidden" name="ordered" value="1">

    <input type="submit" value="添加至购物栏">
    </form>
<?php } ?>
</body>
</html>

查看购物车的商品

 代码如下 复制代码

<?php
//
// cart.php:  www.111cn.net
//
session_start();

require 'lib.inc.php';
//判断购物篮会话变量cart是否注册,不注册则注册cart变量
if (session_is_registered('cart')) {
    session_register('cart');
}


// 如果购物篮没有初始化,则初始化购物篮
if (!isset($_SESSION[cart][num_items])) {
    $_SESSION[cart] = array("num_items" => 0,
                  "products"  => array());
}


// From site_lib.inc, Loads the $master_products_list array
LoadProducts(); //载入物品列表
?>

<html>
<head>
    <title>演示会话跟踪的购物篮程序</title>
</head>

<body>

<h1>欢迎进入网上商店</h1>

<?php
if ($_SESSION[cart][num_items]) {  // If there is something to show
?>
<h2>当前在购物篮里的物品</h2>
<br>
<table border="2" cellpadding="5" cellspacing="2">
<tr>
    <th>
        商品名称
    </th>
    <th>
        商品说明
    </th>
    <th>
        单价
    </th>
    <th>
        数量
    </th>
    <th>&nbsp;
       
    </th>
</tr>
<?php
  
    // Loop through the products
    foreach ($_SESSION[cart][products] as $i => $product) {
        $product_id = $product[0];
        $quantity   = $product[1];

        $total += $quantity *
                  (double)$master_products_list[$product_id][price];
?>
<tr>
    <td>
        <?php echo $master_products_list[$product_id][name]; ?>
    </td>
    <td>
        <?php echo $master_products_list[$product_id][desc]; ?>
    </td>
    <td>
        <?php echo $master_products_list[$product_id][price]; ?>
    </td>
    <td>
        <form action="change_quant.php" method="post">
        <input type="hidden" name="id" value="<?php echo $i; ?>">
        <input type="text" size="3" name="quantity"
                value="<?php echo $quantity; ?>">
    </td>
    <td>
        <input type="submit" value="数量更改">
        </form>
    </td>
</tr>
<?php
    }
?>
<tr>
    <td colspan="2" ALIGN="right">
       <b>合计: </b>
    </td>
    <td colspan="2">
        RMB:<?php echo $total; ?>
    </td>
 <td>&nbsp;</td>
</tr>
</table>
<br>
<br>
<?php
}
?>

<h2>商店待出售的商品</h2>
<br>
<i>
    我们提供以下商品待售:
</i>
<br>
<table border="2" cellpadding="5" cellspacing="2">
<tr>
    <th>
        商品名称
    </th>
    <th>
        商品说明
    </th>
    <th>
        单价
    </th>
    <th>&nbsp;
       
    </th>
</tr>
<?php
    // Show all of the products
    foreach ($master_products_list as $product_id => $item) {
?>
<tr>
    <td>
        <?php echo $item[name]; ?>
    </td>
    <td>
        <?php echo $item[desc]; ?>
    </td>
    <td>
        $<?php echo $item[price]; ?>
    </td>
    <td>
        <a href="add_item.php?id=<?php echo $product_id; ?>">
            添加至购物篮
        </a>
    </td>
</tr>
<?php
    }

?>
</table>

修改购物车的数量

 代码如下 复制代码

<?php
//
// change_quant.php:
//   Change the quantity of an item in the shopping cart.
//
session_start();
if (session_is_registered('cart')) {
    session_register('cart');
}

// Typecast to int, making sure we access the
// right element below
$i = (int)$_POST[id];

// Save the old number of products for display
// and arithmetic
$old_num = $_SESSION[cart][products][$i][1];

if ($_POST[quantity]) {
    $_SESSION[cart][products][$i][1] = $_POST[quantity]; //change the quantity
} else {
    unset($_SESSION[cart][products][$i]); // Send the product into oblivion
}

// Update the number of items
$_SESSION[cart][num_items] = ($old_num >$_POST[quantity]) ?
                   $_SESSION[cart][num_items] - ($old_num-$_POST[quantity]) :
                   $_SESSION[cart][num_items] + ($_POST[quantity]-$old_num);
?>

<html>
<head>
    <title>
        数量修改
    </title>
</head>
<body>
    <h1> 将数量: <?php echo $old_num; ?> 更改为
         <?php echo $_POST[quantity]; ?></h1>
    <a href="cart.php">返回</a> 商品列表页面.
</body>
</html>

功能页面,用户把购物车里面的内容保存到txt数据库

 代码如下 复制代码

<?php
//物品数组
$master_products_list = array();


//载入物品数据函数
function LoadProducts() {
    global $master_products_list;
    $filename = 'products.txt';

    $fp = @fopen($filename, "r")
        or die("打开 $filename 文件失败");
    @flock($fp, 1)
        or die("锁定 $filename 文件失败");

    //读取文件内容
    while ($line = fgets($fp, 1024)) {
        list($id, $name, $desc, $price) = explode('|', $line); //读取每行数据,数据以| 格开
        $id = trim($id); //去掉首尾特殊符号
        $master_products_list[$id] = array("name" =>  $name, //名称
                                           "desc" =>  $desc, //说明
                                           "price" => $price); //单价
    }

    @fclose($fp)  //关闭文件
        or die("关闭 $filename 文件失败");
}
?>

很简单,我们只用了4个文件就实现用php 做好购物车功能哦,好了这只是一款简单的php购物车代码更复杂的需要考虑更多更好。

//发送留言

require("global.func.php教程");
$fid=isset($_GET["id"])?intval($_GET["id"]):0;
$page=isset($_GET["page"])?intval($_GET["page"]):1;
if($_SERVER["REQUEST_METHOD"]=="POST")
{
 if(!file_exists("1.php"))
 {
  writeFile("1.php",$array=array());
 }
 $arr=require("1.php");
 $post=array();
 unset($_POST["Submit"]);
 foreach($_POST as $k=>$v)
 {
  $post[$k]=addslashes(htmlspecialchars($v));
 }
 $post["content"]=str_replace(" ","<br>",$post["content"]);
 $post["id"]=count($arr)+1;
 $post["date"]=time();
 $post["fid"]=$fid;
 $post["ip"]=$_SERVER["REMOTE_ADDR"];
 $arr[]=$post;

 writeFile("1.php",$arr);
 
 echo "<script>location.href="index.php?page=$page"</script>";
 exit;
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>发帖</title>
<script>
var arr=new Array();

     function ckusername()
     {
      if(document.form1.username.value.length<3)
      {
       document.getElementById("user_msg").innerHTML="<font color="red"><b>用户名不能小于3个字符</b></font>";
       arr[0]=1;
      }else
      {
      document.getElementById("user_msg").innerHTML="<font color="green"><b>√</b></font>";
      arr[0]=0;
      }
      
      
     }
     function ckcontent()
     {
      
      if(document.form1.content.value.length<8||document.form1.content.value.length>255)
      {
       document.getElementById("content_msg").innerHTML="<font color="red"><b>内容8-255个字符</b></font>";
       arr[1]=1;
      }else
      {
       document.getElementById("content_msg").innerHTML="<font color="green"><b>√</b></font>";
       arr[1]=0;
      }
     }
     
     function c()
     {
      if(arr.length<2)
      {
       return false;
      }
      for(x in arr)
      {
       if(arr[x]==1)
       {
        return false;
       }
      }
      
      form1.submit();
     
     }
     
</script>
</head>
<body>
<form name="form1" method="post" action="">
  <table width="100%"  border="0">
    <tr>
      <td>用户
      <input name="username" type="text" id="id" onBlur="ckusername()" ></td>
    </tr>
 <tr>
      <td><div id="user_msg"></div>
      </td>
    </tr>
    <tr>
      <td><textarea name="content" cols="100" rows="6" id="content" onBlur="ckcontent()"></textarea></td>
    </tr>
 <tr>
      <td><div id="content_msg"></div>
      </td>
    </tr>
    <tr>
      <td><div align="center">
        <input type="button" name="Submit" value="提交" onClick="c();">
      </div></td>
    </tr>
  </table>
</form>
</body>

</html>

<?php
ini_set("display_errors",0);
require("global.func.php");
?>

显示像163评论
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.111cn.net/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
.b{
border:1px dotted #e3e3e3;
word-wrap:break-word;
word-break:break-all;
}


</style>

<title>PPC备用论坛(递归限制15层+主题)</title>
</head>
<body>
<?php
echo "<a href="post.php?page=1"> 发帖</a><br>";
if(file_exists("1.php"))
{
 $__array=require("1.php");
}
else
{
 $__array=array();
}
$page=isset($_GET["page"])?intval($_GET["page"]):1;
$pagesize=5;
$offset=($page-1)*$pagesize;
$__str="";
function getTotal()
{
 global $__array;
 $i=0;
 foreach($__array as $k=>$v)
 {
  if($v["fid"]==0)
  {
   $i=$i+1;
  }
 }
 return $i;
}
function getFid0()
{
 global $__array,$__str;
 
 foreach ($__array as $k=>$v)
 {
  if($v["fid"]==0)
  {
   $fid0[]=$v;
  }
  
 }
 return array_reverse($fid0);
}
$fid0=getFid0();
function show($fid0,$pagesize,$offset)
{
 global $__str,$page;
 foreach (array_slice($fid0,$offset,$pagesize,true) as $k=>$v)
 {
  
   $__str.="<blockquote class="b"><p>";
   $__str.=$v["ip"]."用户:".$v["username"]."内容:".$v["content"]."<a id="a1" href="post.php?id=".$v["id"]."&page=$page">回复</a>";
   showChild($v["id"]);
   $__str.="</p></blockquote>";
   
  
  
 }
}

function showChild($id,$i=0)
{
 global $__array,$__str,$page,$offset;
 
 
 if($i==15)//递归层数
 {
  return;
 }
 $i++;
 foreach($__array as $k=>$v)
 {
  if($v["fid"]==$id)
  {
   $__str.= "<blockquote class="b"><p id="a1">";
   $__str.= $__array[$k]["ip"]."用户:".$__array[$k]["username"]."内容:".$__array[$k]["content"]."<a href="post.php?id=".$v["id"]."&page=$page">回复</a>";
   showChild($v["id"],$i);
   $__str.= "</p></blockquote>";
  }
 }
}

show($fid0,$pagesize,$offset);
$total=getTotal();

echo $__str;
pageft($total,$pagesize,"index.php");
echo "<br>".$pagenav;
?>
</body>
</html>

global.func.php文件代码如下

<?php

function writeFile($id,$array)
{
 $content="<?php return ".var_export($array,true)."?>";
 return safe_file_put_contents($id,$content);
}
/**
*写入文件
*@param string $filename
*@param string $contents
*@return boolean
*/
function safe_file_put_contents($filename,&$contents)
{
 $fp=fopen($filename,"wb");
 if($fp)
 {
  flock($fp,LOCK_EX);
  fwrite($fp,$contents);
  flock($fp,LOCK_UN);
  fclose($fp);
  return true;
 }else
 {
  return false;
 }
}


/**
*读取文件
*@param string $filename
*@return $data|false
*/
function safe_file_get_contents($filename)
{
 $fp=fopen($filename,"rb");
 if($fp)
 {
  flock($fp,LOCK_SH);
  clearstatcache();
  $filesize=filesize($filename);
  if($filesize>0)
  {
   $data=fread($fp,$filesize);
  }else
  {
   $data=false;
  }
  flock($fp,LOCK_UN);
  fclose($fp);
  return $data;
 }else
 {
  return false;
 }
}
function pageft($total,$displaypg=10,$url=''){
global $page,$firstcount,$pagenav,$_SERVER;

$GLOBALS["displaypg"]=$displaypg;

if(!$page) $page=1;

if(!$url){ $url=$_SERVER["REQUEST_URI"];}

$parse_url=parse_url($url);
@$url_query=$parse_url["query"];
if($url_query){
$url_query=ereg_replace("(^|&)page=$page","",$url_query);

$url=str_replace($parse_url["query"],$url_query,$url);

if($url_query) $url.="&page"; else $url.="page";
}else {
$url.="?page";
}

$lastpg=ceil($total/$displaypg);
$page=min($lastpg,$page);
$prepg=$page-1;
$nextpg=($page==$lastpg ? 0 : $page+1);
if(!$page) $page=1;
$firstcount=($page-1)*$displaypg;


$pagenav.=" <a href='$url=1' class='s1'>首页</a> ";
if($prepg) $pagenav.=" <a href='$url=$prepg' class='s1'>上页</a> "; else $pagenav.="上页 ";
if($nextpg) $pagenav.=" <a href='$url=$nextpg' class='s1'>下页</a> "; else $pagenav.="下页 ";
$pagenav.=" <a href='$url=$lastpg' class='s1'>尾页</a>";

$pagenav.=" 到 <select name='topage' size='1' onchange='window.location="$url="+this.value'> ";
for($i=1;$i<=$lastpg;$i++){
if($i==$page) $pagenav.="<option value='$i' selected>$i</option> ";
else $pagenav.="<option value='$i'>$i</option> ";
}
$pagenav.="</select> 页";
}
?>

//保存的1.php文件数数组形式,如下格式

<?php return array (
  0 =>
  array (
    'username' => 'test',
    'content' => '111cn.net',
    'id' => 1,
    'date' => 1253853347,
    'fid' => 0,
    'ip' => '116.226.2.200',
  ),
  1 =>
  array (
    'username' => 'aaaaaaaaaaad',
    'content' => 'www.111cn.net',
    'id' => 2,
    'date' => 1253857672,
    'fid' => 0,
    'ip' => '116.226.6.188',
  ),
 
)?>

 

Memcache是什么
Memcache是danga.com的一个项目,最早是为 LiveJournal 服务的,目前全世界不少人使用这个缓存项目来构建自己大负载的网站,来分担数据库教程的压力。
它可以应对任意多个连接,使用非阻塞的网络IO。由于它的工作机制是在内存中开辟一块空间,然后建立一个HashTable,Memcached自管理这些HashTable。
Memcache官方网站:http://www.danga.com/memcached,更多详细的信息可以来这里了解

为什么会有Memcache和memcached两种名称?
其实Memcache是这个项目的名称,而memcached是它服务器端的主程序文件名,知道我的意思了把~~~~。一个是项目名称,一个是主程序文件名,在网上看到了很多人不明白,于是混用了。

Memcache的安装
分为两个过程:memcache服务器端的安装和memcached客户端的安装。
所谓服务器端的安装就是在服务器(一般都是linux系统)上安装Memcache实现数据的存储
所谓客户端的安装就是指php教程(或者其他程序,Memcache还有其他不错的api接口提供)去使用服务器端的Memcache提供的函数,需要php添加扩展。

PHP的Memcache

复制代码 代码如下:
< ?php
//连接

$mem = new Memcache;
$mem->connect("192.168.0.200", 12000);

//保存数据

$mem->set('key1', 'This is first value', 0, 60);
$val = $mem->get('key1');
echo "Get key1 value: " . $val ."<br />";

//替换数据

$mem->replace('key1', 'This is replace value', 0, 60);
$val = $mem->get('key1');
echo "Get key1 value: " . $val . "<br />";

//保存数组

$arr = array('aaa', 'bbb', 'ccc', 'ddd');
$mem->set('key2', $arr, 0, 60);
$val2 = $mem->get('key2');
echo "Get key2 value: ";
print_r($val2);
echo "<br />";

//删除数据

$mem->delete('key1');
$val = $mem->get('key1');
echo "Get key1 value: " . $val . "<br />";

//清除所有数据

$mem->flush();
$val2 = $mem->get('key2');
echo "Get key2 value: ";
print_r($val2);
echo "<br />";

//关闭连接
$mem->close();
?>

如果正常的话,浏览器将输出:

Get key1 value: This is first value
Get key1 value: This is replace value
Get key2 value: Array ( [0] => aaa [1] => bbb [2] => ccc [3] => ddd )
Get key1 value:
Get key2 value:

程序代码分析

初始化一个Memcache的对象:

$mem = new Memcache;

连接到我们的Memcache服务器端,第一个参数是服务器的IP地址,也可以是主机名,第二个参数是Memcache的开放的端口:

$mem->connect("192.168.0.200", 12000);

保存一个数据到Memcache服务器上,第一个参数是数据的key,用来定位一个数据,第二个参数是需要保存的数据内容,这里是一个字符串,第三个参数是一个标记,一般设置为0或者MEMCACHE_COMPRESSED就行了,第四个参数是数据的有效期,就是说数据在这个时间内是有效的,如果过去这个时间,那么会被Memcache服务器端清除掉这个数据,单位是秒,如果设置为0,则是永远有效,我们这里设置了60,就是一分钟有效时间:
$mem->set(‘key1‘, ‘This is first value', 0, 60);

从Memcache服务器端获取一条数据,它只有一个参数,就是需要获取数据的key,我们这里是上一步设置的key1,现在获取这个数据后输出输出:

$val = $mem->get('key1′);
echo "Get key1 value: " . $val;

现在是使用replace方法来替换掉上面key1的值,replace方法的参数跟set是一样的,不过第一个参数key1是必须是要替换数据内容的key,最后输出了:

$mem->replace(‘key1′, ‘This is replace value', 0, 60);
$val = $mem->get(‘key1′);
echo "Get key1 value: " . $val;

同样的,Memcache也是可以保存数组的,下面是在Memcache上面保存了一个数组,然后获取回来并输出

$arr = array(‘aaa', ‘bbb', ‘ccc', ‘ddd');
$mem->set(‘key2′, $arr, 0, 60);
$val2 = $mem->get(‘key2′);
print_r($val2);

现在删除一个数据,使用delte接口,参数就是一个key,然后就能够把Memcache服务器这个key的数据删除,最后输出的时候没有结果

$mem->delete(‘key1′);
$val = $mem->get(‘key1′);
echo "Get key1 value: " . $val . "<br>";

最后我们把所有的保存在Memcache服务器上的数据都清除,会发现数据都没有了,最后输出key2的数据为空,最后关闭连接

$mem->flush();
$val2 = $mem->get(‘key2′);
echo "Get key2 value: ";
print_r($val2);
echo "<br>";

Memcache的使用
使用Memcache的网站一般流量都是比较大的,为了缓解数据库的压力,让Memcache作为一个缓存区域,把部分信息保存在内存中,在前端能够迅速的进行存取。那么一般的焦点就是集中在如何分担数据库压力和进行分布式,毕竟单台Memcache的内存容量的有限的。我这里简单提出我的个人看法,未经实践,权当参考。

分布式应用
Memcache本来支持分布式,我们客户端稍加改造,更好的支持。我们的key可以适当进行有规律的封装,比如以user为主的网站来说,每个用户都有User ID,那么可以按照固定的ID来进行提取和存取,比如1开头的用户保存在第一台Memcache服务器上,以2开头的用户的数据保存在第二胎Mecache服务器上,存取数据都先按照User ID来进行相应的转换和存取。

但是这个有缺点,就是需要对User ID进行判断,如果业务不一致,或者其他类型的应用,可能不是那么合适,那么可以根据自己的实际业务来进行考虑,或者去想更合适的方法。

减少数据库压力
这个算是比较重要的,所有的数据基本上都是保存在数据库当中的,每次频繁的存取数据库,导致数据库性能极具下降,无法同时服务更多的用户,比如MySQL,特别频繁的锁表,那么让Memcache来分担数据库的压力吧。我们需要一种改动比较小,并且能够不会大规模改变前端的方式来进行改变目前的架构。

我考虑的一种简单方法:
后端的数据库操作模块,把所有的Select操作提取出来(update/delete/insert不管),然后把对应的SQL进行相应的hash算法计算得出一个hash数据key(比如MD5或者SHA),然后把这个key去Memcache中查找数据,如果这个数据不存在,说明还没写入到缓存中,那么从数据库把数据提取出来,一个是数组类格式,然后把数据在set到Memcache中,key就是这个SQL的hash值,然后相应的设置一个失效时间,比如一个小时,那么一个小时中的数据都是从缓存中提取的,有效减少数据库的压力。缺点是数据不实时,当数据做了修改以后,无法实时到前端显示,并且还有可能对内存占用比较大,毕竟每次select出来的数据数量可能比较巨大,这个是需要考虑的因素。

Memcache的安全
我们上面的Memcache服务器端都是直接通过客户端连接后直接操作,没有任何的验证过程,这样如果服务器是直接暴露在互联网上的话是比较危险,轻则数据泄露被其他无关人员查看,重则服务器被入侵,因为Mecache是以root权限运行的,况且里面可能存在一些我们未知的bug或者是缓冲区溢出的情况,这些都是我们未知的,所以危险性是可以预见的。为了安全起见,我做两点建议,能够稍微的防止黑客的入侵或者数据的泄露。

内网访问
最好把两台服务器之间的访问是内网形态的,一般是Web服务器跟Memcache服务器之间。普遍的服务器都是有两块网卡,一块指向互联网,一块指向内网,那么就让Web服务器通过内网的网卡来访问Memcache服务器,我们Memcache的服务器上启动的时候就监听内网的IP地址和端口,内网间的访问能够有效阻止其他非法的访问。
# memcached -d -m 1024 -u root -l 192.168.0.200 -p 11211 -c 1024 -P /tmp/memcached.pid
Memcache服务器端设置监听通过内网的192.168.0.200的ip的11211端口,占用1024MB内存,并且允许最大1024个并发连接

设置防火墙
防火墙是简单有效的方式,如果却是两台服务器都是挂在网的,并且需要通过外网IP来访问Memcache的话,那么可以考虑使用防火墙或者代理程序来过滤非法访问。
一般我们在Linux下可以使用iptables或者FreeBSD下的ipfw来指定一些规则防止一些非法的访问,比如我们可以设置只允许我们的Web服务器来访问我们Memcache服务器,同时阻止其他的访问。

# iptables -F
# iptables -P INPUT DROP
# iptables -A INPUT -p tcp -s 192.168.0.2 –dport 11211 -j ACCEPT
# iptables -A INPUT -p udp -s 192.168.0.2 –dport 11211 -j ACCEPT

上面的iptables规则就是只允许192.168.0.2这台Web服务器对Memcache服务器的访问,能够有效的阻止一些非法访问,相应的也可以增加一些其他的规则来加强安全性,这个可以根据自己的需要来做。

[!--infotagslink--]

相关文章

  • 不打开网页直接查看网站的源代码

      有一种方法,可以不打开网站而直接查看到这个网站的源代码..   这样可以有效地防止误入恶意网站...   在浏览器地址栏输入:   view-source:http://...2016-09-20
  • php 调用goolge地图代码

    <?php require('path.inc.php'); header('content-Type: text/html; charset=utf-8'); $borough_id = intval($_GET['id']); if(!$borough_id){ echo ' ...2016-11-25
  • C#创建自定义控件及添加自定义属性和事件使用实例详解

    这篇文章主要给大家介绍了关于C#创建自定义控件及添加自定义属性和事件使用的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用C#具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧...2020-06-25
  • JS基于Mootools实现的个性菜单效果代码

    本文实例讲述了JS基于Mootools实现的个性菜单效果代码。分享给大家供大家参考,具体如下:这里演示基于Mootools做的带动画的垂直型菜单,是一个初学者写的,用来学习Mootools的使用有帮助,下载时请注意要将外部引用的mootools...2015-10-23
  • JS+CSS实现分类动态选择及移动功能效果代码

    本文实例讲述了JS+CSS实现分类动态选择及移动功能效果代码。分享给大家供大家参考,具体如下:这是一个类似选项卡功能的选择插件,与普通的TAb区别是加入了动画效果,多用于商品类网站,用作商品分类功能,不过其它网站也可以用,...2015-10-21
  • JS实现自定义简单网页软键盘效果代码

    本文实例讲述了JS实现自定义简单网页软键盘效果。分享给大家供大家参考,具体如下:这是一款自定义的简单点的网页软键盘,没有使用任何控件,仅是为了练习JavaScript编写水平,安全性方面没有过多考虑,有顾虑的可以不用,目的是学...2015-11-08
  • php 取除连续空格与换行代码

    php 取除连续空格与换行代码,这些我们都用到str_replace与正则函数 第一种: $content=str_replace("n","",$content); echo $content; 第二种: $content=preg_replac...2016-11-25
  • php简单用户登陆程序代码

    php简单用户登陆程序代码 这些教程很对初学者来讲是很有用的哦,这款就下面这一点点代码了哦。 <center> <p>&nbsp;</p> <p>&nbsp;</p> <form name="form1...2016-11-25
  • PHP实现清除wordpress里恶意代码

    公司一些wordpress网站由于下载的插件存在恶意代码,导致整个服务器所有网站PHP文件都存在恶意代码,就写了个简单的脚本清除。恶意代码示例...2015-10-23
  • JS实现双击屏幕滚动效果代码

    本文实例讲述了JS实现双击屏幕滚动效果代码。分享给大家供大家参考,具体如下:这里演示双击滚屏效果代码的实现方法,不知道有觉得有用处的没,现在网上还有很多还在用这个特效的呢,代码分享给大家吧。运行效果截图如下:在线演...2015-10-30
  • js识别uc浏览器的代码

    其实挺简单的就是if(navigator.userAgent.indexOf('UCBrowser') > -1) {alert("uc浏览器");}else{//不是uc浏览器执行的操作}如果想测试某个浏览器的特征可以通过如下方法获取JS获取浏览器信息 浏览器代码名称:navigator...2015-11-08
  • C#实现跨线程操作控件方法

    这篇文章主要介绍了C#实现跨线程操作控件方法,主要采用异步访问方式实现,需要的朋友可以参考下...2020-06-25
  • JS日期加减,日期运算代码

    一、日期减去天数等于第二个日期function cc(dd,dadd){//可以加上错误处理var a = new Date(dd)a = a.valueOf()a = a - dadd * 24 * 60 * 60 * 1000a = new Date(a)alert(a.getFullYear() + "年" + (a.getMonth() +...2015-11-08
  • Jquery日历插件制作简单日历

    在页面开发中,经常遇到需要用户输入日期的操作。通常的做法是,提供一个文本框(text),让用户输入,然后,编写代码验证输入的数据,检测其是否是日期类型。这样比较麻烦,同时,用户输入日期的操作也不是很方便,影响用户体验。如果使...2015-10-30
  • PHP开发微信支付的代码分享

    微信支付,即便交了保证金,你还是处理测试阶段,不能正式发布。必须到你通过程序测试提交订单、发货通知等数据到微信的系统中,才能申请发布。然后,因为在微信中是通过JS方式调用API,必须在微信后台设置支付授权目录,而且要到...2014-05-31
  • PHP常用的小程序代码段

    本文实例讲述了PHP常用的小程序代码段。分享给大家供大家参考,具体如下:1.计算两个时间的相差几天$startdate=strtotime("2009-12-09");$enddate=strtotime("2009-12-05");上面的php时间日期函数strtotime已经把字符串...2015-11-24
  • 几种延迟加载JS代码的方法加快网页的访问速度

    本文介绍了如何延迟javascript代码的加载,加快网页的访问速度。 当一个网站有很多js代码要加载,js代码放置的位置在一定程度上将会影像网页的加载速度,为了让我们的网页加载速度更快,本文总结了一下几个注意点...2013-10-13
  • php怎么用拼音 简单的php中文转拼音的实现代码

    小编分享了一段简单的php中文转拼音的实现代码,代码简单易懂,适合初学php的同学参考学习。 代码如下 复制代码 <?phpfunction Pinyin($_String...2017-07-06
  • php导出csv格式数据并将数字转换成文本的思路以及代码分享

    php导出csv格式数据实现:先定义一个字符串 存储内容,例如 $exportdata = '规则111,规则222,审222,规222,服2222,规则1,规则2,规则3,匹配字符,设置时间,有效期'."/n";然后对需要保存csv的数组进行foreach循环,例如复制代...2014-06-07
  • ecshop商品无限级分类代码

    ecshop商品无限级分类代码 function cat_options($spec_cat_id, $arr) { static $cat_options = array(); if (isset($cat_options[$spec_cat_id]))...2016-11-25