三款php计数器代码

 更新时间:2016年11月25日 16:26  点击:1701
文章收藏了三款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图片上传类带图片显示代码,应该可以说是上传文件最简单的上传类了,可以设置要显示图片高度与宽度,文件大小等。

uploadimg.class.php文件

 代码如下 复制代码

class upload
{
var $upload_name;
var $upload_tmp_address;
var $upload_server_name;
var $upload_filetype ;
var $file_type;
var $file_server_address;
var $image_w=900; //要显示图片的宽
var $image_h=350; //要显示图片的高
var $upload_file_size;
var $upload_must_size= 50000; //允许上传文件的大小,自己设置
function upload_file()
{
$this->upload_name = $_files["file"]["name"]; //取得上传文件名
$this->upload_filetype = $_files["file"]["type"];
$this->upload_server_name = date("y_m_dh_i_s").$this->upload_name;
$this->upload_tmp_address = $_files["file"]["tmp_name"]; //取得临时地址
$this->file_type = array("image/gif","image/pjpeg"); //允许上传文件的类型
$this->upload_file_size = $_files["file"]["size"]; //上传文件的大小
if(in_array($this->upload_filetype,$this->file_type))
{ if($this->upload_file_size < $this->upload_must_size)
{
echo("上传成功,谢谢支持");
$this->file_server_address = "d:www.111cn.netupload/".$this->upload_server_name;
move_uploaded_file($this->upload_tmp_address,$this->file_server_address);//从temp目录移出
echo("<img src=$this->file_server_address width=$this->image_w height=$this->image_h/>"); //显示图片


}
else
{
echo("文件容量太大");
}
}
else
{
echo("不支持此文件类型,请重新选择");
}

}

}


html上传代码

 代码如下 复制代码

<form id="form1" name="upload" enctype="multipart/form-data" method="post" action="upload.php">
<input type="hidden" name="max_file_size " />
<input type="file" name="file" />
<input type="submit" name="submit" value="提交" />
</form>


调用方法
upload.php

 代码如下 复制代码

inlcude('uploadimg.class.php');

$dd = new upload;
$dd->upload_file();

 

提供一款国人写的留言板,他是利用了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多文件上传实例代码,好了费话不说多了来看看这些多文件上传功能适合你么。

示例代码:

 代码如下 复制代码
<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模块安装方法快速简捷

[!--infotagslink--]

相关文章

  • 源码分析系列之json_encode()如何转化一个对象

    这篇文章主要介绍了源码分析系列之json_encode()如何转化一个对象,对json_encode()感兴趣的同学,可以参考下...2021-04-22
  • 不打开网页直接查看网站的源代码

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

    PHP去除html、css样式、js格式的方法很多,但发现,它们基本都有一个弊端:空格往往清除不了 经过不断的研究,最终找到了一个理想的去除html包括空格css样式、js 的PHP函数。...2013-08-02
  • 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
  • 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
  • index.php怎么打开?如何打开index.php?

    index.php怎么打开?初学者可能不知道如何打开index.php,不会的同学可以参考一下本篇教程 打开编辑:右键->打开方式->经文本方式打开打开运行:首先你要有个支持运行PH...2017-07-06
  • 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
  • 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中func_get_args(),func_get_arg(),func_num_args()的区别

    复制代码 代码如下:<?php function jb51(){ print_r(func_get_args()); echo "<br>"; echo func_get_arg(1); echo "<br>"; echo func_num_args(); } jb51("www","j...2013-10-04
  • php导出csv格式数据并将数字转换成文本的思路以及代码分享

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