php ajax 留言板

 更新时间:2016年11月25日 16:26  点击:1317
提供一款国人写的留言板,他是利用了jquery php mysql ajax来实现php ajax 局部刷新留方板实例的喜欢就下载吧。

*/

 代码如下 复制代码

$link = @mysql_connect($db_host,$db_user,$db_pass) or die('unable to establish a db connection');

mysql_query("set names 'utf8'");
mysql_select_db($db_database,$link);

class comment
{
 private $data = array();
 
 public function __construct($row)
 {
  /*
  / the constructor
  */
  
  $this->data = $row;
 }
 
 public function markup()
 {
  /*
  / this method outputs the xhtml markup of the comment
  */
  
  // setting up an alias, so we don't have to write $this->data every time:
  $d = &$this->data;
  
  $link_open = '';
  $link_close = '';
  
  if($d['url']){
   
   // if the person has entered a url when adding a comment,
   // define opening and closing hyperlink tags
   
   $link_open = '<a href="'.$d['url'].'">';
   $link_close =  '</a>';
  }
  
  // converting the time to a unix timestamp:
  $d['dt'] = strtotime($d['dt']);
  
  // needed for the default gravatar image:
  $url = 'http://'.dirname($_server['server_name'].$_server["request_uri"]).'/img/default_avatar.gif';
  
  return '
  
   <div class="comment">
    <div class="avatar">
     '.$link_open.'
     <img src="http://www.gravatar.com/avatar/'.md5($d['email']).'?size=50&amp;default='.urlencode($url).'" />
     '.$link_close.'
    </div>
    
    <div class="name">'.$link_open.$d['name'].$link_close.'</div>
    <div class="date" title="added at '.date('h:i on d m y',$d['dt']).'">'.date('d m y',$d['dt']).'</div>
    <p>'.$d['body'].'</p>
   </div>
  ';
 }
 
 public static function validate(&$arr)
 {
  /*
  / this method is used to validate the data sent via ajax.
  /
  / it return true/false depending on whether the data is valid, and populates
  / the $arr array passed as a paremter (notice the ampersand above) with
  / either the valid input data, or the error messages.
  */
  
  $errors = array();
  $data = array();
  
  // using the filter_input function introduced in php 5.2.0
  
  if(!($data['email'] = filter_input(input_post,'email',filter_validate_email)))
  {
   $errors['email'] = 'please enter a valid email.';
  }
  
  if(!($data['url'] = filter_input(input_post,'url',filter_validate_url)))
  {
   // if the url field was not populated with a valid url,
   // act as if no url was entered at all:
   
   $url = '';
  }
  
  // using the filter with a custom callback function:
  
  if(!($data['body'] = filter_input(input_post,'body',filter_callback,array('options'=>'comment::validate_text'))))
  {
   $errors['body'] = 'please enter a comment body.';
  }
  
  if(!($data['name'] = filter_input(input_post,'name',filter_callback,array('options'=>'comment::validate_text'))))
  {
   $errors['name'] = 'please enter a name.';
  }
  
  if(!empty($errors)){
   
   // if there are errors, copy the $errors array to $arr:
   
   $arr = $errors;
   return false;
  }
  
  // if the data is valid, sanitize all the data and copy it to $arr:
  
  foreach($data as $k=>$v){
   $arr[$k] = mysql_real_escape_string($v);
  }
  
  // ensure that the email is lower case:
  
  $arr['email'] = strtolower(trim($arr['email']));
  
  return true;
  
 }

 private static function validate_text($str)
 {
  /*
  / this method is used internally as a filter_callback
  */
  
  if(mb_strlen($str,'utf8')<1)
   return false;
  
  // encode all html special characters (<, >, ", & .. etc) and convert
  // the new line characters to <br> tags:
  
  $str = nl2br(htmlspecialchars($str));
  
  // remove the new line characters that are left
  $str = str_replace(array(chr(10),chr(13)),'',$str);
  
  return $str;
 }

}

$comments = array();
$result = mysql_query("select * from comments order by id asc");

while($row = mysql_fetch_assoc($result))
{
 $comments[] = new comment($row);
}

