php经典文件上传类

 更新时间:2016年11月25日 16:02  点击:1702

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;
 }
}

//这个是后台管理当中的分类列表页

//包含无限分类

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常用缓存方式入门教程
第一种,把需要缓存的数据进行处理,形成PHP可以直接执行的文件。在需要缓存数据

的时候,通过include方式引入,并使用。
第二种,把需要的数据通过serialize函数序列化后直接保存到文件。在需要使用缓存

数据的时候,通过反序列化读入文件内容并复制给需要的变量,然后使用。

测试结果:
通过测试我们发现,第二种也就是serialize缓存数据的方式更加高效。(数据略去,

最后提供了文章地址下载,大家可以自行测试)

原因分析:
include方式读取缓存的时候,PHP需要执行几个过程
1.读取文件
2.解析所Include的文件
3.执行,给变量赋值

而serialize序列化方式读取缓存的时候:
1.读取数据
2.反序列化数据内容
3.给变量赋值

从以上内容对比的话,可能是由于解析PHP文件内的数组需要的时间超过unserialize反

序列化数组的时间。如果你有兴趣可以查看《PHP filesystem相关函数和include

require的性能效率研究》:http://www.ccvita.com/163.html

测试文件代码:
下载地址:MooPHP-CacheTest.zip
原创地址:http://www.ccvita.com/311.html 有新的研究心得会在这里更新。
CacheTest_IncludeFile.php
CacheTest_SerializeFile.php

总结分析:
第一种,include缓存的方式
优点:增加数据的保密性,和安全性,缓存内容不会被外界发现。
缺点:速度相对较慢。
用途:保存禁止系统外部得知的数据,比如web系统的设置,甚至MySQL信息等的保存
第二种,serialize序列化缓存的方式
优点:速度较快。
缺点:缓存系统文件路径一点曝光,缓存内容会泄露。
用途:缓存最新文章,相关文章等不担心外部得知的数据的时候,可以使用这种方式。

备注:
当装了ea、apc等PHP内存缓存之后,第一种通过include读取缓存的方式速度会高于第

二种serialize序列化缓存的方式。所以在MooPHP框架中,我们对于非敏感信息采用第

二种方式缓存;敏感信息采用第一种方式缓存

php 批量生成缩略图代码

