在php中缓存分为很多种类型如,内存缓存,文件缓存,页面缓存本文章要来讲述关于php中内存缓存的一些方法,下面我们介绍Memcached缓存和php自带的APC缓存方法。
1.Memcached缓存。
memcached是高性能的分布式内存缓存服务器,通过缓存数据库查询结果,减少数据库访问次数,以提高动态Web应用的速度。memcached 使用了“Key=>Value”方式组织数据。可以允许不同主机上的多个用户同时访问这个缓存系统,一般用于大型网站使用。memcached使用内存缓存数据,所以它是易失的,当服务器重启,或者memcached进程中止,数据便会丢失,所以 memcached不能用来持久保存数据。
过php_memcache的人都会觉得 PHP内存缓存是一个很复杂的东西,其实不然。
memcached 是高效、快速的分布式内存对象缓存系统,主要用于加速 WEB 动态应用程序。
这里介绍memcached在WIN32下的配置及其使用。
一、PHP内存缓存的配置(WIN32环境)
1、下载php_memcache.rar,请从附件下载。
解压压缩包:php_memcache.rar
php_memcache.rar压缩包里主包含的文件有:
/memcached-1.2.1-win32/memcached.exe
/php_memcache/php_memcache.dll
2、打开命令提示符,指向到memcached.exe所在路径,运行memcached.exe -d start。
3、将php_memcache.dll文件拷贝到PHP的动态文件库的文件夹下。
4、在php.ini文件中加入一行extension=php_memcache.dll。
5、重新启动Apache,然后查看一下phpinfo,如果有memcache,那么就说明安装成功!
例:
代码如下 |
复制代码 |
<?php
//包含 memcached 类文件
require_once('memcached-client.php');
//选项设置
$options = array(
'servers' => array('www.hxsd.com:11211'),//memcached 服务的地址、端口
'debug' => true,//是否打开debug
'compress_threshold' => 10240,//超过多少字节的数据时进行压缩
'persistant' => false//是否使用持久连接
);
//实例化memcached对象
$memcached = new memcached($options);
$sql = 'SELECT * FROM table1';
$key = md5($sql);
//如果在memcached中没有缓存数据,把缓存数据写入memcached
if(!($datas = $memcached->get($key)))
{
$conn = mysql_connect('localhost', 'hxsd', '123456');
mysql_select_db('hxsd');
$result = mysql_query($sql);
while($row = mysql_fetch_object($result))
{
$datas[] = $row;
}
//将数据库中获取到的结果集数据保存到 memcached 中,以供下次访问时使用。
$memcached->add($key, $datas);
}
else
{
//直接使用memcached中的缓存数据$datas
}
?>
|
内存缓存二
APC、EC、Zend加速器的比较
一、APC
APC,全称是Alternative PHP Cache,官方翻译叫”可选PHP缓存”。
主页是 http://pecl.php.net/package/apc
php帮助手册页面: http://cn.php.net/apc
APC是个优化器,自安装之日起,就默默地在后台为您的PHP应用服务了.您的所有PHP代码会被缓存起来. (针对php opcode)
另外,APC可提供一定的内存缓存功能.但是这个功能并不是十分完美,有报告说如果频繁使用APC缓存的写入功能,会导致不可预料的错误.如果想使用这个功能,可以看看apc_fetch,apc_store等几个与apc缓存相关的函数.
安装:
代码如下 |
复制代码 |
# pecl install APC
|
配置:(/etc/php.inc)
代码如下 |
复制代码 |
extension=apc.so
|
[apc]
代码如下 |
复制代码 |
apc.enabled = 1
apc.shm_segments = 1
apc.shm_size = 30
apc.optimization = 0
apc.ttl = 7200
apc.user_ttl = 7200
apc.num_files_hint = 1000
apc.mmap_file_mask = /tmp/apc.XXXXXX
|
分页是目前在显示大量结果时所采用的最好的方式。有了下面这些代码的帮助,开发人员可以在多个页面中显示大量的数据。在互联网上,分页是一般用于搜索结果或是浏览全部信息
php基本分页
代码如下 |
复制代码 |
<?php
// database connection info
$conn = mysql_connect('localhost','dbusername','dbpass') or trigger_error("SQL", E_USER_ERROR);
$db = mysql_select_db('dbname',$conn) or trigger_error("SQL", E_USER_ERROR);
// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM numbers";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];
// number of rows to show per page
$rowsperpage = 10;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql = "SELECT id, number FROM numbers LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
// echo data
echo $list['id'] . " : " . $list['number'] . "<br />";
} // end while
/****** build the pagination links ******/
// range of num links to show
$range = 3;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo " [<b>$x</b>] ";
// if not current page...
} else {
// make it a link
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
// echo forward link for lastpage
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
?>
|
先看一个常用的php分页类
代码如下 |
复制代码 |
<?php
/*
Place code to connect to your DB here.
*/
include('config.php'); // include your code to connect to DB.
$tbl_name=""; //your table name
// How many adjacent pages should be shown on each side?
$adjacents = 3;
/*
First get total number of rows in data table.
If you have a WHERE clause in your query, make sure you mirror it here.
*/
$query = "SELECT COUNT(*) as num FROM $tbl_name";
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages[num];
/* Setup vars for query. */
$targetpage = "filename.php"; //your file name (the name of this file)
$limit = 2; //how many items to show per page
$page = $_GET['page'];
if($page)
$start = ($page - 1) * $limit; //first item to display on this page
else
$start = 0; //if no page var is given, set start to 0
/* Get data. */
$sql = "SELECT column_name FROM $tbl_name LIMIT $start, $limit";
$result = mysql_query($sql);
/* Setup page vars for display. */
if ($page == 0) $page = 1; //if no page var is given, default to 1.
$prev = $page - 1; //previous page is page - 1
$next = $page + 1; //next page is page + 1
$lastpage = ceil($total_pages/$limit); //lastpage is = total pages / items per page, rounded up.
$lpm1 = $lastpage - 1; //last page minus 1
/*
Now we apply our rules and draw the pagination object.
We're actually saving the code to a variable in case we want to draw it more than once.
*/
$pagination = "";
if($lastpage > 1)
{
$pagination .= "<div class="pagination">";
//previous button
if ($page > 1)
$pagination.= "<a href="$targetpage?page=$prev">� previous</a>";
else
$pagination.= "<span class="disabled">� previous</span>";
//pages
if ($lastpage < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up
{
for ($counter = 1; $counter <= $lastpage; $counter++)
{
if ($counter == $page)
$pagination.= "<span class="current">$counter</span>";
else
$pagination.= "<a href="$targetpage?page=$counter">$counter</a>";
}
}
elseif($lastpage > 5 + ($adjacents * 2)) //enough pages to hide some
{
//close to beginning; only hide later pages
if($page < 1 + ($adjacents * 2))
{
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($counter == $page)
$pagination.= "<span class="current">$counter</span>";
else
$pagination.= "<a href="$targetpage?page=$counter">$counter</a>";
}
$pagination.= "...";
$pagination.= "<a href="$targetpage?page=$lpm1">$lpm1</a>";
$pagination.= "<a href="$targetpage?page=$lastpage">$lastpage</a>";
}
//in middle; hide some front and some back
elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
{
$pagination.= "<a href="$targetpage?page=1">1</a>";
$pagination.= "<a href="$targetpage?page=2">2</a>";
$pagination.= "...";
for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
{
if ($counter == $page)
$pagination.= "<span class="current">$counter</span>";
else
$pagination.= "<a href="$targetpage?page=$counter">$counter</a>";
}
$pagination.= "...";
$pagination.= "<a href="$targetpage?page=$lpm1">$lpm1</a>";
$pagination.= "<a href="$targetpage?page=$lastpage">$lastpage</a>";
}
//close to end; only hide early pages
else
{
$pagination.= "<a href="$targetpage?page=1">1</a>";
$pagination.= "<a href="$targetpage?page=2">2</a>";
$pagination.= "...";
for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
{
if ($counter == $page)
$pagination.= "<span class="current">$counter</span>";
else
$pagination.= "<a href="$targetpage?page=$counter">$counter</a>";
}
}
}
//next button
if ($page < $counter - 1)
$pagination.= "<a href="$targetpage?page=$next">next �</a>";
else
$pagination.= "<span class="disabled">next �</span>";
$pagination.= "</div>n";
}
?>
<?php
while($row = mysql_fetch_array($result))
{
// Your while loop here
}
?>
<?=$pagination?>
|
实例
代码如下 |
复制代码 |
<?php
class PageView{
/**页码**/
public $pageNo = 1;
/**页大小**/
public $pageSize = 20;
/**共多少页**/
public $pageCount = 0;
/**总记录数**/
public $totalNum = 0;
/**偏移量,当前页起始行**/
public $offSet = 0;
/**每页数据**/
public $pageData = array();
/**是否有上一页**/
public $hasPrePage = true;
/**是否有下一页**/
public $hasNextPage = true;
public $pageNoList = array();
public $jsFunction ='jsFunction';
/**
*
* @param unknown_type $count 总行数
* @param unknown_type $size 分页大小
* @param unknown_type $string
*/
public function __construct($count=0, $size=20,$pageNo=1,$pageData =array(),$jsFunction='jsFunction'){
$this->totalNum = $count;//总记录数
$this->pageSize = $size;//每页大小
$this->pageNo = $pageNo;
//计算总页数
$this->pageCount = ceil($this->totalNum/$this->pageSize);
$this->pageCount = ($this->pageCount<=0)?1:$this->pageCount;
//检查pageNo
$this->pageNo = $this->pageNo == 0 ? 1 : $this->pageNo;
$this->pageNo = $this->pageNo > $this->pageCount? $this->pageCount : $this->pageNo;
//计算偏移
$this->offset = ( $this->pageNo - 1 ) * $this->pageSize;
//计算是否有上一页下一页
$this->hasPrePage = $this->pageNo == 1 ?false:true;
$this->hasNextPage = $this->pageNo >= $this->pageCount ?false:true;
$this->pageData = $pageData;
$this->jsFunction = $jsFunction;
}
/**
* 分页算法
* @return
*/
private function generatePageList(){
$pageList = array();
if($this->pageCount <= 9){
for($i=0;$i<$this->pageCount;$i++){
array_push($pageList,$i+1);
}
}else{
if($this->pageNo <= 4){
for($i=0;$i<5;$i++){
array_push($pageList,$i+1);
}
array_push($pageList,-1);
array_push($pageList,$this->pageCount);
}else if($this->pageNo > $this->pageCount - 4){
array_push($pageList,1);
array_push($pageList,-1);
for($i=5;$i>0;$i--){
array_push($pageList,$this->pageCount - $i+1);
}
}else if($this->pageNo > 4 && $this->pageNo <= $this->pageCount - 4){
array_push($pageList,1);
array_push($pageList,-1);
array_push($pageList,$this->pageNo -2);
array_push($pageList,$this->pageNo -1);
array_push($pageList,$this->pageNo);
array_push($pageList,$this->pageNo + 1);
array_push($pageList,$this->pageNo + 2);
array_push($pageList,-1);
array_push($pageList,$this->pageCount);
}
}
return $pageList;
}
/***
* 创建分页控件
* @param
* @return String
*/
public function echoPageAsDiv(){
$pageList = $this->generatePageList();
$pageString ="<div class='pagination'><div class='page-bottom'>";
if(!empty($pageList)){
if($this->pageCount >1){
if($this->hasPrePage){
$pageString = $pageString ."<a class='page-next' href="javascript:" .$this->jsFunction . "(" . ($this->pageNo-1) . ")">上一页</a>";
}
foreach ($pageList as $k=>$p){
if($this->pageNo == $p){
$pageString = $pageString ."<span class='page-cur'>" . $this->pageNo . "</span>";
continue;
}
if($p == -1){
$pageString = $pageString ."<span class='page-break'>...</span>";
continue;
}
$pageString = $pageString ."<a href="javascript:" .$this->jsFunction . "(" . $p . ")">" . $p . "</a>";
}
if($this->hasNextPage){
$pageString = $pageString ."<a class='page-next' href="javascript:" .$this->jsFunction . "(" . ($this->pageNo+1) . ")">下一页</a>";
}
}
}
$pageString = $pageString .("</div></div>");
return $pageString;
}
}
?>
|
css代码
代码如下 |
复制代码 |
<style type="text/css">
<!--
.pagination {font-family: Tahoma;overflow: hidden; padding-top: 12px; text-align: center;}
.pagination-tab { margin-bottom: 20px;}
.pagination a, .pagination .page-cur, .pagination .page-prev_g, .pagination .page-prev, .pagination .page-next, .pagination .page-next_g, .pagination .page-break, .pagination .page-skip {
display: inline-block;font-family: Tahoma,SimSun,Arial; height: 22px;line-height:22px; margin: 0; min-width: 16px;padding: 0 5px; text-align: center; vertical-align: top; white-space: nowrap;}
.pagination a, .pagination .page-prev_g, .pagination .page-prev, .pagination .page-next, .pagination .page-next_g, .pagination .page-cur, .pagination .page-break {
border: 1px solid #ed3d83; color:#e9357d; font-weight:bold;}
.pagination a:hover { border: 1px solid #ed3d83;text-decoration: none; background-color:#f95f9d; color:#fff;}
.pagination .page-prev_g, .pagination .page-prev, .pagination .page-next, .pagination .page-next_g { width: 36px; background-image: url(../static/img/page.gif);}
.pagination .page-prev { background-position: -0px -38px; padding-left: 16px;}
.pagination .page-prev_g { background-position:0px -59px; padding-left: 16px; color:#cbcbcb; font-weight:normal;}
.pagination .page-next { background-position: 0px 0px; padding-right: 16px; font-weight:normal;}
.pagination .page-next_g { background-position: -0px -19px; padding-right: 16px; color:#cbcbcb;}
.pagination .page-cur {background-color: #f95f9d; border: 1px solid #ed3d83;color: #fff;font-weight: bold;}
.pagination .page-break {border: medium none; background:none transparent; color:#333;}
-->
</style>
|
在php页面中的调用方法
代码如下 |
复制代码 |
$pageNo = $_GET['pageNo'];
if(empty($pageNo)){
$pageNo = 1;
}
//分页数据
$pageData = News::getNewsPage($pageNo,$pageSize);
//取得总行数
$count = News::getNewsCount();
//创建分页器
$p = new PageView($count['0']['TOTAL'],$pageSize,$pageNo,$pageData);
//生成页码
$pageViewString = $p->echoPageAsDiv();
|
文件缓存就是指把缓存生成一个文件,这个文件可以是php,txt等等文件,当我下载访问时就来判断访问上次生成时间,如果超过了我们指定的时间再重新生成一次,否则就直接调用缓存文件,这样就可以减少了对mysql数据库的查询了。
文件缓存原理
1.把需要缓存的数据通过serialize函数序列化后直接保存到文件。在需要使用缓存数据的时候,通过反序列化读入文件内容并复制给需要的变量,然后使用。不经常改动的数据可以写入缓存文件。
文件缓存实例
index.php
代码如下 |
复制代码 |
define('CACHE_ROOT','./');
include_once('./cache.func.php');
$file = 'qzp';
$cacheFile = getCacheFileByID($file,'info/');
print_R(readCache($cacheFile));
$info = array(
'username'=>'qzp',
'area_name'=>'admin',
'mp_name'=>'1234',
'gh_name'=>'5678');
writeCache($cacheFile,$info);
cache.func.php文件
function arrayeval($array, $level = 0) {
$space = '';
for($i = 0; $i <= $level; $i++) {
$space .= "t";
}
$evaluate = "Arrayn$space(n";
$comma = $space;
foreach($array as $key => $val) {
$key = is_string($key) ? '''.addcslashes($key, ''\').''' : $key;
$val = !is_array($val) && (!preg_match("/^-?[1-9]d*$/", $val) || strlen($val) > 12) ? '''.addcslashes($val, ''\').''' : $val;
if(is_array($val)) {
$evaluate .= "$comma$key => ".arrayeval($val, $level + 1);
} else {
$evaluate .= "$comma$key => $val";
}
$comma = ",n$space";
}
$evaluate .= "n$space)";
return $evaluate;
}
function getCacheFileByID($id,$pre='info/',$md5=true){
if($md5){
$md5id = md5($id);
return CACHE_ROOT.'/'.$pre.substr($md5id,0,2).'/'.substr($md5id,2,2).'/'.$id;
}else{
return CACHE_ROOT.'/'.$pre.$id;
}
}
function readCache($filename,$time=0){
if($datas = @file_get_contents($filename)){
$datas = unserialize($datas);
if($time < 1 || (time() - $datas['time'] < $time)){
return $datas['data'];
}
}
return false;
}
function writeCache($filename,$data){
makeDir(dirname($filename));
if($handle = fopen($filename,'w+')){
$datas = array('data'=>$data,'time'=>time());
flock($handle,LOCK_EX);
$rs = fputs($handle,serialize($datas));
flock($handle,LOCK_UN);
fclose($handle);
if($rs!==false){
return true;
}
}
return false;
}
function makeDir($path)
{
if (! file_exists ( $path )) {
makeDir ( dirname ( $path ) );
if (! mkdir ( $path, 0777 ))
die ( '无法创建文件夹' . $path );
}
}
|
把要缓存的文件序列化下存放起来,当使用的时候反序列化回来使用。
使用对PHP模板数据进行缓存的工具smarty。smarty将HTML文件缓存成一个静态的HTML页,需要缓存的模板文件可以使用smarty。
例:
代码如下 |
复制代码 |
<?php
//包含Smarty类库
require('libs/Smarty.class.php');
//创建Smarty类的对象
$smarty = new Smarty;
//启用缓存
$smarty->caching = true;
//指定缓存文件保存的目录
$smarty->cache_dir = "./cache/";
//也会把输出保存
$smarty->display('index.tpl')
?>
|
本文章总结了两个常用的手机归属地查询程序,一种是利用api调用第三方接口实现,一种是利用我们自己的手机数据库查询然后再判断手机号归属地查询.
先来看一个调用第三方法网站的一个程序
主要使用curl实现,需要开启php对curl的支持.
如果你是windows系统在你的的php.ini文件的设置,找到php_curl.dll,并取消前面的分号注释就行了,如下所示:
//取消下在的注释
extension=php_curl.dll
如果您是在Linux下面,那么,您需要重新编译您的PHP了,编辑时,您需要打开编译参数,在configure命令上加上“–with-curl”参数。
然后重启apache
代码如下 |
复制代码 |
<?php
header("Content-Type:text/html;charset=utf-8");
if (isset($_GET['number'])) {
$url = 'http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo';
$number = $_GET['number'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "mobileCode={$number}&userId=");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
$data = simplexml_load_string($data);
if (strpos($data, 'http://')) {
echo '手机号码格式错误!';
} else {
echo $data;
}
}
?>
<form action="mobile.php" method="get">
手机号码: <input type="text" name="number" /> <input type="submit" value="提交" />
</form>
|
实例二
这个实例利用了手机数据库,把文件保存在本地然后查找数据库再来差别,但是你得经常更新数据库才行哦。
代码如下 |
复制代码 |
<html>
<head>
<title>手机号码归属地查询</title>
</head>
<style type="text/css">
#main{
height:100%;
}
#left {
float:left;
height:100%;
width:10%;
float:left;
}
#right{
float:left;
height:100%;
width:100$;
}
</style>
<body>
<?php
require ('function.php');
$pwd="xiaolin"; //密码,请修改
if (!isset($_GET["action"]) ){
header("Location:manage.php?action=login");
}
if ($_GET["action"]=="login"){
?>
<form action="manage.php?action=loginin" method="POST">
<p>请输入密码:</p>
<p><input type="password" value="" name="pwd"></p>
<p><input type="submit" value="登录"></p>
</form>
<?php
}elseif ($_GET["action"]=="loginin"){
$repwd=$_POST["pwd"];
if ($repwd != $pwd){
echo "Sorry,密码错误~!";
}else {
$_SESSION["flag"]=true;
leftnav();
}
}elseif ($_GET["action"]== "info" ){
leftnav();
getinfo();
?>
</div>
</div>
<?php
}elseif ($_GET["action"]=="edit"){
leftnav();
?>
<form action="manage.php?action=editp" method="POST">
<p>手机号码:<input type="text" name="num">(至少7位)</p>
<p>详细资料:<input type="text" name="info"></p>
<input type="submit" value="更新">
</form>
<?php
}elseif ($_GET["action"]== "loginout"){
if (isset($_SESSION["flag"])){
unset($_SESSION["flag"]);
session_destroy();
}
echo "<p><a>登出</a></p><p><a href='manage.php'>返回</a></p>";
}elseif ($_GET["action"]=="editp"){
leftnav();
$num=$_POST["num"];
$info=$_POST['info'];
if (!empty($num) && !empty($info) && strlen($num)>=7 ){
update($num,$info);
}else{
die ("不得为空!");
}
}elseif ("about"==$_GET["action"]){
leftnav();
showabout();
}
?>
</body>
</html>
index.php
<html>
<head>
<title>手机号码归属地查询</title>
</head>
<body>
<form action="index.php?action=search" method="POST">
<p>请输入你要查询的手机号码:<input type="text" name="phone"></p>
<p><input type="submit" value="查询手机号码归属地"></p></p>
</form>
<?php
if (isset($_GET["action"])){
if ("search"==$_GET["action"] ){
require ('function.php');
$phone=(isset($_POST["phone"]))?$_POST["phone"]:die ("请返回");
echo "你查询的手机号码<font color=red>".$phone."</font>属于<font color=red>".getphone($phone)."</font>";
}
}
?>
</body>
</html>
function.php函数
<?php
session_start();
function update($num,$info){
$dbpath="xiaolin/";
$len=strlen($num);
if ( $len < 7 ){
return "手机号码最低7位哦";
}
$par="[0-9]";
for ($i=0;$i<$len;$i++){
if(!ereg($par,substr($num,$i,1) ) ){
return "手机号码只能为数字";
}
}
$sunum=scandir($dbpath); //得到支持的手机号码前缀
array_splice($sunum,0,1); //把当前目录取消
array_splice($sunum,0,1); //把上一级目录去掉
$sub=substr($num,0,3); //取得该号码的前三位
if (in_array($sub,$sunum) ){
$num1=ltrim(substr($num,3,4),"0");
$search=file($dbpath.$sub);
$tmp=$search[$num1];
$search[$num1]=$num1.'='.$info."n";
$fp1=fopen($dbpath.$sub.'1','wb+');
for ($i=0;$i<10000;$i++){
//$phone=str_pad($i,4,"0",STR_PAD_LEFT);
//$phoneinfo="";
//$phoneinfo.=$phone."=";
//$phoneinfo=(isset($search[$i]))?$search[$i]:"";
//$phoneinfo.="n";
fwrite($fp1,$search[$i]);
}
fclose($fp1);
echo "$num 已更新";
}else{
die ("暂不支持$sub");
}
}
function getphone($phone){
$dbpath="xiaolin/";
$len=strlen($phone);
if ( $len < 7 ){
return "手机号码最低7位哦";
}
$par="[0-9]";
for ($i=0;$i<$len;$i++){
if(!ereg($par,substr($phone,$i,1) ) ){
return "手机号码只能为数字";
}
}
$sunum=scandir($dbpath); //得到支持的手机号码前缀
array_splice($sunum,0,1); //把当前目录取消
array_splice($sunum,0,1); //把上一级目录去掉
$sub=substr($phone,0,3); //取得该号码的前三位
if (in_array($sub,$sunum) ){
$num=ltrim(substr($phone,3,4),"0");
$search=file($dbpath.$sub);
$tmp=$search[$num];
$result=substr($tmp,strpos($tmp,"=")+1,strlen($tmp)-strpos($tmp,"=")-2); //处理数据
return (strlen($result)>1)?$result:"无数据";
}else{
return "暂不支持$sub";
}
}
function check(){
if (!isset($_SESSION["flag"]) ){
die ("<p>请<a href='manage.php?action=login'>登录!</a></p>");
}elseif ($_SESSION["flag"] != true){
die ("<p>请<a href='manage.php?action=login'>登录!</a></p>");
}
}
function getinfo(){
check();
$nums=array("130","131","132","133","134","135","136","137","138","139","150","151","153","155","156","157","158","159");
$counts="";
for($j=0;$j<count($nums);$j++){
$id=$j;
if ($id >= count($nums) ){ die ("OVER"); }
$nownum=$nums[$id]; //当前的号码段
$dbpath="xiaolin/";
$fp=fopen("xiaolin/$nownum",'r');
while(!feof($fp)){
$line=fgets($fp);
$tmp=explode("=",$line);
$num1[$tmp[0]]=substr($line,strpos($line,"=")+1,strlen($line)-strpos($line,"=")-2);
}
fclose($fp);
$flag=0;
for($i=0;$i<10000;$i++){
$ser=str_pad($i,4,"0",STR_PAD_LEFT);
if(!strlen($num1[$ser]) ==0 ){
++$flag;
}
}
$counts+=$flag;
echo "$nownum:段记录$flag</p>";
}
echo "总计$counts";}
function leftnav(){
check();
?>
<div>
<div id="right">
<?php
}
function showabout(){
echo "<p>手机号码归属地查询</p>
";
}
?>
|
搞了半天终于把CKEditor搞了个明明白白,配合ckfinder实现了图片的上传,具体步骤给需要的同志们。
1、建立项目ckeditor,将ckeditor和ckfinder解压缩放到项目下
两个东东的下载地址分别为:
ckeditor: http://ckeditor.com/download/
ckfinder: http://ckfinder.com/download
项目目录结构为:
ckeditor
---ckeditor
--ckfinder
--test.php 用来测试的PHP文件
2、找到ckfinder目录下的config.php文件打开
1)定位到CheckAuthentication方法,默认此方法只有返回值false,这样是不允许上传文件到服务器的,需要将其进行修改,函数内已经用英文注明,不建议直接改为false,因为那样会不安全,什么都会上传了,所以用session来处理一下,就成了下面的样子
代码如下 |
复制代码 |
session_start();
function CheckAuthentication()
{
if(isset($_SESSION['UseEditor']))//这个随便命名就可以了
return true;
else
return false;
}
|
2) 配置上传文件位置,
默认ckfinder会把上传文件放到根目录下的ckfinder/userfiles/images文件夹下,我们可以修改成自己的项目目录下,在项目下建立upfiles文件夹,在config.php中找到baseUrl并且修改为:
代码如下 |
复制代码 |
$baseUrl = '/ckeditor/upfiles/';
|
这样上传文件会保存到upfiles下的images文件夹。当然,你也可以根据需要设置不同的上传文件夹,至于怎么传值给他以判断上传文件夹,当然是通过session了。
3、修改上传文件名,默认系统以原有名字命名,所以我们重新命名文件。方法为:打开ckfindercoreconnectorphpphp5CommandHandler下FileUpload.php文件
找到 $sUnsafeFileName 后面加上重命名代码,如下:
代码如下 |
复制代码 |
$sUnsafeFileName = CKFinder_Connector_Utils_FileSystem::convertToFilesystemEncoding(CKFinder_Connector_Utils_Misc::mbBasename($uploadedFile['name']));
//先获取原文件后缀
$sExtension=CKFinder_Connector_Utils_FileSystem::getExtension($sUnsafeFileName);
//重新命名文件
$sUnsafeFileName=date('YmdHis').'.'.$sExtension;
|
4、最后在test.php中使用ckfinder,代码如下:
代码如下 |
复制代码 |
session_start();
$_SESSION[‘UseEditor’]=’ok’;//一定别忘记这个哦,否则没法上传
include_once('ckeditor/ckeditor.php');
include_once('ckfinder/ckfinder.php');
$fc = new CKEditor();
CKFinder::SetupCKEditor($fc,'./ckfinder/');
$fc->editor("content", "<p>Initial value.</p>");
|