?>

<!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
<title>simple ajax commenting system | tutorialzine demo</title>

<link rel="stylesheet" type="text/css教程" href="styles.css" />

</head>

<body>

 


<div id="main">

<?php

/*
/ output the comments one by one:
*/

foreach($comments as $c){
 echo $c->markup();
}

?>

<div id="addcommentcontainer">
 <p>add a comment</p>
 <form id="addcommentform" method="post" action="">
     <div>
         <label for="name">your name</label>
         <input type="text" name="name" id="name" />
           
            <label for="email">your email</label>
            <input type="text" name="email" id="email" />
           
            <label for="url">website (not required)</label>
            <input type="text" name="url" id="url" />
           
            <label for="body">comment body</label>
            <textarea name="body" id="body" cols="20" rows="5"></textarea>
           
            <input type="submit" id="submit" value="submit" />
        </div>
    </form>
</div>

</div>

<script type="text/网页特效" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>

</body>
</html>

数据库教程结构

 代码如下 复制代码

--
-- table structure for table `comments`
--

create table `comments` (
  `id` int(10) unsigned not null auto_increment,
  `name` varchar(128) collate utf8_unicode_ci not null default '',
  `url` varchar(255) collate utf8_unicode_ci not null default '',
  `email` varchar(255) collate utf8_unicode_ci not null default '',
  `body` text collate utf8_unicode_ci not null,
  `dt` timestamp not null default '0000-00-00',
  primary key  (`id`)
) engine=myisam  default charset=utf8 collate=utf8_unicode_ci;

文章收藏了三款php计数器代码,他们三个都有一个同共点就是全部无需数据库,而是利用了文本文件来实例网页浏览计数哦。
 代码如下 复制代码
<?php
//计数器
function countx($file="count.dat"){
if(file_exists($file)){
$fp=fopen($file,"r");
$numx=fgets($fp,10);
fclose($fp);
$numx++;
//以上四行代码可以用一条表达式代替:$numx=file_get_contents($file)+1;
}
else{
$numx=1;}
file_put_contents($file,$numx);//当文件不存在时,这函数会自动创建文件,而且会自动把参数转成字符串写入。
echo $numx;
/*整个函数体可以用两条表达式代替:file_exists($file)?file_put_contents($file,file_get_contents($file)+1):file_put_contents($file,"1");readfile($file);
*/
}
//函数调用
countx();
?>

代码二

 代码如下 复制代码

<?php
  
  
  $counterfile = "balong.txt";//存储数值的文件名几路径
  
  function displaycounter($counterfile) {
   $fp = fopen($counterfile,"rw");
   $num = fgets($fp,5);
   $num += 1;
   print "您是第 "."$num"." 个看巴泷计数器的家伙";
   exec( "rm -rf $counterfile");
   exec( "echo $num > $counterfile");
  }
  
  if (!file_exists($counterfile)) {
   exec( "echo 0 > $counterfile");
  }
  
  displaycounter($counterfile);
  
  ?>


代码三

 代码如下 复制代码

<?php
  
  
  $counterfile = "www.111cn.net.txt";//存储数值的文件名几路径
  
  function displaycounter($counterfile) {
   $fp = fopen($counterfile,"rw");
   $num = fgets($fp,5);
   $num += 1;
   print "您是第 "."$num"." 个看巴泷计数器的家伙";
   exec( "rm -rf $counterfile");
   exec( "echo $num > $counterfile");
  }
  
  if (!file_exists($counterfile)) {
   exec( "echo 0 > $counterfile");
  }
  
  displaycounter($counterfile);
  
  ?>

在php开发应用中经常会碰到文件上传这个需,有时也会碰到要多文件上传,下面我们就来看看我提供的三款php多文件上传实例代码,好了费话不说多了来看看这些多文件上传功能适合你么。

示例代码:

 代码如下 复制代码
<form action="" method="post" enctype="multipart/form-data" >
<input type="file" name="uploadfile[]">   命名必是这样有"[]"
<input type="file" name="uploadfile[]">