//创建目录(目录, [模式])
function mkdirs($l1, $l2 = 0777){
if(!is_dir($l1)){
  //如果目录不存在,递归建立
  mkdirs(dirname($l1), $l2); 
  return @mkdir($l1, $l2);
}
return true;
}
//保存文件(文件, [内容])
function savefile($l1, $l2=''){ 
if(function_exists(file_put_contents)){
  file_put_contents($l1, $l2);
} else{
  $fp = @fopen($l1, 'wb');
  @fwrite($fp, $l2);
  fclose($fp);
}
}
//获取文件后缀(文件)
function getfix($l1){
return end(explode('.', $l1));
}
//是否为允许类型(当前, 允许)
function checkfix($l1, $l2){
if(!is_array($l2)){
  $l2 = explode(',', str_replace(' ', '', $l2));
}
return in_array($l1, $l2) ? 1 : 0;
}
class image{
//源地址
var $src; 
//新图路径(本地化后)
var $newsrc;
 
//允许的图类型
var $allowtype = array('.jpg','.gif','.png','.jpeg'); 
//是否缩略GIF, 为0不处理
var $regif   = 0;
//是否保留源文件(1为保留, 0为MD5)
var $keep = 0;
//是否可以覆盖已存在的图片,为0则不可覆盖
var $over = 0;
  
//图片源目录
var $dir;
//处理后的目录
var $newdir;

function __construct($l1=null, $l2=null){
  $this->dir   = $l1 ? $l1 : "./images/temp";
  $this->newdir = $l2 ? $l2 : "./images/s";
}

function image($l1=null, $l2=null){
  $this->__construct($l1, $l2);
}

/**
  * 处理后的文件路径
  * 将源图片,MD5文件名后保存到新的目录里
  *
  * @ param  rename()
  * @ return 处理后的文件名
  */
function reName($src){
  //MD5后文件名(例如:3293okoe.gif)
  $l1 = substr(md5($src),10,10).strrchr($src,".");
  //处理后文件名
  $l1  = $this->w.'_'.$this->h.'_'.$l1;
  //返回处理后的地址
  return $this->newdir.'/'.$l1;
}

 
/**
  * 生成缩略图
  *
  * @ param  Mini(图片地址, 宽度, 高度, 质量)
  *   如果要保留原来的文件名,请设置 $o->keep = 1;
  * @ return 处理后的图片地址
  */
function Mini($src,$w,$h, $q=80){
  $this->src = $src;
  $this->w = $w;
  $this->h = $h;
 
  //是否处理GIF图
  if(strrchr($src, ".") == ".gif" && $this->regif == 0){
   return $this->src;
  }
 
  //是否保留原文件名,默认不保留
  if(!$this->keep){
   //改名后的文件地址
   $newsrc = $this->reName($src);
  } else {
   //保持原名
   $src = str_replace('\', '/', $src);
   $newsrc = $this->newdir.strrchr($src, "/");
  }
 
  //如果已存在,直接返回地址
  if(file_exists($newsrc) && $this->over == 0){
   return $newsrc;
  }
 
  //如果是网络文件,先保存
  if(strstr($src, "http://") && !strstr($src, $_SERVER['HTTP_HOST'])){
   $src = $this->getimg($src);
  }
  //获取图片属性
  $arr = getimagesize($src); 
  $ow = $arr[0];
  $oh = $arr[1];
  $ot = $arr[2]; 
  switch($ot){
   case 1:
    $im = imagecreatefromgif($src);
    break;
   case 2:
    $im = imagecreatefromjpeg($src);
    break;
   case 3:
    $im = imagecreatefrompng($src);
    break;
   default:
    return 0;
  }
  //处理缩略图
  $nim = imagecreatetruecolor($w,$h);
  $k1 = round($h/$w,2);
  $k2 = round($oh/$ow,2);
  if ($k1<$k2){
   $oow = $ow;
   $ooh = round($ow*$k1);
   $sw = 0;
   $sh = ($oh-$ooh)/2;
  }
  else {
   $oow = $oh/$k1;
   $ooh = $oh;
   $sw = ($ow-$oow)/2;
   $sh = 0;
  }
  //生成图片
  if(function_exists(imagecopyresampled)){
   imagecopyresampled($nim,$im,0,0,$sw,$sh,$w,$h,$oow,$ooh);  
  }
  else {
   imagecopyresized($nim,$im,0,0,$sw,$sh,$w,$h,$oow,$ooh);
  }
  //处理后的目录是否存在
  if(!is_dir($this->newdir)){
   @mkdir($this->newdir);
  }
  //保存图片   
  switch($ot){
   case 1:
    $rs = imagegif($nim,$newsrc);
    break;
   case 2:
    $rs = imagejpeg($nim,$newsrc,$q);
    break;
   case 3:
    $rs = imagepng($nim,$newsrc);
    break;
   default:
    return 0;
  }
  //返回处理后路径
  return $newsrc;   
}
  
/**
  * 保存网络图片
  *
  * @ param  getImg(源图)
  * @ return 保存后的本地址址(本地目录的MD5文件名)
  */
function getimg($l1){
  $l2 = $this->dir.'/'.substr(md5($l1),10,10).strrchr($l1,".");
  //文件存在,直接返回地址
  if(file_exists($l2)){  
   //echo "exits...";
   return $l2;
  }
 
  //开始获取文件,并返回新路径
  $img = file_get_contents($l1);    
  if($img){
   if(!is_dir($this->dir)){
    @mkdir($this->dir);
   }
   savefile($l2, $img);
   //echo "file_get..";
   return $l2;
  }   
}

/**
  * 转换缩略图(文件名和结构不变)
  *
  * @ param  mini(源地址, 宽度, 高度, 质量 )
  * @ return 生成的地址
  */

function reImg($src, $w, $h, $q=80){
  $this->keep = 1;
  return $this->Mini($src, $w, $h, $q);
}
}

php fscokopen实现数据异步调用代码

我们就可以使用fsockopen连接到本地服务器,触发脚本执行,然后立即返回,不等待

脚本执行完成。
 
function triggerRequest($url,
$post_data
=
array(),
$cookie
=
array())…{
        $method
=
"GET";  //可以通过POST或者GET传递一些参数给要触发的脚本

$url_array
=
parse_url($url); //获取URL信息,以便平凑HTTP HEADER

$port
=
isset($url_array['port'])?
$url_array['port'] :
80;
     
        $fp
=
fsockopen($url_array['host'],
$port,
$errno,
$errstr,
30);
        if (!$fp) …{
                return
FALSE;
        }
        $getPath
=
$url_array['path'] ."?".
$url_array['query'];
        if(!empty($post_data))…{
                $method
=
"POST";
        }
        $header
=
$method
.
"
"
.
$getPath;
        $header
.=
" HTTP/1.1rn";
        $header
.=
"Host: ".
$url_array['host'] .
"rn
"; //HTTP 1.1 Host域不能省略

/**//*以下头信息域可以省略
        $header .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en

-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13 rn";
        $header .= "Accept:

text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=

0.8,image/png,q=0.5 rn";
        $header .= "Accept-Language: en-us,en;q=0.5 ";
        $header .= "Accept-Encoding: gzip,deflatern";
         */

        $header
.=
"Connection:Closern";
        if(!empty($cookie))…{
                $_cookie
=
strval(NULL);
                foreach($cookie
as
$k
=>
$v)…{
                        $_cookie
.=
$k."=".$v."; ";
                }
                $cookie_str
=
"Cookie: "
.
base64_encode($_cookie) ." rn";//传递Cookie

$header
.=
$cookie_str;
        }
        if(!empty($post_data))…{
                $_post
=
strval(NULL);
                foreach($post_data
as
$k
=>
$v)…{
                        $_post
.=
$k."=".$v."&";
                }
                $post_str
=
"Content-Type: application/x-www-form-urlencodedrn";//POST数据

$post_str
.=
"Content-Length: ".
strlen($_post) ." rn";//POST数据的长度

$post_str
.=
$_post."rnrn "; //传递POST数据

$header
.=
$post_str;
        }
        fwrite($fp,
$header);
        //echo fread($fp, 1024); //我们不关心服务器返回

fclose($fp);
        return
true;
}

 

