function cat_options($spec_cat_id, $arr)
{
static $cat_options = array();
if (isset($cat_options[$spec_cat_id]))
{
return $cat_options[$spec_cat_id];
}
if (!isset($cat_options[0]))
{
/*
初始化关键参数:
$level:当前子节点深度
$last_cat_id:当前父节点ID
$options:带有缩进级别的数组
$cat_id_array:沿同一路径的父节点依次进驻
$level_array:该节点的子节点深度,也是依次进驻
*/
<?php
// 获取用户IP地址
function getIp() {
if($_SERVER['HTTP_CLIENT_IP'])
{
return $_SERVER['HTTP_CLIENT_IP'];
} elseif ($_SERVER['HTTP_X_FORWARDED_FOR']) {
return $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
return $_SERVER['REMOTE_ADDR'];
}
}
function getFile($url)
{
if($f=fopen("$url","r"))
{
while(!feof($f))
{
$s.=fgets($f);
}
fclose($f);
return $s;
} else {
return false;
}
}
function putFile($file_name,$file_string)
{
if($f=fopen($file_name,"w"))
{
fwrite($f, $file_string);
}
fclose($f);
}
function cnSubStr($string,$sublen) {
if($sublen>=strlen($string)){
return $string;
}
$s="";
for($i=0;$i<$sublen;$i++){
if(ord($string{$i})>127){
$s.=$string{$i}.$string{++$i};
continue;
}else{
$s.=$string{$i};
continue;
}
}
return $s."...";
}
function getPageBar($count = 0)
{
$bad_link_color = "#C0C0C0";
$page["url"] = eregi_replace("&page=[^&]+","",basename($_SERVER[SCRIPT_NAME])."?".$_SERVER[QUERY_STRING]);
$page["result_count"] = (string) $count;
$page["this_page"] = (empty($_GET["page"]))?"1":$_GET["page"];
$page["this_page"] = ($page["result_count"] == 0)?"0":$page["this_page"];
$page["page_size"] = $GLOBALS["option"]["page_size"];
$page["page_count"] = (string) ceil($page["result_count"]/$page["page_size"]);
$page["first_page"] = ($page["this_page"] > 1)?"<a href="".$page["url"]."&page=1" title="首页"><span style="font-size:12px; font-weight: bold; font-familly: Courier;">«</span></a>":"";
$page["rearward_page"] = ($page["this_page"] < (int) $page["page_count"])?"<a href="".$page["url"]."&page=".$page["page_count"]."" title="末页"><span style="font-size:12px; font-weight: bold; font-familly: Courier;">»</span></a>":"";
$page["prev_page"] = ($page["this_page"] > 1)?"<a href="".$page["url"]."&page=".((int)$page["this_page"] - 1)."" title="上一页"><span style="font-size:12px; font-weight: bold; font-familly: Courier;">‹</span></a>":"";
$page["next_page"] = ($page["this_page"] < (int) $page["page_count"])?"<a href="".$page["url"]."&page=".((int)$page["this_page"] + 1)."" title="下一页"><span style="font-size:12px; font-weight: bold; font-familly: Courier;">›</span></a>":"";
$page['start_page'] = ((int)$page["this_page"]-5<1)?1:(int)$page["this_page"]-5;
$page['end_page'] = ((int)$page["this_page"]+5 > $page['page_count'])?(int)$page["page_count"]:(int)$page["this_page"]+5;
for ($i = $page['start_page'];$i <= $page['end_page'];$i++)
{
$selected = ($_GET["page"] == $i)?"selected":"";
$page["page_select"] .= "<option value="$i" $selected>$i</option>";
$page["page_list"] .= ($i == $page["this_page"])?" <font color="red">$i</font> ":"<a href="".$page['url']."&page=$i" title="第 ".$i." 页">[$i]</a>";
}
return $page;
}
function getRows($table,$order='')
{
if (!empty($order))
{
$order = explode(',',$order);
$order = 'ORDER BY `'.$order[0].'` '.$order[1];
}
$query = dbQuery("SELECT * FROM `".$GLOBALS['prefix'].$table."` ".$order.";");
while ($row = dbArray($query))
{
$link[$row['id']] = $row;
}
return $link;
}
function autoTime($time)
{
preg_match('/([0-9]*)-([0-9]*)-([0-9]*) ([0-9]*):([0-9]*):([0-9]*)/',$time,$date);
return mktime ($date[4],$date[5],$date[6],$date[2],$date[3],$date[1]);
}
function getTime() {
$t = explode(' ', microtime());
return $t[1] + $t[0];
}
function calendar($time)
{
$start = mktime(0, 0, 0, date('m', $time), 1, date('Y', $time));
$prev_month['year'] = date('Y',$start-86400);
$prev_month['month'] = date('m',$start-86400);
$end = mktime(0, 0, 0, date('m', $time)+1, 1, date('Y', $time));
$next_month['year'] = date('Y',$end);
$next_month['month'] = date('m',$end);
$sWeekday=array('日','一','二','三','四','五','六');
//$sWeekday=array('S','M','T','W','T','F','S');
$title=date('M Y', $time);
$str = '';
$str .= <<<END
<table class="calendar" cellspacing="1">
<tr class="title">
<th colspan="1"><a href=?mod=article&year={$prev_month['year']}&month={$prev_month['month']}><span style="font-size:12px; font-weight: bold; font-familly: Courier;">«</span></a></td>
<th colspan="5">{$title}</td>
<th colspan="1"><a href=?mod=article&year={$next_month['year']}&month={$next_month['month']}><span style="font-size:12px; font-weight: bold; font-familly: Courier;">»</span></a></td>
</tr>
<tr class="head">
<th>{$sWeekday[0]}</td>
<th>{$sWeekday[1]}</td>
<th>{$sWeekday[2]}</td>
<th>{$sWeekday[3]}</td>
<th>{$sWeekday[4]}</td>
<th>{$sWeekday[5]}</td>
<th>{$sWeekday[6]}</td>
</tr>
<tr class="cbody">
END;
$year = (empty($_GET['year']))?date('Y'):$_GET['year'];
$month = (empty($_GET['month']))?date('m'):$_GET['month'];
$query = dbQuery("SELECT FROM_UNIXTIME(date,'%e') as `day`,count(*) as `count` FROM `".$GLOBALS['prefix']."article`,`".$GLOBALS['prefix']."article_class` WHERE FROM_UNIXTIME(date,'%Y/%m') = '".$year."/".$month."' AND `status` = 'published' AND ".$GLOBALS['prefix']."article.class_id = ".$GLOBALS['prefix']."article_class.id AND `in_main_page` = 1 GROUP BY `day`;");
for ($i = 0;$i < mysql_num_rows($query);$i++)
{
$row = dbArray($query);
$calendar[$row['day']] = $row['count'];
}
for ($i = 0;$i < date('w',$start);$i++)
{
$str.= '<td> </td>';
}
for($stamp=$start;$stamp<$end;$stamp+=86400) // loop through each day, which is 86400 seconds
{
$weekday=date('w', $stamp);
$day = date('d', $stamp);
if(date('Y-m-d', $stamp)==date('Y-m-d')) $style='today';
else if(date('w', $stamp)==0 || date('w', $stamp)==6) $style='weekend';
else $style='weekday';
$str.= "tt".'<td class="'.$style.'">';
$str.= ($calendar[date('j', $stamp)] > 0)?'<a href="?mod=article&year='.$year.'&month='.$month.'&day='.$day.'">'.(int)$day.'</a>':(int)$day;
$str.= '</td>'."n";
if(date('w', $stamp)==6) $str.="t".'</tr>'."n";
}
$str .= '</table>';
return $str;
}
//php利用纯真ip数据库查地址的函数
function convertip($ip) {
if(!preg_match("/^d{1,3}.d{1,3}.d{1,3}.d{1,3}$/", $ip)) {
return '';
}
if($fd = @fopen( "e:hostswkhddbipdatawry.dat", 'rb')) {//fopen()中是纯真ip数据库文件位置,请自行设定!
$ip = explode('.', $ip);
$ipNum = $ip[0] * 16777216 + $ip[1] * 65536 + $ip[2] * 256 + $ip[3];
$DataBegin = fread($fd, 4);
$DataEnd = fread($fd, 4);
$ipbegin = implode('', unpack('L', $DataBegin));
if($ipbegin < 0) $ipbegin += pow(2, 32);
$ipend = implode('', unpack('L', $DataEnd));
if($ipend < 0) $ipend += pow(2, 32);
$ipAllNum = ($ipend - $ipbegin) / 7 + 1;
$BeginNum = 0;
$EndNum = $ipAllNum;
while($ip1num > $ipNum || $ip2num < $ipNum) {
$Middle= intval(($EndNum + $BeginNum) / 2);
fseek($fd, $ipbegin + 7 * $Middle);
$ipData1 = fread($fd, 4);
if(strlen($ipData1) < 4) {
fclose($fd);
return '系统错误';
}
$ip1num = implode('', unpack('L', $ipData1));
if($ip1num < 0) $ip1num += pow(2, 32);
if($ip1num > $ipNum) {
$EndNum = $Middle;
continue;
}
$DataSeek = fread($fd, 3);
if(strlen($DataSeek) < 3) {
fclose($fd);
return '系统错误';
}
$DataSeek = implode('', unpack('L', $DataSeek.chr(0)));
fseek($fd, $DataSeek);
$ipData2 = fread($fd, 4);
if(strlen($ipData2) < 4) {
fclose($fd);
return 'System Error';
}
$ip2num = implode('', unpack('L', $ipData2));
if($ip2num < 0) $ip2num += pow(2, 32);
if($ip2num < $ipNum) {
if($Middle == $BeginNum) {
fclose($fd);
return 'Unknown';
}
$BeginNum = $Middle;
}
}
$ipFlag = fread($fd, 1);
if($ipFlag == chr(1)) {
$ipSeek = fread($fd, 3);
if(strlen($ipSeek) < 3) {
fclose($fd);
return '系统错误';
}
$ipSeek = implode('', unpack('L', $ipSeek.chr(0)));
fseek($fd, $ipSeek);
$ipFlag = fread($fd, 1);
}
if($ipFlag == chr(2)) {
$AddrSeek = fread($fd, 3);
if(strlen($AddrSeek) < 3) {
fclose($fd);
return 'System Error';
}
$ipFlag = fread($fd, 1);
if($ipFlag == chr(2)) {
$AddrSeek2 = fread($fd, 3);
if(strlen($AddrSeek2) < 3) {
fclose($fd);
return 'System Error';
}
$AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
fseek($fd, $AddrSeek2);
} else {
fseek($fd, -1, SEEK_CUR);
}
while(($char = fread($fd, 1)) != chr(0))
$ipAddr2 .= $char;
$AddrSeek = implode('', unpack('L', $AddrSeek.chr(0)));
fseek($fd, $AddrSeek);
while(($char = fread($fd, 1)) != chr(0))
$ipAddr1 .= $char;
} else {
fseek($fd, -1, SEEK_CUR);
while(($char = fread($fd, 1)) != chr(0))
$ipAddr1 .= $char;
$ipFlag = fread($fd, 1);
if($ipFlag == chr(2)) {
$AddrSeek2 = fread($fd, 3);
if(strlen($AddrSeek2) < 3) {
fclose($fd);
return 'System Error';
}
$AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
fseek($fd, $AddrSeek2);
} else {
fseek($fd, -1, SEEK_CUR);
}
while(($char = fread($fd, 1)) != chr(0))
$ipAddr2 .= $char;
}
fclose($fd);
if(preg_match('/http/i', $ipAddr2)) {
$ipAddr2 = '';
}
$ipaddr = "$ipAddr1"; // 完整地址为 "$ipAddr1 $ipAddr2"
$ipaddr = preg_replace('/CZ88.NET/is', '', $ipaddr);
$ipaddr = preg_replace('/^s*/is', '', $ipaddr);
$ipaddr = preg_replace('/s*$/is', '', $ipaddr);
if(preg_match('/http/i', $ipaddr) || $ipaddr == '') {
$ipaddr = 'Unknown';
}
return $ipaddr;
} else {
$datadir = PHPCMS_ROOT.'./ipdata/';
$ip_detail = explode('.', $ip);
if(file_exists($datadir.$ip_detail[0].'.txt')) {
$ip_fdata = @fopen($datadir.$ip_detail[0].'.txt', 'r');
} else {
if(!($ip_fdata = @fopen($datadir.'0.txt', 'r'))) {
return 'Invalid IP data file';
}
}
for ($i = 0; $i <= 3; $i++) {
$ip_detail[$i] = sprintf('%03d', $ip_detail[$i]);
}
$ip = join('.', $ip_detail);
do {
$ip_data = fgets($ip_fdata, 200);
$ip_data_detail = explode('|', $ip_data);
if($ip >= $ip_data_detail[0] && $ip <= $ip_data_detail[1]) {
fclose($ip_fdata);
return $ip_data_detail[2].$ip_data_detail[3];
}
} while(!feof($ip_fdata));
fclose($ip_fdata);
return '未知地址';
}
}
// station_id 函数
function sta_id(){
include_once('./include/tq/config.inc.php');
include_once('./include/tq/error.inc.php');
include_once('./include/tq/mysql.inc.php');
include_once('./include/tq/template.inc.php');
unset($onlineip);
if($_SERVER['HTTP_CLIENT_IP']){
$onlineip=$_SERVER['HTTP_CLIENT_IP'];
}elseif($_SERVER['HTTP_X_FORWARDED_FOR']){
$onlineip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$onlineip=$_SERVER['REMOTE_ADDR'];
}
$ips = $onlineip;
$addr = convertip($ips);
$address = $addr;
$address = str_replace(array('省','市','县','工业','北京','区','大学','武汉','西安','安交','海交','新疆','大连','广西'),array(' ',' ',' ',' 工业','北京 ',' ',' ','武汉 ','西安 ','安 交','海 交','新疆 ','大连 ','广西 '),$address);
$addresss = explode(" ",$address);
$address1 = $addresss[0];
$address2 = $addresss[1];
$address3 = $addresss[2];
$address4 = $addresss[3];
$query = dbQuery("select count(*) as num from ".weather_station." where province like '$address1' ");//查询 省字段 数目
$row = dbArray($query);
$number = $row["num"];
if($number>0 && $address2<>'' && $address1<>上海 && $address1<>重庆){
unset($addresss[0]);
}
if($address4==''){
unset($addresss[3]);
}
if($address3==''){
unset($addresss[2]);
}
$query = dbQuery("select count(*) as num from ".weather_station." where station like '$address4' ");//查询 县 字段
$row = dbArray($query);
$number = $row["num"];
if($number==0){
unset($addresss[3]);
}
$query = dbQuery("select count(*) as num from ".weather_station." where station like '$address3' ");//查询 县 字段
$row = dbArray($query);
$number = $row["num"];
if($number==0){
unset($addresss[2]);
}
//数组数据2 查询开始
$queryx = dbQuery("select count(*) as nums from ".weather_station." where station like '$address2' ");//查询 县 字段
$row = dbArray($queryx);
$nums = $row["nums"];
$queryy = dbQuery("select count(*) as numd from ".weather_station." where district like '$address2' ");//查询 市 字段
$row = dbArray($queryy);
$numd = $row["numy"];
if($nums==0 && $numd==0){
unset($addresss[1]); // 如果 数组数据2 不在数据库里则删除数据2
}
//数组数据2 查询结束
$query = dbQuery("select count(*) as num from ".weather_station." where district like '$address2' ");//查询 市 字段
$row = dbArray($query);
$number = $row["num"];
if($number>1 && $address3<>'' && $nums<>0 && $address2<>广州 ){
unset($addresss[1]); // 如果数组数据2在数据库里有 多个 则删除数据2
}
@extract(dbQuery("select count(*) as num_0 from ".weather_station." where district like '$address1' "));//查询 市 字段
@extract(dbQuery("select count(*) as num_1 from ".weather_station." where station like '$address2' "));//查询 县 字段
$number = $num_0;
$numbery = $num_1;
if($number>1 && $numbery>0 && $address2<>''){
unset($addresss[0]); //如果数组数据1在数据库里有 多个 则删除数据1
}
$addresss = implode("",$addresss);
//字符串处理完毕 下面开始查询 station_id
$query1 = dbQuery("select count(*) as nums_addresss from ".weather_station." where station like '$addresss' ");
$row1 = dbArray($query1);
$nums_addresss = $row1["nums_addresss"];
$query2 = dbQuery("select count(*) as numd_addresss from ".weather_station." where district like '$addresss' ");
$row2 = dbArray($query2);
$numd_addresss = $row2["numd_addresss"];
if($nums_addresss>0){
$result = dbQuery("SELECT station_id FROM ".weather_station." WHERE station like '$addresss' ORDER BY id");
$r = dbArray($result);
$station_id[] = $r[station_id];
$station_id = $station_id[0];
return $station_id; // 查询结果
}
if($nums_addresss==0 && $numd_addresss>0){
$result = dbQuery("SELECT station_id FROM ".weather_station." WHERE district like '$addresss' ORDER BY id");
$r = dbArray($result);
$station_id[] = $r[station_id];
$station_id = $station_id[0];
return $station_id; // 查询结果
//echo $station_id;
}
}
function get_real_ip()
{
$ip=false;
if(!empty($_SERVER["HTTP_CLIENT_IP"]))
{
$ip = $_SERVER["HTTP_CLIENT_IP"];
}
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
if ($ip)
{
array_unshift($ips, $ip); $ip = FALSE;
}
for ($i = 0; $i < count($ips); $i++)
{
if (!eregi ("^(10|172.16|192.168).", $ips[$i]))
{
$ip = $ips[$i];
break;
}
}
}
return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}
function addr(){
include_once('./include/tq/config.inc.php');
include_once('./include/tq/error.inc.php');
include_once('./include/tq/mysql.inc.php');
include_once('./include/tq/template.inc.php');
unset($onlineip);
if($_SERVER['HTTP_CLIENT_IP']){
$onlineip=$_SERVER['HTTP_CLIENT_IP'];
}elseif($_SERVER['HTTP_X_FORWARDED_FOR']){
$onlineip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$onlineip=$_SERVER['REMOTE_ADDR'];
}
$ips = $onlineip;
$addr = convertip($ips);
$address = $addr;
$address = str_replace(array('省','市','县','工业','北京','区','大学','武汉','西安','安交','海交','新疆','大连','广西'),array(' ',' ',' ',' 工业','北京 ',' ',' ','武汉 ','西安 ','安 交','海 交','新疆 ','大连 ','广西 '),$address);
$addresss = explode(" ",$address);
$address1 = $addresss[0];
$address2 = $addresss[1];
$address3 = $addresss[2];
$address4 = $addresss[3];
$query = dbQuery("select count(*) as num from ".weather_station." where province like '$address1' ");//查询 省字段 数目
$row = dbArray($query);
$number = $row["num"];
if($number>0 && $address2<>'' && $address1<>上海 && $address1<>重庆){
unset($addresss[0]);
}
if($address4==''){
unset($addresss[3]);
}
if($address3==''){
unset($addresss[2]);
}
$query = dbQuery("select count(*) as num from ".weather_station." where station like '$address4' ");//查询 县 字段
$row = dbArray($query);
$number = $row["num"];
if($number==0){
unset($addresss[3]);
}
$query = dbQuery("select count(*) as num from ".weather_station." where station like '$address3' ");//查询 县 字段
$row = dbArray($query);
$number = $row["num"];
if($number==0){
unset($addresss[2]);
}
//数组数据2 查询开始
$queryx = dbQuery("select count(*) as nums from ".weather_station." where station like '$address2' ");//查询 县 字段
$row = dbArray($queryx);
$nums = $row["nums"];
$queryy = dbQuery("select count(*) as numd from ".weather_station." where district like '$address2' ");//查询 市 字段
$row = dbArray($queryy);
$numd = $row["numy"];
if($nums==0 && $numd==0){
unset($addresss[1]); // 如果 数组数据2 不在数据库里则删除数据2
}
//数组数据2 查询结束
$query = dbQuery("select count(*) as num from ".weather_station." where district like '$address2' ");//查询 市 字段
$row = dbArray($query);
$number = $row["num"];
if($number>1 && $address3<>'' && $nums<>0 && $address2<>广州 ){
unset($addresss[1]); // 如果数组数据2在数据库里有 多个 则删除数据2
}
@extract(dbQuery("select count(*) as num_0 from ".weather_station." where district like '$address1' "));//查询 市 字段
@extract(dbQuery("select count(*) as num_1 from ".weather_station." where station like '$address2' "));//查询 县 字段
$number = $num_0;
$numbery = $num_1;
if($number>1 && $numbery>0 && $address2<>''){
unset($addresss[0]); //如果数组数据1在数据库里有 多个 则删除数据1
}
$addresss = implode("",$addresss);
return $addresss; // 结果
}
?>
<?php
// this file is mysql config
$dbhost = 'localhost';
$dbname = '********';
$dbuser = '********';
$dbpass = '******';
$prefix = '';
?>
php 保存远程服务器图片代码
<?php
function getmicrotime(){
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
function SaveHTTPFile($fFileHTTPPath,$fFileSavePath,$fFileSaveName)
{
//记录程序开始的时间
$BeginTime=getmicrotime();
//取得文件名
$fFileSaveName=$fFileSavePath."/".$fFileSaveName;
//取得文件的内容
ob_start();
readfile($fFileHTTPPath);
$img = ob_get_contents();
ob_end_clean();
//$size = strlen($img);
//保存到本地
$fp2=@fopen($fFileSaveName, "a");
fwrite($fp2,$img);
fclose($fp2);
//记录程序运行结束的时间
$EndTime=getmicrotime();
//返回运行时间
return($EndTime-$BeginTime);
}
?>
//这个是后台管理当中的分类列表页
//包含无限分类
include ROOT.'include/tree.class.php';
//声明无限分类
$tree = new tree();
//设置缓存目录
$tree->cDir = ROOT.'cache/class/';
//读入分类缓存
$tree->getCache('class');
//获取缓存
$rootArray = $tree->nodes; //分类信息在写入缓存之前,就已经按照顺序排列好了,不需再次生成分类树,可以拿来直接进行输出
复制代码//只有在修改数据库中的分类表时才需要重新生成分类树
//包含无限分类
include ROOT.'include/tree.class.php';
//声明无限分类
$tree = new tree();
//设置缓存目录
$tree->cDir = ROOT.'cache/class/';
//查询数据库,返回分类的ID,名称,父类3个字段
$db->select('all','class','id,name,parent');
//遍历结果集,并压入无限分类
while ($row = $db->record('all'))
{
$tree->newNode($row['id'],$row['name'],(int)$row['parent']); //父类ID需要为数字
}
//生成分类树,并写入缓存
$tree->putCache('class');
复制代码//另一种更简便的重写缓存方式,该代码是删除分类页中的
//包含无限分类
include ROOT.'include/tree.class.php';
//声明无限分类
$tree = new tree();
//设置缓存目录
$tree->cDir = ROOT.'cache/class/';
//读入分类缓存
$tree->getCache('class');
//是否存在该分类
if (isset($tree->nodes[$id]))
{
//生成查询条件
$condition = 'id='.$id;
//获取该分类的子分类ID
$childsId = $tree->getChildsId($id); //如果存在子分类,改方法返回的是一个一维数组,值分别为各子分类的ID,如果不存在子分类,该方法返回false
//如果存在子分类
if ($childsId)
{
//如果子分类存在,连同子分类一同删除
foreach ($childsId as $childId)
{
$condition .= ' or id='.$childId; //生成删除条件
//卸载无限分类中的条目
unset($tree->nodes[$childId]); //直接将分类树中对应ID的分类信息删除
}
}
//开始删除
$db->delete('class',$condition);
//删除该分类在无限分类中条目
unset($tree->nodes[$id]);
//重写无限分类缓存
$tree->putCache('class');
//输出删除成功标记
exit('OK');
} else {
//不存在则输出错误消息
exit('该分类不存在!');
}
复制代码
php经典文件上传类
#*********************************************************
#文件名称:
inc_class.upload.php
#功能描述: 上传文件类
#程序制作:青春一度(adleyliu)
#联系qq
:14339095
2.0.a
#注:转发时请保留此声明信息,这段声明不并会影响你的速度!
#如有修改请将修改后的文件以邮件形式发送给作者一份,谢谢!
#
#*********************************************************
if(!defined('IN_PHPADLEYIU'))
{
exit('Access Denied');
}
/*
//使用说明:
//声明一个上传类
include_once(ADLEYLIU_ROOT.'./inc_class.upload.php');
$_YL_UPLOAD
= array();
$yl_uploadfile = new
yl_upload_class();
$_YL_UPLOAD['yl_filedata'] =
'uploadFile';//表单名
$_YL_UPLOAD['yl_directroy'] =
'upload_files';//上传主目录
$_YL_UPLOAD['file_urldirectroy'] = '/';//
程序路径
$_YL_UPLOAD['yl_settingsnew'] =
''.date('ym').'/'.date('d').'/'.substr(time(), 0,
5).'';//上传子主目录
$_YL_UPLOAD['yl_maxsize'] = 1048576;
//这里以字节为单位(1024*2)*1024=2097152 就是 2M
$_YL_UPLOAD['yl_sizeformat'] =
'k'; //显示文件大小单位b字节,k千,m兆
$_YL_UPLOAD['yl_arrext'] =
array('gif','jpg','jpeg','png','bmp','rar','txt');//允许上传文件类型
$_YL_UPLOAD['yl_ext']
= 0; //0原文件类型上传,1统一为存为jpg
$_YL_UPLOAD['yl_prefix'] =
''.$uid.''.$yl_uploadfile -> yl_createrand(1,0).''.$cid.'';
//在文件名前缀加上特殊字符 //$uid 会员ID $cid 分类ID
$_YL_UPLOAD['yl_suffix'] =
''; //''.$yl_uploadfile -> yl_createrand(3,0).'';
//在文件名后缀加上特殊字符
$_YL_UPLOAD['thumbwidth'] = 100;
//缩略图宽
$_YL_UPLOAD['thumbheight'] = 100;
//缩略图高
$_YL_UPLOAD['maxthumbwidth'] = 500;
//大图高
$_YL_UPLOAD['maxthumbheight'] = 500;
//大图宽
//上传
$yl_uploadfile -> yl_uploadfile();
获取值:
'yl_filename'
=> addslashes($_YL_UPLOAD['yl_filename']),原文件名
'yl_attachment' =>
$_YL_UPLOAD['yl_attachment'],新文件名及路径
'yl_filesize' =>
$_YL_UPLOAD['yl_filesize'] ,文件大小
'yl_filetype' =>
$_YL_UPLOAD['yl_filetype'],文件类型
'yl_isimage' =>
$_YL_UPLOAD['yl_isimage'],是否是图片
'yl_isthumb' =>
$_YL_UPLOAD['yl_isthumb'],是否有小图片
*/
class yl_upload_class
{
function __GET($property_name)
{
if(isset($this -> $property_name))
{
return $this -> $property_name;
} else
{
return
NULL;
}
}
function __SET($property_name,
$value) {
$this -> $property_name =
$value;
}
#*********************************************************
#生成缩略图
#*********************************************************
function makethumb($srcfile) {
global $_YL_UPLOAD;
//判断文件是否存在
if (!file_exists($srcfile))
{
return '';
}
$dstfile =
$srcfile.'.small.jpg';
$bigfile =
$srcfile.'.big.jpg';
//缩略图大小
$tow =
intval($_YL_UPLOAD['thumbwidth']);
$toh =
intval($_YL_UPLOAD['thumbheight']);
if($tow < 60) $tow =
60;
if($toh < 60) $toh = 60;
$make_max = 0;
$maxtow =
intval($_YL_UPLOAD['maxthumbwidth']);
$maxtoh =
intval($_YL_UPLOAD['maxthumbheight']);
if($maxtow >= 300
&& $maxtoh >= 300) {
$make_max =
1;
}
//获取图片信息
$im = '';
if($data =
getimagesize($srcfile)) {
if($data[2] == 1)
{
$make_max =
0;//gif不处理
if(function_exists("imagecreatefromgif"))
{
$im =
imagecreatefromgif($srcfile);
}
}
elseif($data[2] == 2)
{
if(function_exists("imagecreatefromjpeg"))
{
$im =
imagecreatefromjpeg($srcfile);
}
}
elseif($data[2] == 3)
{
if(function_exists("imagecreatefrompng"))
{
$im =
imagecreatefrompng($srcfile);
}
}
}
if(!$im)
return '';
$srcw = imagesx($im);
$srch = imagesy($im);
$towh = $tow/$toh;
$srcwh =
$srcw/$srch;
if($towh <= $srcwh){
$ftow =
$tow;
$ftoh = $ftow*($srch/$srcw);
$fmaxtow = $maxtow;
$fmaxtoh =
$fmaxtow*($srch/$srcw);
} else {
$ftoh =
$toh;
$ftow = $ftoh*($srcw/$srch);
$fmaxtoh = $maxtoh;
$fmaxtow =
$fmaxtoh*($srcw/$srch);
}
if($srcw <= $maxtow
&& $srch <= $maxtoh) {
$make_max =
0;//不处理
}
if($srcw > $tow || $srch > $toh)
{
if(function_exists("imagecreatetruecolor") &&
function_exists("imagecopyresampled") && @$ni =
imagecreatetruecolor($ftow, $ftoh))
{
imagecopyresampled($ni, $im, 0, 0, 0, 0, $ftow,
$ftoh, $srcw,
$srch);
//大图片
if($make_max
&& @$maxni = imagecreatetruecolor($fmaxtow, $fmaxtoh))
{
imagecopyresampled($maxni, $im, 0, 0, 0, 0,
$fmaxtow, $fmaxtoh, $srcw, $srch);
}else if (@$maxni
= imagecreatetruecolor(round($srcw/2),
round($srch/2))){
imagecopyresampled($maxni,
$im, 0, 0, 0, 0, round($srcw/2), round($srch/2), $srcw,
$srch);
}
}
elseif(function_exists("imagecreate") &&
function_exists("imagecopyresized") && @$ni = imagecreate($ftow, $ftoh))
{
imagecopyresized($ni, $im, 0, 0, 0, 0, $ftow,
$ftoh, $srcw,
$srch);
//大图片
if($make_max
&& @$maxni = imagecreate($fmaxtow, $fmaxtoh))
{
imagecopyresized($maxni, $im, 0, 0, 0, 0,
$fmaxtow, $fmaxtoh, $srcw, $srch);
}else if (@$maxni
= imagecreate(round($srcw/2),
round($srch/2))){
imagecopyresized($maxni, $im,
0, 0, 0, 0, round($srcw/2), round($srch/2), $srcw,
$srch);
}
} else
{
return
'';
}
if(function_exists('imagejpeg'))
{
imagejpeg($ni,
$dstfile);
//大图片
if($make_max)
{
imagejpeg($maxni,
$bigfile);
}else{
imagejpeg($maxni,
$bigfile);
}
}
elseif(function_exists('imagepng')) {
imagepng($ni,
$dstfile);
//大图片
if($make_max)
{
imagepng($maxni,
$bigfile);
}else{
imagejpeg($maxni,
$bigfile);
}
}
imagedestroy($ni);
if($make_max)
{
}else{
imagedestroy($maxni);
}
}else{
if(function_exists("imagecreatetruecolor") &&
function_exists("imagecopyresampled") && @$ni =
imagecreatetruecolor($srcw, $srch))
{
imagecopyresampled($ni, $im, 0, 0, 0, 0, $srcw,
$ftoh, $srch,
$srch);
//大图片
$maxni =
imagecreatetruecolor($srch, $srch);
imagecopyresampled($maxni, $im, 0, 0, 0, 0, $srcw, $srch, $srcw,
$srch);
} elseif(function_exists("imagecreate")
&& function_exists("imagecopyresized") && @$ni =
imagecreate($ftow, $ftoh)) {
imagecopyresized($ni,
$im, 0, 0, 0, 0, $srcw, $srch, $srcw,
$srch);
//大图片
$maxni =
imagecreate($fmaxtow, $fmaxtoh);
imagecopyresized($maxni, $im, 0, 0, 0, 0, $srcw, $srch, $srcw,
$srch);
} else
{
return
'';
}
imagejpeg($ni, $dstfile);
imagejpeg($maxni,
$bigfile);
}
imagedestroy($im);
if(!file_exists($dstfile)) {
return
'';
} else {
return
$dstfile;
}
}
#*********************************************************
#获取随机数函数
#*********************************************************
function
yl_createrand($length, $numeric = 0) {
PHP_VERSION < '4.2.0'
&& mt_srand((double)microtime() * 1000000);
if($numeric)
{
$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10,
$length) - 1));
} else {
$hash =
'';
$chars =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';///0123456789
$max
= strlen($chars) - 1;
for($i = 0; $i < $length; $i++)
{
$hash .= $chars[mt_rand(0,
$max)];
}
}
return
$hash;
}
#***************
#*********************************************************
#创建目录函数
#*********************************************************
function
createfolder($yl_path)
{
if
(!file_exists($yl_path))
{
$this ->
createfolder(dirname($yl_path));
@mkdir($yl_path,
0777);
}
return $this ->
createfolder;
}
#*********************************************************
#获取文件
名称,大小,类型,临时文件名
#*********************************************************
function
yl_getfilename($yl_type)
{
global
$_YL_UPLOAD;
return
$_FILES[$_YL_UPLOAD['yl_filedata']][$yl_type];
}
#*********************************************************
#获取文件大小
#*********************************************************
function
yl_getfilesize()
{
global
$_YL_UPLOAD;
$yl_filesize = $this ->
yl_getfilename('size');
if($yl_filesize ==
0){
$this ->
alert("请选择上传文件!");
exit;
}
if($yl_filesize
> $_YL_UPLOAD['yl_maxsize']){
switch
(strtolower($_YL_UPLOAD['yl_sizeformat'])){
case
'b':
$yl_maxsizek = $_YL_UPLOAD['yl_maxsize'] .
' B';
break;
case
'k':
$yl_maxsizek =
$_YL_UPLOAD['yl_maxsize']/1024 . '
K';
break;
case
'm':
$yl_maxsizek =
$_YL_UPLOAD['yl_maxsize']/(1024*1024) . '
M';
}
$this ->
alert("上传文件超出限制范围[".$yl_maxsizek."].K!");
exit;
}
return
$yl_filesize;
}
#*********************************************************
#获得文件扩展名
#*********************************************************
function
yl_getfiletype()
{
global
$_YL_UPLOAD;
$pathinfo = pathinfo($this ->
yl_getfilename('name'));
$yl_file_ext =
strtolower($pathinfo['extension']);
//检查扩展名
if(!array_keys($_YL_UPLOAD['yl_arrext'],$yl_file_ext))
{
$this ->
alert("上传文件类型被限制!");
exit;
}
return
$yl_file_ext;
}
#*********************************************************
#上传验证
#*********************************************************
function
yl_upfile($source, $target) {
//
如果一种函数上传失败,还可以用其他函数上传
if (function_exists('move_uploaded_file')
&& @move_uploaded_file($source, $target))
{
@chmod($target, 0666);
return
$target;
} elseif (@copy($source, $target))
{
@chmod($target, 0666);
return
$target;
} elseif (@is_readable($source))
{
if ($fp = @fopen($source,'rb'))
{
@flock($fp,2);
$filedata
=
@fread($fp,@filesize($source));
@fclose($fp);
}
if
($fp = @fopen($target, 'wb')) {
@flock($fp,
2);
@fwrite($fp,
$filedata);
@fclose($fp);
@chmod
($target, 0666);
return
$target;
} else {
return
false;
}
}
}
#*********************************************************
#上传
#*********************************************************
function
yl_uploadfile()
{
global
$_YL_UPLOAD;
$yl_file_path =
$_YL_UPLOAD['yl_directroy'].'/'.$_YL_UPLOAD['yl_settingsnew']
;//建立一个目录
$yl_filename = $this ->
yl_getfilename('name');//原文件名
$yl_filenamenews =
$_YL_UPLOAD['yl_prefix'].''.substr(time(), 5,
9).''.$_YL_UPLOAD['yl_suffix'].'';//重命名
$yl_file_size = $this
-> yl_getfilesize();//获取文件大小
$yl_file_type = $this ->
yl_getfiletype();//获取文件类型
if($_YL_UPLOAD['yl_ext'] ==
0){
$yl_filenamenewsext =
$yl_filenamenews.'.'.$yl_file_type;//改名
}elseif
($_YL_UPLOAD['yl_ext'] == 1){
$yl_filenamenewsext =
$yl_filenamenews.'.jpg';//统一改名为jpg
}
//$yl_tmp_name
= str_replace(' ','',$this ->
yl_getfilename('tmp_name'));//服务器上临时文件名
$yl_tmp_name =
$this ->
yl_getfilename('tmp_name');//服务器上临时文件名
//检查是否已上传
if(<A
href="mailto:!@is_uploaded_file($yl_tmp_name">!@is_uploaded_file
($yl_tmp_name))
{
$this ->
alert("文件已上传!");
exit;
}
//检查目录是否存在,不存在则创建
if(<A
href="mailto:!@is_dir(''.$_YL_UPLOAD
['file_urldirectroy'].''.$yl_file_path.''">!@is_dir(''.$_YL_UPLOAD
['file_urldirectroy'].''.$yl_file_path.''))
{
$this ->
createfolder(''.$_YL_UPLOAD['file_urldirectroy'].''.$yl_file_path.'');//创建
目录
}
//检查目录写权限
if
(<A
href="mailto:!@is_writable(''.$_YL_UPLOAD
['file_urldirectroy'].''.$yl_file_path.''">!@is_writable(''.$_YL_UPLOAD
['file_urldirectroy'].''.$yl_file_path.''))
{
$this ->
alert("上传目录没有写权限!");
exit;
}
$yl_path_name
=
''.$_YL_UPLOAD
['file_urldirectroy'].''.$yl_file_path.'/'.$yl_filenamenewsext.'';
$yl_doupload
= $this -> yl_upfile($yl_tmp_name, $yl_path_name);
if($yl_doUpload ===
false)
{
$this ->
alert("上传失败!");
exit;
}else{
//echo
'上传成功';
//echo
'<br>';
/*
echo
'原文件名:'.$yl_filename.'';
echo
'<br>';
echo
'新文件名及目录:'.$yl_file_path.'/'.$yl_filenamenewsext;
echo
'<br>';
echo
'文件大小:'.$yl_file_size.'';
echo
'<br>';
echo
'文件类型:'.$yl_file_type.'';
*/
$_YL_UPLOAD['yl_filename']
= $yl_filename;
$_YL_UPLOAD['yl_attachment'] =
''.$yl_file_path.'/'.$yl_filenamenewsext.'';
$_YL_UPLOAD['yl_filesize']
= $yl_file_size;
$_YL_UPLOAD['yl_filetype'] =
$yl_file_type;
//检查是否图片
if(@getimagesize($yl_path_name))
{
$_YL_UPLOAD['yl_isimage'] =
1;
///生成缩略图
if ($this
->
makethumb($yl_path_name)){
$_YL_UPLOAD['yl_isthumb']
=
1;
}else{
$_YL_UPLOAD['yl_isthumb']
=
0;
}
}else{
$_YL_UPLOAD['yl_isimage']
= 0;
}
}
return
true;
}
#*********************************************************
#提示
#*********************************************************
function
alert($yl_msg)
{
echo
'<html>';
echo '<head>';
echo
'<title>error</title>';
echo '<meta
http-equiv="content-type" content="text/html;
charset=gb2312">';
echo '</head>';
echo
'<body>';
echo '<script
type="text/javascript">alert("'.$yl_msg.'");history.back();</script>';
echo
'</body>';
echo
'</html>';
exit;
}
}