//设置允许用户上传的文件类型。
$type = array('gif', 'jpg', 'png', 'zip', 'rar');
$upload = new uploadfile($_files['uploadfile'], '/', 1024*1024, $type);
参数说明:1:表单的文件,2:上传目录,3:支持文件大小,4:允许文件类型
$icount = $upload->upload();
if($icount > 0) { //上传成功
   print_r($upload->getsaveinfo());
  */

class uploadfile {
var $postfile = array();       // 用户上传的文件
var $custompath = "";          // 自定义文件上传路径
var $maxsize = "";             // 文件最大尺寸
var $lasterror = "";           // 最后一次出错信息
var $allowtype = array('gif', 'jpg', 'png', 'zip', 'rar', 'txt', 'doc', 'pdf');
var $endfilename = "";         // 最终保存的文件名
var $saveinfo = array();       // 保存文件的最终信息
var $root_dir = ""; // 项目在硬盘上的位置

/**
* 构造函数
* @access public
*/

 代码如下 复制代码
function uploadfile($arrfile, $path="_", $size = 2097152, $type = 0) {
   $this->postfile     = $arrfile;
   $this->custompath   = $path == "_" ? "" : $path ;
   $this->maxsize      = $size;
   if($type!=0)   $this->allowtype   = $arrfile;
   $this->root_dir      = $_server['document_root'];
   $this->_mkdir($this->custompath);
}

/**
* 文件上传的核心代码
* @access public
* @return int 上传成功文件数
*/

 代码如下 复制代码

function upload() {
   $ilen = sizeof($this->postfile['name']);
   for($i=0;$i<$ilen;$i++){
    if ($this->postfile['error'][$i] == 0) { //上传时没有发生错误
      //取当前文件名、临时文件名、大小、扩展名,后面将用到。
     $sname   = $this->postfile['name'][$i];
     $stname = $this->postfile['tmp_name'][$i];
     $isize   = $this->postfile['size'][$i];
     $stype   = $this->postfile['type'][$i];
     $sextn   = $this->_getextname($sname);
   
     //检测当前上传文件大小是否合法。
     if($this->_checksize){
      $this->lasterror = "您上传的文件[".$sname."],超过系统支持大小!";
      $this->_showmsg($this->lasterror);
      continue;
     }

     if(!is_uploaded_file($stname)) {
      $this->lasterror = "您的文件不是通过正常途径上传!";
      $this->_showmsg($this->lasterror);
      continue;
     }
     $_filename = basename($sname,".".$sextn)."_".time().".".$sextn;
     $this->endfilename = $this->custompath.$_filename;
   
     if(!move_uploaded_file($stname, $this->root_dir.$this->endfilename)) {
      $this->lasterror = $this->postfile['error'][$i];
      $this->_showmsg($this->lasterror);
      continue;
     }

     //存储当前文件的有关信息,以便其它程序调用。
     $this->save_info[] =   array("name" => $sname, "type" => $sextn, "size" => $isize,   "path" => $this->endfilename);
    }
   }

   return sizeof($this->save_info);
}

 

本文章是利用了php一个插件实例邮php文件上传进度条的功能,方法比较简单,因为都有组件了,所以只要按照人家的意思照办就可以实例php大文件上传的功能了。

目前我知道的方法有两种,一种是使用php的创始人 rasmus lerdorf 写的apc扩展模块来实现(http://pecl.php.net/package/apc),另外一种方法是使用pecl扩展模块uploadprogress实现(http://pecl.php.net/package/uploadprogress) 我这里举两个分别实现的例子供参考,更灵活的应用根据自己需要来修改。

apc实现方法:

安装apc,参照官方文档安装,可以使用pecl模块安装方法快速简捷,这里不说明

配置php.ini,设置参数 apc.rfc1867=1 ,使apc支持上传进度条功能,在apc源码说明文档里面有说明

 

php文件上传进度条实现方法:安装apc,参照官方文档安装,可以使用pecl模块安装方法快速简捷,这里不说明 配置php.ini,设置参数 apc.rfc1867=1 ,使apc支持上传进度条功能,在apc源码说明文档里面有说明 代码范例:

if($_server['request_method']=='post'){//上传请求
$status=apc_fetch('upload_'.$_post['apc_upload_progress']);
$status['done']=1;
echojson_encode($status);//输出给用户端页面里的ajax调用,相关文档请自己寻找
exit;
}elseif(isset($_get['progress_key'])){//读取上传进度
$status=apc_fetch('upload_'.$_get['progress_key']);
echojson_encode($status);
exit;
}else{
//其他代码,比如上传表单等
}
uploadprogress 模块实现方法:使用pecl模块安装方法安装该模块的php文件上传进度条实现方法 php.ini里面设置 uploadprogress.file.filename_template = "/tmp/upd_%s.txt"

if($_server['request_method']=='post'){
if(is_uploaded_file($_files['upfile']['tmp_name'])){
$upload_dir='your_path/';
$ext=strrchr($_files['video']['name'],'.');
$sessid=$_post['upload_identifier'];
$tmpfile=$upload_dir.$sessid;
$sessfile=$upload_dir.$sessid.$ext;
if(move_uploaded_file($_files['upfile']['tmp_name'],$tmpfile)){
//上传成功
}else{
//上传失败
}else{
//上传错误

}elseif(!empty($_get['sessid'])){
header("expires:mon,26jul199705:00:00gmt");
header("last-modified:".gmdate("d,dmyh:i:s")."gmt");
header("cache-control:no-store,no-cache,must-revalidate");
header("cache-control:post-check=0,pre-check=0′,false);
header("pragma:no-cache");
header("content-type:text/html;charset=utf-8′);

$unique_id=$_get['sessid'];
$uploadvalues=uploadprogress_get_info($unique_id);

if(is_array($uploadvalues)){
echo  json_encode($uploadvalues);
}else{
//读取进度失败,另外处理逻辑
}

}else{
//显示上传表单
}


pecl扩展模块uploadprogress实现。


基于php的ajax技术的具体应用解析
php限制上传文件大小的具体解决办法
php批量上传图片的具体实现方式
php动态多文件上传的具体代码分享
php通用文件上传类的具体解析 我这里举两个分别实现的例子供参考,更灵活的应用根据自己需要来修改。

apc的php文件上传进度条实现方法:

安装apc,参照官方文档安装,可以使用pecl模块安装方法快速简捷

 <?php教程
/**
*十进制转二进制、八进制、十六进制 不足位数前面补零*
*
* @param array $datalist 传入数据array(100,123,130)
* @param int $bin 转换的进制可以是:2,8,16
* @return array 返回数据 array() 返回没有数据转换的格式
* @copyright chengmo qq:8292669
*/
function decto_bin($datalist,$bin)
{
static $arr=array(0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f');
if(!is_array($datalist)) $datalist=array($datalist);
if($bin==10)return $datalist; //相同进制忽略
$bytelen=ceil(16/$bin); //获得如果是$bin进制,一个字节的长度
$aoutchar=array();
foreach ($datalist as $num)
{
$t="";
$num=intval($num);
if($num===0)continue;
while($num>0)
{
$t=$arr[$num%$bin].$t;
$num=floor($num/$bin);
}
$tlen=strlen($t);
if($tlen%$bytelen!=0)
{
$pad_len=$bytelen-$tlen%$bytelen;
$t=str_pad("",$pad_len,"0",str_pad_left).$t; //不足一个字节长度,自动前面补充0
}
$aoutchar[]=$t;
}
return $aoutchar;
}

[!--infotagslink--]

相关文章

  • vue.js 表格分页ajax 异步加载数据

    Vue.js通过简洁的API提供高效的数据绑定和灵活的组件系统.这篇文章主要介绍了vue.js 表格分页ajax 异步加载数据的相关资料,需要的朋友可以参考下...2016-10-20
  • node.js+express留言板功能实现示例

    本文介绍基于nodejs+express+art-template的留言板功能。包含列表界面、添加界面和发送留言功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-21
  • jquery Ajax实现Select动态添加数据

    这篇文章主要为大家详细介绍了jquery Ajax实现Select动态添加数据的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2017-06-15
  • JS基于MSClass和setInterval实现ajax定时采集信息并滚动显示的方法

    这篇文章主要介绍了JS基于MSClass和setInterval实现ajax定时采集信息并滚动显示的方法,涉及JavaScript页面元素定时滚动操作及ajax调用实现技巧,需要的朋友可以参考下...2016-04-19
  • php实现网站留言板功能

    我要实现的就是下图的这种样式,可参考下面这两个网站的留言板,他们的实现原理都是一样的畅言留言板样式:网易跟帖样式:原理 需要在评论表添加两个主要字段 id 和 pid ,其他字段随意添加,比如文章id、回复时间、回复内容、...2015-11-08
  • php+ajax制作无刷新留言板

    本文就是和大家分享一款由php结合ajax实现的无刷新留言板,先给大家看一下最后的效果图:数据库连接代码如下: <&#63;php$conn = @mysql_connect("localhost","root","root") or die ("MySql连接错误");mysql_select_db("d...2015-10-30
  • jQuery+ajax简单实现文件上传的方法

    这篇文章主要介绍了jQuery+ajax简单实现文件上传的方法,结合实例形式简单分析了jQuery基于ajax的post方法进行文件传输及asp.net后台处理技巧,需要的朋友可以参考下...2016-06-12
  • PHP+jQuery+Ajax实现多图片上传效果

    今天我给大家分享的是在不刷新页面的前提下,使用PHP+jQuery+Ajax实现多图片上传的效果。用户只需要点击选择要上传的图片,然后图片自动上传到服务器上并展示在页面上。...2015-03-15
  • js实现ajax的用户简单登入功能

    这篇文章主要为大家详细介绍了js实现ajax的用户简单登入功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-06-19
  • Bootstrap进度条与AJAX后端数据传递结合使用实例详解

    这篇文章主要介绍了Bootstrap进度条与AJAX后端数据传递结合使用,需要的朋友可以参考下...2017-04-27
  • jQuery UI结合Ajax创建可定制的Web界面

    这篇文章主要为大家详细介绍了jQuery UI结合Ajax创建可定制的Web界面,如何利用Ajax和jQuery UI创建具有各种定制功能的高度可定制的UI,感兴趣的小伙伴们可以参考一下...2016-06-24
  • jquery ajax局部加载方法详解(实现代码)

    下面想就为大家带来一篇jquery ajax局部加载方法详解(实现代码)。小编觉得挺不错的,现在分享给大家,也给大家做个参考,一起跟随小编过来看看吧...2016-05-14
  • jquery+Ajax实现简单分页条效果

    这篇文章主要为大家详细介绍了jquery+Ajax实现简单分页条效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-06-17
  • jQuery中通过ajax的get()函数读取页面的方法

    这篇文章主要介绍了jQuery中通过ajax的get()函数读取页面的方法,需要的朋友可以参考下...2016-03-01
  • JQUERY的AJAX请求缓存里的数据问题处理

    这篇文章主要介绍了JQUERY的AJAX请求缓存里的数据问题处理的相关资料,需要的朋友可以参考下...2016-02-26
  • Vue实现简单的留言板

    这篇文章主要为大家详细介绍了Vue实现简单的留言板,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-10-22
  • jQuery Ajax全解析

    本文主要介绍了Ajax基本概念;Ajax的异步加载局部刷新功能的实现;通过XMLHttpRequest发送请求。具有很好的参考价值,下面跟着小编一起来看下吧...2017-02-19
  • javascript实现简单留言板案例

    这篇文章主要为大家详细介绍了javascript实现简单留言板案例,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-09
  • 原生js实现对Ajax的封装(仿jquery)

    这篇文章主要为大家详细介绍了原生js实现对Ajax的封装,模仿jquery,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2017-01-26
  • jQuery ajax全局函数处理session过期后的ajax跳转问题

    这篇文章主要介绍了基于jQuery的全局ajax函数处理session过期后的ajax操作的相关资料,需要的朋友可以参考下...2016-06-12