    现在,就可以通过这个函数来触发一个PHP脚本的执行,然后函数就会返回。 我们

就可以接着执行下一步操作了。

   还有一个问题就是,当客户端断开连接以后。也就是triggerRequest发送请求后,

立即关闭了连接,那么可能会引起服务器端正在执行的脚本退出。

   在 PHP 内部,系统维护着连接状态,其状态有三种可能的情况:

    * 0 - NORMAL(正常)

    * 1 - ABORTED(异常退出)

    * 2 - TIMEOUT(超时)

     当 PHP 脚本正常地运行 NORMAL 状态时,连接为有效。当客户端中断连接时,

ABORTED状态的标记将会被打开。远程客户端连接的中断通常是由用户点击 STOP 按钮

导致的。当连接时间超过 PHP 的时限(请参阅set_time_limit() 函数)时,TIMEOUT

状态的标记将被打开。

    可以决定脚本是否需要在客户端中断连接时退出。有时候让脚本完整地运行会带来

很多方便,即使没有远程浏览器接受脚本的输出。默认的情况是当远程客户端连接中断

时脚本将会退出。该处理过程可由 php.ini 的 ignore_user_abort 或由 Apache

.conf设置中对应的“php_value ignore_user_abort”以及 ignore_user_abort() 函

数来控制。如果没有告诉PHP 忽略用户的中断,脚本将会被中断,除非通过

register_shutdown_function()设置了关闭触发函数。通过该关闭触发函数,当远程用

户点击 STOP 按钮后,脚本再次尝试输出数据时,PHP将会检测到连接已被中断,并调

用关闭触发函数。

     脚本也有可能被内置的脚本计时器中断。默认的超时限制为 30 秒。这个值可以

通过设置 php.ini 的max_execution_time 或 Apache .conf 设置中对应的

“php_valuemax_execution_time”参数或者 set_time_limit()函数来更改。当计数器

超时的时候,脚本将会类似于以上连接中断的情况退出,先前被注册过的关闭触发函数

也将在这时被执行。在该关闭触发函数中,可以通过调用 connection_status() 函数

来检查超时是否导致关闭触发函数被调用。如果超时导致了关闭触发函数的调用,该函

数将返回 2。

     需要注意的一点是 ABORTED 和 TIMEOUT 状态可以同时有效。这在告诉 PHP 忽略

用户的退出操作时是可能的。PHP将仍然注意用户已经中断了连接但脚本仍然在运行的

情况。如果到了运行的时间限制,脚本将被退出,设置过的关闭触发函数也将被执行。

在这时会发现函数connection_status() 返回 3。

      所以还在要触发的脚本中指明:


ignore_user_abort(TRUE); //如果客户端断开连接,不会引起脚本abort.
set_time_limit(0);//取消脚本执行延时上限

     或者,也可以使用:
register_shutdown_function(callback fuction[, parameters]);//注册脚本退出时

执行的函数

[!--infotagslink--]

相关文章

  • php读取zip文件(删除文件,提取文件,增加文件)实例

    下面小编来给大家演示几个php操作zip文件的实例,我们可以读取zip包中指定文件与删除zip包中指定文件,下面来给大这介绍一下。 从zip压缩文件中提取文件 代...2016-11-25
  • Jupyter Notebook读取csv文件出现的问题及解决

    这篇文章主要介绍了JupyterNotebook读取csv文件出现的问题及解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2023-01-06
  • Photoshop打开PSD文件空白怎么解决

