<?= 和<?php 的区别
发布时间:2015-10-14, 11:40:19 | 评论:3 | 分类:PHP
<?=$var?> <?php echo $var; ?>
一种缩写形式,需要short_open_tag,不推荐使用
发布时间:2015-10-14, 11:40:19 | 评论:3 | 分类:PHP
<?=$var?> <?php echo $var; ?>
发布时间:2015-10-14, 14:35:24 | 评论:1 | 分类:PHP
<?php
$the_host = $_SERVER['HTTP_HOST'];//取得当前域名
$the_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';//判断地址后面部分
//$the_url = strtolower($the_url);//将英文字母转成小写
if($the_url=="/index.php")//判断是不是首页
{
$the_url="";//如果是首页,赋值为空
}
if($the_host !== 'www.lizhenqiu.com')//如果域名不是带www的网址那么进行下面的301跳转
{
header('HTTP/1.1 301 Moved Permanently');//发出301头部
header('Location:http://www.lizhenqiu.com'.$the_url);//跳转到带www的网址
//header后的PHP代码还会被执行 .确保重定向后,后续代码不会被执行
exit;
}
发布时间:2015-10-14, 14:36:45 | 评论:0 | 分类:PHP
<?php
include("connection.php");
$perNumber=10; //每页显示的记录数
$page=$_GET['page']; //获得当前的页面值
$count=mysql_query("select count(*) from user"); //获得记录总数
$rs=mysql_fetch_array($count);
$totalNumber=$rs[0];
$totalPage=ceil($totalNumber/$perNumber); //计算出总页数
if (!isset($page)) {
 $page=1;
} //如果没有值,则赋值1
$startCount=($page-1)*$perNumber; //分页开始,根据此方法计算出开始的记录
$result=mysql_query("select * from user limit $startCount,$perNumber"); //根据前面的计算出开始的记录和记录数
while ($row=mysql_fetch_array($result)) {
 echo "user_id:".$row[0]."<br-->";
 echo "username:".$row[1]."<br>"; //显示数据库的内容
}
if ($page != 1) { //页数不等于1
?>
<a href="fenye.php?page=<?php echo $page - 1;?>">上一页</a> <!--显示上一页-->
<?php
}
for ($i=1;$i<=$totalPage;$i++) {  //循环显示出页面
?>
<a href="fenye.php?page=<?php echo $i;?>"><?php echo $i ;?></a>
<?php
}
if ($page<$totalPage) { //如果page小于总页数,显示下一页链接
?>
<a href="fenye.php?page=<?php echo $page + 1;?>">下一页</a>
<?php
}
?>发布时间:2015-10-14, 14:37:33 | 评论:0 | 分类:PHP
function getip(){
if(!empty($_SERVER["HTTP_CLIENT_IP"])){
$cip = $_SERVER["HTTP_CLIENT_IP"];
}
else if(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){
$cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
else if(!empty($_SERVER["REMOTE_ADDR"])){
$cip = $_SERVER["REMOTE_ADDR"];
}
else{
$cip = '';
}
preg_match("/[\d\.]{7,15}/", $cip, $cips);
$cip = isset($cips[0]) ? $cips[0] : 'unknown';
unset($cips);
return $cip;
}发布时间:2015-10-14, 15:12:10 | 评论:0 | 分类:PHP
class test
{ var $b;
function test() { $this->b=5; }
function addab($c) { return $this->b+$c; }
}
$a = new test(); echo $a->addab(4); // 返回 9
class employee{
function __construct()….
}
class Manager extents Employee{
function __construct(){
parent::_construct();
echo ‘这个子类的父类构造函数调用了!';
}
}
class test{
protected $a=9,$b=2,$c;
public $d;
function __set($n,$v) { $this->$n = $v+2; }
function __get($name) { return $this->$name+2; }
}
$a = new test();
$a->b =5; echo “<br />”; echo $a->b;
class test{
private $a=5,$b=6,$c;
function __set($n,$v)
{
if($n=='a'&&$n>0)
$this->$n = $v;
else
$this->$n = $v+2;
}
function __get($name)
{
return $this->$name; //如果改为return $this->$name + $this->addab(); 如调用a的值,实际返回的是a+a+b的值。默认为5+5+6=16。
}
function addab()
{ return $this->a + $this->b; }
}
$e=new test();
$e->a = 11; //注意写法:类的内部用$this->$n即变量的写法,但外部实例要用$e->a的方式。
$e->b = 12; //get 14
$e->k = 22;
class test{
private $a;
const PI = '3.14′;
…..
//在类中调用上面的常量用两种方法,“$this::PI”,或 “类名::PI”,这里就是test::PI,如下:
function getvalue(){
return $this->a * $this::PI; //或$this->a * test::PI,用this关键字或类名均可,但都要用双冒号。
}
}
$e= new test();
$e->PI =5; //注意,这里用 ->只是创造了一个也是名为PI的属性,而不是改变类中的PI常量的值。
echo $e::PI; //这个才是调用类的常量。
class test{
public static $v = 0;
function __construct(){ self::$v++; }
static function getV(){ return self::$v; }
}
$a = new test();
echo test::getV(); // 返回 1
$b = new test();
echo test::getV(); // 返回 2
test::$v=8; //由于public定义的成员,改变静态成员的值。
$c = new test();
echo test::getV(); // 返回 9
class test{ public $p;
public function __toString(){ return var_export($this,TRUE); }
}
$a=new test();
echo $a; //输出:test::__set_state(array( ‘p' => NULL, )),或写成:echo $a->__toString();
class cB{
function __call($method,$n){
if($method=='showVarType'){
if(is_numeric($n[0])){ //不能用$n。要用$n[0];
$this->displayNum();
}else if (is_array($n[0])){
$this->displayArr();
}else{
$this->displayOther();
}
}
}
function displayNum() {
echo ‘<h3>这是数字!</h3>';
}
function displayArr() {
echo ‘<h3>这是数组!</h3>';
}
function displayOther() {
echo ‘<h3>不是数组也不是数字!</h3>';
}
}
$x='a';
$y=array(‘a','b');
$b=new cB;
$b->showVarType($x); //不是数组也不是数字
$b->showVarType($y); //这是数组
abstract class Employee
{
abstract function a(…);
abstract function b(…);
}
abstract class BaseShop{
Const TAX=0.06; // 在抽象类中定义常量
public function buy($gid) { // 如果定义为抽象方法abstract function buy()就不能在这里实现主体。
echo(‘你购买了ID为 :'.$gid.'的商品');
}
public function sell($gid) {
echo(‘你卖了ID为 :'.$gid.'的商品');
}
public function view($gid) {
echo(‘你查看了ID为 :'.$gid.'的商品');
}
}
class BallShop extends BaseShop{
var $itme_id = null;
public function __construct()
{
$this->itme_id = 2314;
}
public function open()
{
$this->sell($this->itme_id);
}
public function getTax()
{
echo printf(‘<h3>平均税率是 %d%%。</h3>',$this::TAX*100);
}
}
$s = new BallShop;
$s->open(); //你卖了ID为 :2314的商品
$shop->getTax();
class em{ var $k=56; }
class test{
function __construct()
{ echo $this->addab(new em(),2); }
function addab(em $j,$c) //这个方法,即可以在内部调用,也可以在外部调用。只要作用域许可。
{ return $j->k+$c; }
}
$a = new test();
$b = new em();
echo $a->addab($b,2); //或 $a->addab(new em(),2);
class test2{}
class test{}
class testChilern Extends test{}
$a = new test2();
$m = new test();
$i = ($m instanceof test);
if($i)echo ‘$m是类test的实例!<br />'; // get this value
switch ($a instanceof test){
case true :
echo ‘YES<br />';
break;
case false :
echo ‘No<br />'; //get this value
break;
}
$d=new testChilern();
if($d instanceof test)echo ‘$d是类test的子类!<br />'; // get this value
class test{
public $v=2;
private $c=5;
function __construct(){
$this->v=5;
}
private function getv(){
return $this->v;
}
}
class test2 extends test{}
$a=new test();
$b=new test2();
print_r( get_class_methods(‘test')); //或:print_r( get_class_methods($a)); 均返回:Array ( [0] => __construct [1] => getv )
echo ‘<br />';
print_r( get_class_vars(‘test')); //返回:Array ( [v] => 2 ),和上面不一样,不能用print_r( get_class_methods($a));
echo ‘<br />';
echo get_parent_class($b);//或get_parent_class(‘test2′); 返回test
echo ‘<br />';
echo is_a($b,'test');// 返回1
echo ‘<br />';
if(is_subclass_of(‘test2′,'test'))echo ‘是子类!'; //或(is_subclass_of($b,'test')),返回1,当参数1为$a时则返回false,
echo ‘<br />';
echo method_exists($a,'getv') //或用method_exists(‘test','getv')返回1,本函数也适用于用private等定义域的方法。
< ?php
class c{
public $m=7;
}
?>
< ?php
function __autoload($class){
require_once “$class.class.php”;
}
$m = new c(); //创建实例调用的类也是c
echo $m->m;
?>
< ?php
class mm{
public $m=7;
}
?>
< ?php
function __autoload($class){
require_once “$class.class.php”;
}
# __autoload(‘c'); //如果不加这一行就会出错。
$m = new mm();
echo $m->m;
?>
class test
{
public $p=5;
function __clone(){ //只在克隆发生时起作用。用于改变在克隆时某些值
$this->p=15;
}
}
$a=new test();
echo $a->p;
$a->p=8; //如果没有__clone()方法影响,$b的P值将为8
$b = clone $a;
echo $b->p; //15
class cA{
public $name,$age;
function __construct($n) {
$this->name = $n;
$this->age = 25;
}
function __set($n,$v) {
$this->$n = $v;
}
function __get($n) {
return $this->$n;
}
}
class cB extends cA{
function funB1() { echo ‘<h3>Class cB execute success!</h3>'; }
}
class cC extends cB {
function funC1() { echo ‘<h3>Class cC FunC1!</h3>'; }
}
$b=new cB(‘Jack');
$b->name='John';
echo “$b->name : $b->age”;
$b->funB1();
$c=new cC(); //这里会出错,由于cB也没有构造函数,因此再向上以cA为准,需要一个参数。改为$c=new cC(‘David');即可。
echo $c->name(); //David
class cB extends cA{
function __construct() {
echo ‘<h3>this is Class cB \'s __construct!</h3>';
}
function funB1() {
echo ‘<h3>Class cB execute success!</h3>';
}
}
function __construct($n) {
parent::__construct($n); // 或:cA::__construct($n);
echo ‘<h3>this is Class cB \'s __construct!</h3>';
}
function __construct($n) {
cA::__construct($n); //即:类名::构造函数。
cB::__construct();
echo ‘<h3>this is Class cB \'s __construct!</h3>';
}
interface Info{ //定义接口
const N=22;
public function getage();
public function getname();
}
class age implements Info //如要多个接口 class age (extends emJob) implements Info,interB…
{
public $age=15;
public $name='Join';
function getage() {
echo “年级是$this->age”;
}
function getname() {
echo “姓名是$this->name”;
}
function getN(){
echo ‘<h3>在接口中定义的常量N的值是:'.$this::N.' </h3>'; //直接继承接口中的常量值。
}
}
$age=new age;
echo $age::N; //22,直接调用接口中的常量值。
$age->getN();
class a{ …. }
$c = new ReflectionClass(‘a'); //PHP 内置类。
echo ‘<pre>'.$c.'</pre>';发布时间:2015-10-14, 15:18:13 | 评论:0 | 分类:PHP
iconv("UTF-8","GB2312//IGNORE",$data)
<?php
echo $str= '你好,这里是卖咖啡!';
echo '<br />';
echo iconv('GB2312', 'UTF-8', $str); //将字符串的编码从GB2312转到UTF-8
echo '<br />';
echo iconv_substr($str, 1, 1, 'UTF-8'); //按字符个数截取而非字节
print_r(iconv_get_encoding()); //得到当前页面编码信息
echo iconv_strlen($str, 'UTF-8'); //得到设定编码的字符串长度
//也有这样用的
$content = iconv("UTF-8","gbk//TRANSLIT",$content);
?>
<?php
echo iconv("gb2312","ISO-8859-1","我们");
?>
< ?php
header("content-Type: text/html; charset=Utf-8");
echo mb_convert_encoding("妳係我的友仔", "UTF-8", "GBK");
?>
header("content-Type: text/html; charset=big5");
echo mb_convert_encoding("你是我的朋友", "big5", "GB2312");
?>发布时间:2015-10-14, 15:18:59 | 评论:0 | 分类:PHP
file_put_contents(路径.txt, 内容); //输出
file_get_contents(路径.txt); //导入发布时间:2015-10-14, 15:19:38 | 评论:0 | 分类:PHP
//返回格林威治标准时间
function MyDate($format='Y-m-d H:i:s',$timest=0)
{
global $cfg_cli_time;
$addtime = $cfg_cli_time * 3600;
if(empty($format))
{
$format = 'Y-m-d H:i:s';
}
return gmdate ($format,$timest+$addtime);
}
function GetAlabNum($fnum)
{
$nums = array("0","1","2","3","4","5","6","7","8","9");
//$fnums = "0123456789";
$fnums = array("0","1","2","3","4","5","6","7","8","9");
$fnum = str_replace($nums,$fnums,$fnum);
$fnum = ereg_replace("[^0-9\.-]",'',$fnum);
if($fnum=='')
{
$fnum=0;
}
return $fnum;
}
function Html2Text($str,$r=0)
{
if(!function_exists('SpHtml2Text'))
{
require_once(DEDEINC."/inc/inc_fun_funString.php");
}
if($r==0)
{
return SpHtml2Text($str);
}
else
{
$str = SpHtml2Text(stripslashes($str));
return addslashes($str);
}
}
//文本转HTML
function Text2Html($txt)
{
$txt = str_replace(" "," ",$txt);
$txt = str_replace("<","<",$txt);
$txt = str_replace(">",">",$txt);
$txt = preg_replace("/[\r\n]{1,}/isU","<br/>\r\n",$txt);
return $txt;
}
function AjaxHead()
{
@header("Pragma:no-cache\r\n");
@header("Cache-Control:no-cache\r\n");
@header("Expires:0\r\n");
}
//中文截取2,单字节截取模式
//如果是request的内容,必须使用这个函数
function cn_substrR($str,$slen,$startdd=0)
{
$str = cn_substr(stripslashes($str),$slen,$startdd);
return addslashes($str);
}
//中文截取2,单字节截取模式
function cn_substr($str,$slen,$startdd=0)
{
global $cfg_soft_lang;
if($cfg_soft_lang=='utf-8')
{
return cn_substr_utf8($str,$slen,$startdd);
}
$restr = '';
$c = '';
$str_len = strlen($str);
if($str_len < $startdd+1)
{
return '';
}
if($str_len < $startdd + $slen || $slen==0)
{
$slen = $str_len - $startdd;
}
$enddd = $startdd + $slen - 1;
for($i=0;$i<$str_len;$i++)
{
if($startdd==0)
{
$restr .= $c;
}
else if($i > $startdd)
{
$restr .= $c;
}
if(ord($str[$i])>0x80)
{
if($str_len>$i+1)
{
$c = $str[$i].$str[$i+1];
}
$i++;
}
else
{
$c = $str[$i];
}
if($i >= $enddd)
{
if(strlen($restr)+strlen($c)>$slen)
{
break;
}
else
{
$restr .= $c;
break;
}
}
}
return $restr;
}
//utf-8中文截取,单字节截取模式
function cn_substr_utf8($str, $length, $start=0)
{
if(strlen($str) < $start+1)
{
return '';
}
preg_match_all("/./su", $str, $ar);
$str = '';
$tstr = '';
//为了兼容mysql4.1以下版本,与数据库varchar一致,这里使用按字节截取
for($i=0; isset($ar[0][$i]); $i++)
{
if(strlen($tstr) < $start)
{
$tstr .= $ar[0][$i];
}
else
{
if(strlen($str) < $length + strlen($ar[0][$i]) )
{
$str .= $ar[0][$i];
}
else
{
break;
}
}
}
return $str;
}
function GetMkTime($dtime)
{
global $cfg_cli_time;
if(!ereg("[^0-9]",$dtime))
{
return $dtime;
}
$dtime = trim($dtime);
$dt = Array(1970,1,1,0,0,0);
$dtime = ereg_replace("[\r\n\t]|日|秒"," ",$dtime);
$dtime = str_replace("年","-",$dtime);
$dtime = str_replace("月","-",$dtime);
$dtime = str_replace("时",":",$dtime);
$dtime = str_replace("分",":",$dtime);
$dtime = trim(ereg_replace("[ ]{1,}"," ",$dtime));
$ds = explode(" ",$dtime);
$ymd = explode("-",$ds[0]);
if(!isset($ymd[1]))
{
$ymd = explode(".",$ds[0]);
}
if(isset($ymd[0]))
{
$dt[0] = $ymd[0];
}
if(isset($ymd[1]))
{
$dt[1] = $ymd[1];
}
if(isset($ymd[2]))
{
$dt[2] = $ymd[2];
}
if(strlen($dt[0])==2)
{
$dt[0] = '20'.$dt[0];
}
if(isset($ds[1]))
{
$hms = explode(":",$ds[1]);
if(isset($hms[0]))
{
$dt[3] = $hms[0];
}
if(isset($hms[1]))
{
$dt[4] = $hms[1];
}
if(isset($hms[2]))
{
$dt[5] = $hms[2];
}
}
foreach($dt as $k=>$v)
{
$v = ereg_replace("^0{1,}",'',trim($v));
if($v=='')
{
$dt[$k] = 0;
}
}
$mt = @gmmktime($dt[3],$dt[4],$dt[5],$dt[1],$dt[2],$dt[0]) - 3600 * $cfg_cli_time;
if(!empty($mt))
{
return $mt;
}
else
{
return time();
}
}
function SubDay($ntime,$ctime)
{
$dayst = 3600 * 24;
$cday = ceil(($ntime-$ctime)/$dayst);
return $cday;
}
function AddDay($ntime,$aday)
{
$dayst = 3600 * 24;
$oktime = $ntime + ($aday * $dayst);
return $oktime;
}
function GetDateTimeMk($mktime)
{
return MyDate('Y-m-d H:i:s',$mktime);
}
function GetDateMk($mktime)
{
return MyDate("Y-m-d",$mktime);
}
function GetIP()
{
if(!empty($_SERVER["HTTP_CLIENT_IP"]))
{
$cip = $_SERVER["HTTP_CLIENT_IP"];
}
else if(!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
{
$cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
else if(!empty($_SERVER["REMOTE_ADDR"]))
{
$cip = $_SERVER["REMOTE_ADDR"];
}
else
{
$cip = '';
}
preg_match("/[\d\.]{7,15}/", $cip, $cips);
$cip = isset($cips[0]) ? $cips[0] : 'unknown';
unset($cips);
return $cip;
}
//获取拼音以gbk编码为准
function GetPinyin($str,$ishead=0,$isclose=1)
{
global $cfg_soft_lang;
if(!function_exists('SpGetPinyin'))
{
require_once(DEDEINC."/inc/inc_fun_funAdmin.php");
}
if($cfg_soft_lang=='utf-8')
{
return SpGetPinyin(utf82gb($str),$ishead,$isclose);
}
else
{
return SpGetPinyin($str,$ishead,$isclose);
}
}
function GetNewInfo()
{
if(!function_exists('SpGetNewInfo'))
{
require_once(DEDEINC."/inc/inc_fun_funAdmin.php");
}
return SpGetNewInfo();
}
function UpdateStat()
{
include_once(DEDEINC."/inc/inc_stat.php");
return SpUpdateStat();
}
$arrs1 = array(0x63,0x66,0x67,0x5f,0x70,0x6f,0x77,0x65,0x72,0x62,0x79);
$arrs2 = array(0x20,0x3c,0x61,0x20,0x68,0x72,0x65,0x66,0x3d,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,
0x77,0x77,0x77,0x2e,0x64,0x65,0x64,0x65,0x63,0x6d,0x73,0x2e,0x63,0x6f,0x6d,0x20,0x74,0x61,0x72,
0x67,0x65,0x74,0x3d,0x27,0x5f,0x62,0x6c,0x61,0x6e,0x6b,0x27,0x3e,0x50,0x6f,0x77,0x65,0x72,0x20,
0x62,0x79,0x20,0x44,0x65,0x64,0x65,0x43,0x6d,0x73,0x3c,0x2f,0x61,0x3e);
function ShowMsg($msg,$gourl,$onlymsg=0,$limittime=0)
{
if(empty($GLOBALS['cfg_phpurl'])) $GLOBALS['cfg_phpurl'] = '..';
$htmlhead = "<html>\r\n<head>\r\n<title>SIOGONCMS提示信息</title>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\" />\r\n";
$htmlhead .= "<base target='_self'/>\r\n<style>div{line-height:160%;}</style></head>\r\n<body leftmargin='0' topmargin='0'>".(isset($GLOBALS['ucsynlogin']) ? $GLOBALS['ucsynlogin'] : '')."\r\n<center>\r\n<script>\r\n";
$htmlfoot = "</script>\r\n</center>\r\n</body>\r\n</html>\r\n";
$litime = ($limittime==0 ? 1000 : $limittime);
$func = '';
if($gourl=='-1')
{
if($limittime==0) $litime = 5000;
$gourl = "javascript:history.go(-1);";
}
if($gourl=='' || $onlymsg==1)
{
$msg = "<script>alert(\"".str_replace("\"","“",$msg)."\");</script>";
}
else
{
//当网址为:close::objname 时, 关闭父框架的id=objname元素
if(eregi('close::',$gourl))
{
$tgobj = trim(eregi_replace('close::', '', $gourl));
$gourl = 'javascript:;';
$func .= "window.parent.document.getElementById('{$tgobj}').style.display='none';\r\n";
}
$func .= " var pgo=0;
function JumpUrl(){
if(pgo==0){ location='$gourl'; pgo=1; }
}\r\n";
$rmsg = $func;
$rmsg .= "document.write(\"<br /><div style='width:450px;padding:100px 0px 0px 0px;background: url({$GLOBALS['cfg_phpurl']}/img/wbg.png) no-repeat'>";
$rmsg .= "<div style='padding:6px;font-size:12px;'><b>SIOGONCMS 提示信息!</b></div>\");\r\n";
$rmsg .= "document.write(\"<div style='height:130px;font-size:10pt;border-top:0px;border-left:1px solid #B3C800;border-right:1px solid #B3C800;border-bottom:1px solid #B3C800;'><br />\");\r\n";
$rmsg .= "document.write(\"".str_replace("\"","“",$msg)."\");\r\n";
$rmsg .= "document.write(\"";
if($onlymsg==0)
{
if( $gourl != 'javascript:;' && $gourl != '')
{
$rmsg .= "<br /><a href='{$gourl}'>如果你的浏览器没反应,请点击这里...</a>";
$rmsg .= "<br/></div>\");\r\n";
$rmsg .= "setTimeout('JumpUrl()',$litime);";
}
else
{
$rmsg .= "<br/></div>\");\r\n";
}
}
else
{
$rmsg .= "<br/><br/></div>\");\r\n";
}
$msg = $htmlhead.$rmsg.$htmlfoot;
}
echo $msg;
}
function ExecTime()
{
$time = explode(" ", microtime());
$usec = (double)$time[0];
$sec = (double)$time[1];
return $sec + $usec;
}
function GetEditor($fname,$fvalue,$nheight="350",$etype="Basic",$gtype="print",$isfullpage="false")
{
if(!function_exists('SpGetEditor'))
{
require_once(DEDEINC."/inc/inc_fun_funAdmin.php");
}
return SpGetEditor($fname,$fvalue,$nheight,$etype,$gtype,$isfullpage);
}
function GetTemplets($filename)
{
if(file_exists($filename))
{
$fp = fopen($filename,"r");
$rstr = fread($fp,filesize($filename));
fclose($fp);
return $rstr;
}
else
{
return '';
}
}
function GetSysTemplets($filename)
{
return GetTemplets($GLOBALS['cfg_basedir'].$GLOBALS['cfg_templets_dir'].'/system/'.$filename);
}
function AttDef($oldvar,$nv)
{
return empty($oldvar) ? $nv : $oldvar;
}
function dd2char($ddnum)
{
$ddnum = strval($ddnum);
$slen = strlen($ddnum);
$okdd = '';
$nn = '';
for($i=0;$i<$slen;$i++)
{
if(isset($ddnum[$i+1]))
{
$n = $ddnum[$i].$ddnum[$i+1];
if( ($n>96 && $n<123) || ($n>64 && $n<91) )
{
$okdd .= chr($n);
$i++;
}
else
{
$okdd .= $ddnum[$i];
}
}
else
{
$okdd .= $ddnum[$i];
}
}
return $okdd;
}
function PutCookie($key,$value,$kptime=0,$pa="/")
{
global $cfg_cookie_encode;
setcookie($key,$value,time()+$kptime,$pa);
setcookie($key.'__ckMd5',substr(md5($cfg_cookie_encode.$value),0,16),time()+$kptime,$pa);
}
function DropCookie($key)
{
setcookie($key,'',time()-360000,"/");
setcookie($key.'__ckMd5','',time()-360000,"/");
}
function GetCookie($key)
{
global $cfg_cookie_encode;
if( !isset($_COOKIE[$key]) || !isset($_COOKIE[$key.'__ckMd5']) )
{
return '';
}
else
{
if($_COOKIE[$key.'__ckMd5']!=substr(md5($cfg_cookie_encode.$_COOKIE[$key]),0,16))
{
return '';
}
else
{
return $_COOKIE[$key];
}
}
}
function GetCkVdValue()
{
@session_start();
return isset($_SESSION['dd_ckstr']) ? $_SESSION['dd_ckstr'] : '';
}
//php某些版本有Bug,不能在同一作用域中同时读session并改注销它,因此调用后需执行本函数
function ResetVdValue()
{
@session_start();
$_SESSION['dd_ckstr'] = '';
$_SESSION['dd_ckstr_last'] = '';
}
function FtpMkdir($truepath,$mmode,$isMkdir=true)
{
global $cfg_basedir,$cfg_ftp_root,$g_ftpLink;
OpenFtp();
$ftproot = ereg_replace($cfg_ftp_root.'$','',$cfg_basedir);
$mdir = ereg_replace('^'.$ftproot,'',$truepath);
if($isMkdir)
{
ftp_mkdir($g_ftpLink,$mdir);
}
return ftp_site($g_ftpLink,"chmod $mmode $mdir");
}
function FtpChmod($truepath,$mmode)
{
return FtpMkdir($truepath,$mmode,false);
}
function OpenFtp()
{
global $cfg_basedir,$cfg_ftp_host,$cfg_ftp_port, $cfg_ftp_user,$cfg_ftp_pwd,$cfg_ftp_root,$g_ftpLink;
if(!$g_ftpLink)
{
if($cfg_ftp_host=='')
{
echo "由于你的站点的PHP配置存在限制,程序尝试用FTP进行目录操作,你必须在后台指定FTP相关的变量!";
exit();
}
$g_ftpLink = ftp_connect($cfg_ftp_host,$cfg_ftp_port);
if(!$g_ftpLink)
{
echo "连接FTP失败!";
exit();
}
if(!ftp_login($g_ftpLink,$cfg_ftp_user,$cfg_ftp_pwd))
{
echo "登陆FTP失败!";
exit();
}
}
}
function CloseFtp()
{
global $g_ftpLink;
if($g_ftpLink)
{
@ftp_quit($g_ftpLink);
}
}
function MkdirAll($truepath,$mmode)
{
global $cfg_ftp_mkdir,$isSafeMode,$cfg_dir_purview;
if($isSafeMode||$cfg_ftp_mkdir=='Y')
{
return FtpMkdir($truepath,$mmode);
}
else
{
if(!file_exists($truepath))
{
mkdir($truepath,$cfg_dir_purview);
chmod($truepath,$cfg_dir_purview);
return true;
}
else
{
return true;
}
}
}
function ParCv($n)
{
return chr($n);
}
function ChmodAll($truepath,$mmode)
{
global $cfg_ftp_mkdir,$isSafeMode;
if($isSafeMode||$cfg_ftp_mkdir=='Y')
{
return FtpChmod($truepath,$mmode);
}
else
{
return chmod($truepath,'0'.$mmode);
}
}
function CreateDir($spath)
{
if(!function_exists('SpCreateDir'))
{
require_once(DEDEINC.'/inc/inc_fun_funAdmin.php');
}
return SpCreateDir($spath);
}
// $rptype = 0 表示仅替换 html标记
// $rptype = 1 表示替换 html标记同时去除连续空白字符
// $rptype = 2 表示替换 html标记同时去除所有空白字符
// $rptype = -1 表示仅替换 html危险的标记
function HtmlReplace($str,$rptype=0)
{
$str = stripslashes($str);
if($rptype==0)
{
$str = htmlspecialchars($str);
}
else if($rptype==1)
{
$str = htmlspecialchars($str);
$str = str_replace(" ",' ',$str);
$str = ereg_replace("[\r\n\t ]{1,}",' ',$str);
}
else if($rptype==2)
{
$str = htmlspecialchars($str);
$str = str_replace(" ",'',$str);
$str = ereg_replace("[\r\n\t ]",'',$str);
}
else
{
$str = ereg_replace("[\r\n\t ]{1,}",' ',$str);
$str = eregi_replace('script','script',$str);
$str = eregi_replace("<[/]{0,1}(link|meta|ifr|fra)[^>]*>",'',$str);
}
return addslashes($str);
}
//获得某文档的所有tag
function GetTags($aid)
{
global $dsql;
$tags = '';
$query = "Select tag From `#@__taglist` where aid='$aid' ";
$dsql->Execute('tag',$query);
while($row = $dsql->GetArray('tag'))
{
$tags .= ($tags=='' ? $row['tag'] : ','.$row['tag']);
}
return $tags;
}
function ParamError()
{
ShowMsg('对不起,你输入的参数有误!','javascript:;');
exit();
}
//过滤用于搜索的字符串
function FilterSearch($keyword)
{
global $cfg_soft_lang;
if($cfg_soft_lang=='utf-8')
{
$keyword = ereg_replace("[\"\r\n\t\$\\><']",'',$keyword);
if($keyword != stripslashes($keyword))
{
return '';
}
else
{
return $keyword;
}
}
else
{
$restr = '';
for($i=0;isset($keyword[$i]);$i++)
{
if(ord($keyword[$i]) > 0x80)
{
if(isset($keyword[$i+1]) && ord($keyword[$i+1]) > 0x40)
{
$restr .= $keyword[$i].$keyword[$i+1];
$i++;
}
else
{
$restr .= ' ';
}
}
else
{
if(eregi("[^0-9a-z@#\.]",$keyword[$i]))
{
$restr .= ' ';
}
else
{
$restr .= $keyword[$i];
}
}
}
}
return $restr;
}
//处理禁用HTML但允许换行的内容
function TrimMsg($msg)
{
$msg = trim(stripslashes($msg));
$msg = nl2br(htmlspecialchars($msg));
$msg = str_replace(" "," ",$msg);
return addslashes($msg);
}
//获取单篇文档信息
function GetOneArchive($aid)
{
global $dsql;
include_once(DEDEINC."/channelunit.func.php");
$aid = trim(ereg_replace('[^0-9]','',$aid));
$reArr = array();
$chRow = $dsql->GetOne("Select arc.*,ch.maintable,ch.addtable,ch.issystem From `#@__arctiny` arc left join `#@__channeltype` ch on ch.id=arc.channel where arc.id='$aid' ");
if(!is_array($chRow)) {
return $reArr;
}
else {
if(empty($chRow['maintable'])) $chRow['maintable'] = '#@__archives';
}
if($chRow['issystem']!=-1)
{
$nquery = " Select arc.*,tp.typedir,tp.topid,tp.namerule,tp.moresite,tp.siteurl,tp.sitepath
From `{$chRow['maintable']}` arc left join `#@__arctype` tp on tp.id=arc.typeid
where arc.id='$aid' ";
}
else
{
$nquery = " Select arc.*,1 as ismake,0 as money,'' as filename,tp.typedir,tp.topid,tp.namerule,tp.moresite,tp.siteurl,tp.sitepath
From `{$chRow['addtable']}` arc left join `#@__arctype` tp on tp.id=arc.typeid
where arc.aid='$aid' ";
}
$arcRow = $dsql->GetOne($nquery);
if(!is_array($arcRow)) {
return $reArr;
}
if(!isset($arcRow['description'])) {
$arcRow['description'] = '';
}
if(empty($arcRow['description']) && isset($arcRow['body'])) {
$arcRow['description'] = cn_substr(html2text($arcRow['body']),250);
}
if(!isset($arcRow['pubdate'])) {
$arcRow['pubdate'] = $arcRow['senddate'];
}
if(!isset($arcRow['notpost'])) {
$arcRow['notpost'] = 0;
}
$reArr = $arcRow;
$reArr['aid'] = $aid;
$reArr['topid'] = $arcRow['topid'];
$reArr['arctitle'] = $arcRow['title'];
$reArr['arcurl'] = GetFileUrl($aid,$arcRow['typeid'],$arcRow['senddate'],$reArr['title'],$arcRow['ismake'],$arcRow['arcrank'],$arcRow['namerule'],
$arcRow['typedir'],$arcRow['money'],$arcRow['filename'],$arcRow['moresite'],$arcRow['siteurl'],$arcRow['sitepath']);
return $reArr;
}
//获取模型的表信息
function GetChannelTable($id,$formtype='channel')
{
global $dsql;
if($formtype == 'archive')
{
$query = "select ch.maintable, ch.addtable from #@__arctiny tin left join #@__channeltype ch on ch.id=tin.channel where tin.id='$id'";
}
elseif($formtype == 'typeid')
{
$query = "select ch.maintable, ch.addtable from #@__arctype act left join #@__channeltype ch on ch.id=act.channeltype where act.id='$id'";
}
else
{
$query = "select maintable, addtable from #@__channeltype where id='$id'";
}
$row = $dsql->getone($query);
return $row;
}
function jstrim($str,$len)
{
$str = preg_replace("/{quote}(.*){\/quote}/is",'',$str);
$str = str_replace('<br/>',' ',$str);
$str = cn_substr($str,$len);
$str = ereg_replace("['\"\r\n]","",$str);
return $str;
}
function jstrimjajx($str,$len)
{
$str = preg_replace("/{quote}(.*){\/quote}/is",'',$str);
$str = str_replace('<br/>',' ',$str);
$str = cn_substr($str,$len);
$str = ereg_replace("['\"\r\n]","",$str);
$str = str_replace('<', '<', $str);
$str = str_replace('>', '>', $str);
return $str;
}
/*-------------------------------
//管理员上传文件的通用函数
//filetype: image、media、addon
//return: -1 没选定上传文件,0 文件类型不允许, -2 保存失败,其它:返回上传后的文件名
//$file_type='' 对于swfupload上传的文件, 因为没有filetype,所以需指定,并且有些特殊之处不同
-------------------------------*/
function AdminUpload($uploadname, $ftype='image', $rnddd=0, $watermark=true, $filetype='' )
{
global $dsql, $cuserLogin, $cfg_addon_savetype, $cfg_dir_purview;
global $cfg_basedir, $cfg_image_dir, $cfg_soft_dir, $cfg_other_medias;
global $cfg_imgtype, $cfg_softtype, $cfg_mediatype;
if($watermark) include_once(DEDEINC.'/image.func.php');
$file_tmp = isset($GLOBALS[$uploadname]) ? $GLOBALS[$uploadname] : '';
if($file_tmp=='' || !is_uploaded_file($file_tmp) )
{
return -1;
}
$file_tmp = $GLOBALS[$uploadname];
$file_size = filesize($file_tmp);
$file_type = $filetype=='' ? strtolower(trim($GLOBALS[$uploadname.'_type'])) : $filetype;
$file_name = isset($GLOBALS[$uploadname.'_name']) ? $GLOBALS[$uploadname.'_name'] : '';
$file_snames = explode('.', $file_name);
$file_sname = strtolower(trim($file_snames[count($file_snames)-1]));
if($ftype=='image' || $ftype=='imagelit')
{
$filetype = '1';
$sparr = Array('image/pjpeg', 'image/jpeg', 'image/gif', 'image/png', 'image/xpng', 'image/wbmp');
if(!in_array($file_type, $sparr)) return 0;
if($file_sname=='')
{
if($file_type=='image/gif') $file_sname = 'jpg';
else if($file_type=='image/png' || $file_type=='image/xpng') $file_sname = 'png';
else if($file_type=='image/wbmp') $file_sname = 'bmp';
else $file_sname = 'jpg';
}
$filedir = $cfg_image_dir.'/'.MyDate($cfg_addon_savetype, time());
}
else if($ftype=='media')
{
$filetype = '3';
if( !eregi($cfg_mediatype, $file_sname) ) return 0;
$filedir = $cfg_other_medias.'/'.MyDate($cfg_addon_savetype, time());
}
else
{
$filetype = '4';
$cfg_softtype .= '|'.$cfg_mediatype.'|'.$cfg_imgtype;
$cfg_softtype = ereg_replace('||', '|', $cfg_softtype);
if( !eregi($cfg_softtype, $file_sname) ) return 0;
$filedir = $cfg_soft_dir.'/'.MyDate($cfg_addon_savetype, time());
}
if(!is_dir(DEDEROOT.$filedir))
{
MkdirAll($cfg_basedir.$filedir, $cfg_dir_purview);
CloseFtp();
}
$filename = $cuserLogin->getUserID().'-'.dd2char(MyDate('ymdHis', time())).$rnddd;
if($ftype=='imagelit') $filename .= '-L';
if( file_exists($cfg_basedir.$filedir.'/'.$filename.'.'.$file_sname) )
{
for($i=50; $i <= 5000; $i++)
{
if( !file_exists($cfg_basedir.$filedir.'/'.$filename.'-'.$i.'.'.$file_sname) )
{
$filename = $filename.'-'.$i;
break;
}
}
}
$fileurl = $filedir.'/'.$filename.'.'.$file_sname;
$rs = move_uploaded_file($file_tmp, $cfg_basedir.$fileurl);
if(!$rs) return -2;
if($ftype=='image' && $watermark)
{
WaterImg($cfg_basedir.$fileurl, 'up');
}
//保存信息到数据库
$title = $filename.'.'.$file_sname;
$inquery = "INSERT INTO `#@__uploads`(title,url,mediatype,width,height,playtime,filesize,uptime,mid)
VALUES ('$title','$fileurl','$filetype','0','0','0','".filesize($cfg_basedir.$fileurl)."','".time()."','".$cuserLogin->getUserID()."'); ";
$dsql->ExecuteNoneQuery($inquery);
$fid = $dsql->GetLastID();
AddMyAddon($fid, $fileurl);
return $fileurl;
}
//邮箱格式检查
function CheckEmail($email)
{
return eregi("^[0-9a-z][a-z0-9\._-]{1,}@[a-z0-9-]{1,}[a-z0-9]\.[a-z\.]{1,}[a-z]$", $email);
}
//前台会员通用上传函数
//$upname 是文件上传框的表单名,而不是表单的变量
//$handname 允许用户手工指定网址情况下的网址
function MemberUploads($upname,$handname,$userid=0,$utype='image',$exname='',$maxwidth=0,$maxheight=0,$water=false,$isadmin=false)
{
global $cfg_imgtype,$cfg_mb_addontype,$cfg_mediatype,$cfg_user_dir,$cfg_basedir,$cfg_dir_purview;
//当为游客投稿的情况下,这个 id 为 0
if( empty($userid) ) $userid = 0;
if(!is_dir($cfg_basedir.$cfg_user_dir."/$userid"))
{
MkdirAll($cfg_basedir.$cfg_user_dir."/$userid", $cfg_dir_purview);
CloseFtp();
}
//有上传文件
$allAllowType = str_replace('||', '|', $cfg_imgtype.'|'.$cfg_mediatype.'|'.$cfg_mb_addontype);
if(!empty($GLOBALS[$upname]) && is_uploaded_file($GLOBALS[$upname]))
{
$nowtme = time();
$GLOBALS[$upname.'_name'] = trim(ereg_replace("[ \r\n\t\*\%\\/\?><\|\":]{1,}",'',$GLOBALS[$upname.'_name']));
//源文件类型检查
if($utype=='image')
{
if(!eregi("\.(".$cfg_imgtype.")$", $GLOBALS[$upname.'_name']))
{
ShowMsg("你所上传的图片类型不在许可列表,请上传{$cfg_imgtype}类型!",'-1');
exit();
}
$sparr = Array("image/pjpeg","image/jpeg","image/gif","image/png","image/xpng","image/wbmp");
$imgfile_type = strtolower(trim($GLOBALS[$upname.'_type']));
if(!in_array($imgfile_type,$sparr))
{
ShowMsg('上传的图片格式错误,请使用JPEG、GIF、PNG、WBMP格式的其中一种!', '-1');
exit();
}
}
else if($utype=='flash' && !eregi("\.swf$", $GLOBALS[$upname.'_name']))
{
ShowMsg('上传的文件必须为flash文件!', '-1');
exit();
}
else if($utype=='media' && !eregi("\.(".$cfg_mediatype.")$",$GLOBALS[$upname.'_name']))
{
ShowMsg('你所上传的文件类型必须为:'.$cfg_mediatype, '-1');
exit();
}
else if(!eregi("\.(".$allAllowType.")$", $GLOBALS[$upname.'_name']))
{
ShowMsg("你所上传的文件类型不被允许!",'-1');
exit();
}
//再次严格检测文件扩展名是否符合系统定义的类型
$fs = explode('.', $GLOBALS[$upname.'_name']);
$sname = $fs[count($fs)-1];
$alltypes = explode('|', $allAllowType);
if(!in_array(strtolower($sname), $alltypes))
{
ShowMsg('你所上传的文件类型不被允许!', '-1');
exit();
}
//强制禁止的文件类型
if(eregi("\.(asp|php|pl|cgi|shtm|js)", $sname))
{
ShowMsg('你上传的文件为系统禁止的类型!', '-1');
exit();
}
if($exname=='')
{
$filename = $cfg_user_dir."/$userid/".dd2char($nowtme.'-'.mt_rand(1000,9999)).'.'.$sname;
}
else
{
$filename = $cfg_user_dir."/{$userid}/{$exname}.".$sname;
}
move_uploaded_file($GLOBALS[$upname], $cfg_basedir.$filename) or die("上传文件到 {$filename} 失败!");
@unlink($GLOBALS[$upname]);
if(@filesize($cfg_basedir.$filename) > $GLOBALS['cfg_mb_upload_size'] * 1024)
{
@unlink($cfg_basedir.$filename);
ShowMsg('你上传的文件超出系统大小限制!', '-1');
exit();
}
//加水印或缩小图片
if($utype=='image')
{
include_once(DEDEINC.'/image.func.php');
if($maxwidth>0 || $maxheight>0)
{
ImageResize($cfg_basedir.$filename, $maxwidth, $maxheight);
}
else if($water)
{
WaterImg($cfg_basedir.$filename);
}
}
return $filename;
}
//没有上传文件
else
{
//强制禁止的文件类型
if($handname=='')
{
return $handname;
}
else if(eregi("\.(asp|php|pl|cgi|shtm|js)", $handname))
{
exit('Not allow filename for not safe!');
}
else if( !eregi("\.(".$allAllowType.")$", $handname) )
{
exit('Not allow filename for filetype!');
}
else if( !eregi('^http:', $handname) && !eregi('^'.$cfg_user_dir.'/'.$userid, $handname) && !$isadmin )
{
exit('Not allow filename for not userdir!');
}
return $handname;
}
}发布时间:2015-10-14, 15:45:54 | 评论:0 | 分类:PHP
问题:
如下面内容,两个问题:
1、用正则取得所有图片地址的php语句怎么写?
2、取出的多个地址如何一条一条地保存到数据库中?
<p><img alt="" width="153" src="/upload/2009-11-15/9_3.jpg" height="60" /><img src="/upload/2009-11-15/58263668.png" alt="" /><img width="153" height="60" alt="" src="/upload/2009-11-15/155439_2.jpg" />1、什么是在线编辑器 2、fckeditor配置 3、fckeditor的应用 4、fckeditor结合数据库应用</p>
<?php
$str ='<p><img alt="" width="153" src="/upload/2009-11-15/9_3.jpg" height="60" /><img src="/upload/2009-11-15/58263668.png" alt="" /><img width="153" height="60" alt="" src="/upload/2009-11-15/155439_2.jpg" />1、什么是在线编辑器 2、fckeditor配置 3、fckeditor的应用 4、fckeditor结合数据库应用</p>';
preg_match_all("/\<img.*?src\=\"(.*?)\"[^>]*>/i", $str, $match);
print_r($match);
<?php
//dump($content);
$str=$content;
$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
preg_match_all($pattern,$str,$match);
//print_r($match ['1']);
$pic_arr_n=count($match['1']);
$pic_arr_n_i=0;
$pattern="/<[img|IMG].*?title=[\'|\"](.*?)[\'|\"].*?[\/]?>/";
//preg_match_all('/<img.+(title=/"?/d*/"?).+>/i',$str,$matchsrc);
preg_match_all($pattern,$str,$matchsrc);
//print_r($matchsrc['1']);
//$pic_arr_n=count($match['1']);
//$pic_arr_n_i=0;
?>
发布时间:2015-10-14, 15:47:29 | 评论:0 | 分类:PHP
/**
* 是否合法的email
* @param string $str
* @return string||false
*/
function is_email($str=''){
return preg_match('/^[\w\d\_\.]+\@[\w\d\_\.\-]+\.[\w\d]{2,4}$/',str_replace('%40','@',$str));
}
//是否是中文
function is_chinese($str=''){
return preg_match("/^[\x80-\xff]+$/",$str);
}
//是否是手机号码
function is_mobile($str=''){
return preg_match("/^1[34589]\d{9}$/",$str);
}
//是否是QQ号码
function is_qq($str=''){
return preg_match("/^\d{5,15}$/",$str);
}
//是否是正确的用户名 英文数字加下划线,4-16位
function is_uname($str=''){
return chk_string($str);
return preg_match("/^[\w\d\_]{4,20}$/",$str);
}
//是否是正确的密码,不能有空格单引号和双引号,6-20位
function is_pwd($str=''){
return true;
}
//是否合法的日期
function is_date($string){
$arr=explode('-',$string);
return checkdate($arr[1],$arr[2],$arr[0])?true:false;
}
//是否合法的身份证
function is_idcard($idcard=''){
if (strlen($idcard) != 18)return false;
$idcard_base = substr($idcard, 0, 17);
if (strlen($idcard_base) != 17) return false;
$factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
$verify_number_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
$checksum = 0;
for ($i = 0; $i < strlen($idcard_base); $i++) {
$checksum += substr($idcard_base, $i, 1) * $factor[$i];
}
$mod = $checksum % 11;
$verify_number = $verify_number_list[$mod];
if ($verify_number == strtoupper(substr($idcard, 17, 1)))return true;
return false;
}
/**
*检查字符串是否合法,合法则返回真,不合法则返回假,不能含有特殊符号
*@param string $str
*@return bool
*/
function chk_string($str=''){
return $str?preg_match('/^[a-zA-Z0-9\x80-\xff\_\@\.]+?$/',$str):false;
}
发布时间:2015-10-14, 16:40:51 | 评论:0 | 分类:PHP
<?php
require_once ('email.class.php');
//##########################################
$smtpserver = "smtp.163.com";//SMTP服务器
$smtpserverport =25;//SMTP服务器端口
$smtpusermail = "xxx@163.com";//SMTP服务器的用户邮箱
$smtpemailto = "xxx@qq.com";//发送给谁
$smtpuser = "xxx@looklo.com";//SMTP服务器的用户帐号
$smtppass = "*****";//SMTP服务器的用户密码
$mailsubject = "PHP100测试邮件系统";//邮件主题
$mailbody = "<h1> 这是一个测试程序 PHP100.com </h1>";//邮件内容
$mailtype = "HTML";//邮件格式(HTML/TXT),TXT为文本邮件
##########################################
$smtp = new smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
$smtp->debug = true;//是否显示发送的调试信息
$smtp->sendmail($smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype);
?>
[/php]
email.class.php
[php]
<?
class smtp
{
/* Public Variables */
public $smtp_port;
public $time_out;
public $host_name;
public $log_file;
public $relay_host;
public $debug;
public $auth;
public $user;
public $pass;
/* Private Variables */
private $sock;
/* Constractor */
function smtp($relay_host = "", $smtp_port = 25,$auth = false,$user,$pass)
{
$this->debug = FALSE;
$this->smtp_port = $smtp_port;
$this->relay_host = $relay_host;
$this->time_out = 30; //is used in fsockopen()
#
$this->auth = $auth;//auth
$this->user = $user;
$this->pass = $pass;
#
$this->host_name = "localhost"; //is used in HELO command
$this->log_file ="";
$this->sock = FALSE;
}
/* Main Function */
function sendmail($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "")
{
$mail_from = $this->get_address($this->strip_comment($from));
$body = preg_replace("/(^|(\r\n))(\\.)/", "\\1.\\3", $body);
$header .= "MIME-Version:1.0\r\n";
if($mailtype=="HTML"){
$header .= "Content-Type:text/html\r\n";
}
$header .= "To: ".$to."\r\n";
if ($cc != "") {
$header .= "Cc: ".$cc."\r\n";
}
$header .= "From: $from<".$from.">\r\n";
$header .= "Subject: ".$subject."\r\n";
$header .= $additional_headers;
$header .= "Date: ".date("r")."\r\n";
$header .= "X-Mailer:By Redhat (PHP/".phpversion().")\r\n";
list($msec, $sec) = explode(" ", microtime());
$header .= "Message-ID: <".date("YmdHis", $sec).".".($msec*1000000).".".$mail_from.">\r\n";
$TO = explode(",", $this->strip_comment($to));
if ($cc != "") {
$TO = array_merge($TO, explode(",", $this->strip_comment($cc)));
}
if ($bcc != "") {
$TO = array_merge($TO, explode(",", $this->strip_comment($bcc)));
}
$sent = TRUE;
foreach ($TO as $rcpt_to) {
$rcpt_to = $this->get_address($rcpt_to);
if (!$this->smtp_sockopen($rcpt_to)) {
$this->log_write("Error: Cannot send email to ".$rcpt_to."\n");
$sent = FALSE;
continue;
}
if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $header, $body)) {
$this->log_write("E-mail has been sent to <".$rcpt_to.">\n");
} else {
$this->log_write("Error: Cannot send email to <".$rcpt_to.">\n");
$sent = FALSE;
}
fclose($this->sock);
$this->log_write("Disconnected from remote host\n");
}
echo "<br>";
echo $header;
return $sent;
}
/* Private Functions */
function smtp_send($helo, $from, $to, $header, $body = "")
{
if (!$this->smtp_putcmd("HELO", $helo)) {
return $this->smtp_error("sending HELO command");
}
#auth
if($this->auth){
if (!$this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user))) {
return $this->smtp_error("sending HELO command");
}
if (!$this->smtp_putcmd("", base64_encode($this->pass))) {
return $this->smtp_error("sending HELO command");
}
}
#
if (!$this->smtp_putcmd("MAIL", "FROM:<".$from.">")) {
return $this->smtp_error("sending MAIL FROM command");
}
if (!$this->smtp_putcmd("RCPT", "TO:<".$to.">")) {
return $this->smtp_error("sending RCPT TO command");
}
if (!$this->smtp_putcmd("DATA")) {
return $this->smtp_error("sending DATA command");
}
if (!$this->smtp_message($header, $body)) {
return $this->smtp_error("sending message");
}
if (!$this->smtp_eom()) {
return $this->smtp_error("sending <CR><LF>.<CR><LF> [EOM]");
}
if (!$this->smtp_putcmd("QUIT")) {
return $this->smtp_error("sending QUIT command");
}
return TRUE;
}
function smtp_sockopen($address)
{
if ($this->relay_host == "") {
return $this->smtp_sockopen_mx($address);
} else {
return $this->smtp_sockopen_relay();
}
}
function smtp_sockopen_relay()
{
$this->log_write("Trying to ".$this->relay_host.":".$this->smtp_port."\n");
$this->sock = @fsockopen($this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out);
if (!($this->sock && $this->smtp_ok())) {
$this->log_write("Error: Cannot connenct to relay host ".$this->relay_host."\n");
$this->log_write("Error: ".$errstr." (".$errno.")\n");
return FALSE;
}
$this->log_write("Connected to relay host ".$this->relay_host."\n");
return TRUE;;
}
function smtp_sockopen_mx($address)
{
$domain = preg_replace("/^.+@([^@]+)$/", "\\1", $address);
if (!@getmxrr($domain, $MXHOSTS)) {
$this->log_write("Error: Cannot resolve MX \"".$domain."\"\n");
return FALSE;
}
foreach ($MXHOSTS as $host) {
$this->log_write("Trying to ".$host.":".$this->smtp_port."\n");
$this->sock = @fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out);
if (!($this->sock && $this->smtp_ok())) {
$this->log_write("Warning: Cannot connect to mx host ".$host."\n");
$this->log_write("Error: ".$errstr." (".$errno.")\n");
continue;
}
$this->log_write("Connected to mx host ".$host."\n");
return TRUE;
}
$this->log_write("Error: Cannot connect to any mx hosts (".implode(", ", $MXHOSTS).")\n");
return FALSE;
}
function smtp_message($header, $body)
{
fputs($this->sock, $header."\r\n".$body);
$this->smtp_debug("> ".str_replace("\r\n", "\n"."> ", $header."\n> ".$body."\n> "));
return TRUE;
}
function smtp_eom()
{
fputs($this->sock, "\r\n.\r\n");
$this->smtp_debug(". [EOM]\n");
return $this->smtp_ok();
}
function smtp_ok()
{
$response = str_replace("\r\n", "", fgets($this->sock, 512));
$this->smtp_debug($response."\n");
if (!preg_match("/^[23]/", $response)) {
fputs($this->sock, "QUIT\r\n");
fgets($this->sock, 512);
$this->log_write("Error: Remote host returned \"".$response."\"\n");
return FALSE;
}
return TRUE;
}
function smtp_putcmd($cmd, $arg = "")
{
if ($arg != "") {
if($cmd=="") $cmd = $arg;
else $cmd = $cmd." ".$arg;
}
fputs($this->sock, $cmd."\r\n");
$this->smtp_debug("> ".$cmd."\n");
return $this->smtp_ok();
}
function smtp_error($string)
{
$this->log_write("Error: Error occurred while ".$string.".\n");
return FALSE;
}
function log_write($message)
{
$this->smtp_debug($message);
if ($this->log_file == "") {
return TRUE;
}
$message = date("M d H:i:s ").get_current_user()."[".getmypid()."]: ".$message;
if (!@file_exists($this->log_file) || !($fp = @fopen($this->log_file, "a"))) {
$this->smtp_debug("Warning: Cannot open log file \"".$this->log_file."\"\n");
return FALSE;
}
flock($fp, LOCK_EX);
fputs($fp, $message);
fclose($fp);
return TRUE;
}
function strip_comment($address)
{
$comment = "/\\([^()]*\\)/";
while (preg_match($comment, $address)) {
$address = preg_replace($comment, "", $address);
}
return $address;
}
function get_address($address)
{
$address = preg_replace("/([ \t\r\n])+/", "", $address);
$address = preg_replace("/^.*<(.+)>.*$/", "\\1", $address);
return $address;
}
function smtp_debug($message)
{
if ($this->debug) {
echo $message."<br>";
}
}
function get_attach_type($image_tag) { //
$filedata = array();
$img_file_con=fopen($image_tag,"r");
unset($image_data);
while ($tem_buffer=AddSlashes(fread($img_file_con,filesize($image_tag))))
$image_data.=$tem_buffer;
fclose($img_file_con);
$filedata['context'] = $image_data;
$filedata['filename']= basename($image_tag);
$extension=substr($image_tag,strrpos($image_tag,"."),strlen($image_tag)-strrpos($image_tag,"."));
switch($extension){
case ".gif":
$filedata['type'] = "image/gif";
break;
case ".gz":
$filedata['type'] = "application/x-gzip";
break;
case ".htm":
$filedata['type'] = "text/html";
break;
case ".html":
$filedata['type'] = "text/html";
break;
case ".jpg":
$filedata['type'] = "image/jpeg";
break;
case ".tar":
$filedata['type'] = "application/x-tar";
break;
case ".txt":
$filedata['type'] = "text/plain";
break;
case ".zip":
$filedata['type'] = "application/zip";
break;
default:
$filedata['type'] = "application/octet-stream";
break;
}
return $filedata;
}
} // end class
?>
发布时间:2015-10-14, 16:41:46 | 评论:0 | 分类:PHP
<?php
require("class.phpmailer.php"); //下载的文件必须放在该文件所在目录
$mail = new PHPMailer(); //建立邮件发送类
$address ="youbinliu@126.com";
$mail->IsSMTP(); // 使用SMTP方式发送
$mail->Host = "smtp.qq.com"; // 您的企业邮局域名
$mail->SMTPAuth = true; // 启用SMTP验证功能
$mail->Username = "843831601@qq.com"; // 邮局用户名(请填写完整的email地址)
$mail->Password = "***********"; // 邮局密码
$mail->Port=25;
$mail->From = "843831601@qq.com"; //邮件发送者email地址
$mail->FromName = "liuyoubin";
$mail->AddAddress("$address", "a");//收件人地址,可以替换成任何想要接收邮件的email信箱,格式是AddAddress("收件人email","收件人姓名")
//$mail->AddReplyTo("", "");
//$mail->AddAttachment("/var/tmp/file.tar.gz"); // 添加附件
//$mail->IsHTML(true); // set email format to HTML //是否使用HTML格式
$mail->Subject = "PHPMailer测试邮件"; //邮件标题
$mail->Body = "Hello,这是测试邮件"; //邮件内容
$mail->AltBody = "This is the body in plain text for non-HTML mail clients"; //附加信息,可以省略
if(!$mail->Send())
{
echo "邮件发送失败. <p>";
echo "错误原因: " . $mail->ErrorInfo;
exit;
}
echo "邮件发送成功";
/*************************************************
附件:
phpmailer 中文使用说明(简易版)
A开头:
$AltBody--属性
出自:PHPMailer::$AltBody
文件:class.phpmailer.php
说明:该属性的设置是在邮件正文不支持HTML的备用显示
AddAddress--方法
出自:PHPMailer::AddAddress(),文件:class.phpmailer.php
说明:增加收件人。参数1为收件人邮箱,参数2为收件人称呼。例 AddAddress("eb163@eb163.com","eb163"),但参数2可选,AddAddress(eb163@eb163.com)也是可以的。
函数原型:public function AddAddress($address, $name = '') {}
AddAttachment--方法
出自:PHPMailer::AddAttachment()
文件:class.phpmailer.php。
说明:增加附件。
参数:路径,名称,编码,类型。其中,路径为必选,其他为可选
函数原型:
AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream'){}
AddBCC--方法
出自:PHPMailer::AddBCC()
文件:class.phpmailer.php
说明:增加一个密送。抄送和密送的区别请看[SMTP发件中的密送和抄送的区别] 。
参数1为地址,参数2为名称。注意此方法只支持在win32下使用SMTP,不支持mail函数
函数原型:public function AddBCC($address, $name = ''){}
AddCC --方法
出自:PHPMailer::AddCC()
文件:class.phpmailer.php
说明:增加一个抄送。抄送和密送的区别请看[SMTP发件中的密送和抄送的区别] 。
参数1为地址,参数2为名称注意此方法只支持在win32下使用SMTP,不支持mail函数
函数原型:public function AddCC($address, $name = '') {}
AddCustomHeader--方法
出自:PHPMailer::AddCustomHeader()
文件:class.phpmailer.php
说明:增加一个自定义的E-mail头部。
参数为头部信息
函数原型:public function AddCustomHeader($custom_header){}
AddEmbeddedImage --方法
出自:PHPMailer::AddEmbeddedImage()
文件:class.phpmailer.php
说明:增加一个嵌入式图片
参数:路径,返回句柄[,名称,编码,类型]
函数原型:public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {}
提示:AddEmbeddedImage(PICTURE_PATH. "index_01.jpg ", "img_01 ", "index_01.jpg ");
在html中引用
AddReplyTo--方法
出自:PHPMailer:: AddRepl
*************************************************/
?>
$mail->CharSet = "utf-8"; // 这里指定字符集
$mail->Encoding = "base64";
发布时间:2015-10-14, 16:42:53 | 评论:0 | 分类:PHP
<?php
session_start();
if(!$_SESSION['admin']) exit('Error:bannnergly201111251');
//上传类型
$uptypes=array('image/jpg','image/jpeg','image/png','image/pjpeg','image/gif','image/x-png');
$max_file_size=4900000;
$destination_folder=dirname(__FILE__).'/../upload/banner/';
//文件状态判断
$sy=@$_GET['sy'];
$sy_arr=array('1','2','3');
$n=@$_GET['n'];
$n_arr=array('zby','gny','cjy');
if(!in_array($sy, $sy_arr) && !in_array($n, $n_arr)) exit();
$sys=in_array($n, $n_arr)?$n:'sy';
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$file = $_FILES['upfile'];
$filename=$file['tmp_name'];
if (!is_uploaded_file($_FILES['upfile']['tmp_name'])) exit;
if($max_file_size < $file['size']) exit;
if(!in_array($file['type'], $uptypes)) exit;
$destination = $destination_folder.$sys.$sy.".gif";
if(!move_uploaded_file ($filename, $destination)) exit;
//调整上传图片的大小
$destinations = $destination_folder.$sys.'m'.$sy.".gif";
$size=getimagesize($destination);
$width=200;
$height=100;
if($size[2]==1)$im_in=imagecreatefromgif($destination);
if($size[2]==2)$im_in=imagecreatefromjpeg($destination);
if($size[2]==3)$im_in=imagecreatefrompng($destination);
$im_out=imagecreatetruecolor($width,$height);
imagecopyresampled($im_out,$im_in,0,0,0,0,$width,$height,$size[0],$size[1]);
imagejpeg($im_out,$destinations);
chmod($destinations,0744);
imagedestroy($im_in);
imagedestroy($im_out);
//if(!move_uploaded_file ($destination, $destinations)) exit;
}
echo "<script>window.location.href='../admin.php?admin=$sys';</script>";
exit();
发布时间:2015-10-14, 16:48:12 | 评论:0 | 分类:PHP
<?php
echo floor(4.3); // 4
echo floor(9.999); // 9
?> <?php
echo ceil(4.3); // 5
echo ceil(9.999); // 10
?>
<?php
echo round(3.4); // 3
echo round(3.5); // 4
echo round(3.6); // 4
echo round(3.6, 0); // 4
echo round(1.95583, 2); // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2); // 5.05
echo round(5.055, 2); // 5.06
?>
发布时间:2015-10-14, 17:05:10 | 评论:0 | 分类:PHP
<?php
//$title=iconv('utf-8','gbk',WEBNICK);
$Shortcut = "[InternetShortcut]
URL=http://www.12345t.com
IDList=
[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,2";
Header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=岑溪网站开发工作室.url;");
//TITLE等于标题
echo $Shortcut;
?>
lizhenqiu blog is powered by lizhenqiu.com Version 6.9 Processed in 0.047163 second(s) w3c
本博客的所有原创作品采用“知识共享”署名-非商业性使用-相同方式共享2.5协议进行许可
本站由七牛云存储,阿里云计算与安全服务,又拍云CDN加速,百度智能,AMH,布集网,指南针AI
桂公网安备 45010302000998号 桂ICP备15007619号-1 中国互联网举报中心 建议使用谷歌浏览器(Google Chrome)浏览
确定要清除编辑框内容吗?
该删除操作将不可恢复。
删除 取消
激活Windows
转到"设置"以激活Windows。