    有时我们接受或下载到的PSD文件打开是空白的,那么我们要如何来解决这个 问题了,下面一聚教程小伙伴就为各位介绍Photoshop打开PSD文件空白解决办法。 1、如我们打开...2016-09-14
  • C#操作本地文件及保存文件到数据库的基本方法总结

    C#使用System.IO中的文件操作方法在Windows系统中处理本地文件相当顺手,这里我们还总结了在Oracle中保存文件的方法,嗯,接下来就来看看整理的C#操作本地文件及保存文件到数据库的基本方法总结...2020-06-25
  • 解决python 使用openpyxl读写大文件的坑

    这篇文章主要介绍了解决python 使用openpyxl读写大文件的坑,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-13
  • C#实现HTTP下载文件的方法

    这篇文章主要介绍了C#实现HTTP下载文件的方法,包括了HTTP通信的创建、本地文件的写入等,非常具有实用价值,需要的朋友可以参考下...2020-06-25
  • SpringBoot实现excel文件生成和下载

    这篇文章主要为大家详细介绍了SpringBoot实现excel文件生成和下载,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-09
  • php无刷新利用iframe实现页面无刷新上传文件(1/2)

    利用form表单的target属性和iframe 一、上传文件的一个php教程方法。 该方法接受一个$file参数,该参数为从客户端获取的$_files变量,返回重新命名后的文件名,如果上传失...2016-11-25
  • Php文件上传类class.upload.php用法示例

    本文章来人大家介绍一个php文件上传类的使用方法,期望此实例对各位php入门者会有不小帮助哦。 简介 Class.upload.php是用于管理上传文件的php文件上传类, 它可以帮...2016-11-25
  • php批量替换内容或指定目录下所有文件内容

    要替换字符串中的内容我们只要利用php相关函数,如strstr,str_replace,正则表达式了,那么我们要替换目录所有文件的内容就需要先遍历目录再打开文件再利用上面讲的函数替...2016-11-25
  • PHP文件上传一些小收获

    又码了一个周末的代码,这次在做一些关于文件上传的东西。(PHP UPLOAD)小有收获项目是一个BT种子列表,用户有权限上传自己的种子,然后配合BT TRACK服务器把种子的信息写出来...2016-11-25
  • jQuery实现简单的文件上传进度条效果

    本文实例讲述了jQuery实现文件上传进度条效果的代码。分享给大家供大家参考。具体如下: 运行效果截图如下:具体代码如下:<!DOCTYPE html><html><head><meta charset="utf-8"><title>upload</title><link rel="stylesheet...2015-11-24
  • AI源文件转photoshop图像变模糊问题解决教程

    今天小编在这里就来给photoshop的这一款软件的使用者们来说下AI源文件转photoshop图像变模糊问题的解决教程,各位想知道具体解决方法的使用者们,那么下面就快来跟着小编...2016-09-14
  • C++万能库头文件在vs中的安装步骤(图文)

    这篇文章主要介绍了C++万能库头文件在vs中的安装步骤(图文),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-23
  • Zend studio文件注释模板设置方法

    步骤:Window -> PHP -> Editor -> Templates,这里可以设置(增、删、改、导入等)管理你的模板。新建文件注释、函数注释、代码块等模板的实例新建模板,分别输入Name、Description、Patterna)文件注释Name: 3cfileDescriptio...2013-10-04
  • php文件上传你必须知道的几点

    本篇文章主要说明的是与php文件上传的相关配置的知识点。PHP文件上传功能配置主要涉及php.ini配置文件中的upload_tmp_dir、upload_max_filesize、post_max_size等选项,下面一一说明。打开php.ini配置文件找到File Upl...2015-10-21
  • ant design中upload组件上传大文件,显示进度条进度的实例

    这篇文章主要介绍了ant design中upload组件上传大文件,显示进度条进度的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-10-29
  • C#使用StreamWriter写入文件的方法

    这篇文章主要介绍了C#使用StreamWriter写入文件的方法,涉及C#中StreamWriter类操作文件的相关技巧,需要的朋友可以参考下...2020-06-25
  • php实现文件下载实例分享

    举一个案例:复制代码 代码如下:<?phpclass Downfile { function downserver($file_name){$file_path = "./img/".$file_name;//转码,文件名转为gb2312解决中文乱码$file_name = iconv("utf-8","gb2312",$file_name...2014-06-07
  • C#路径,文件,目录及IO常见操作汇总

    这篇文章主要介绍了C#路径,文件,目录及IO常见操作,较为详细的分析并汇总了C#关于路径,文件,目录及IO常见操作,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25