实用的php购物车程序

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

实用的php教程购物车程序
以前有用过一个感觉不错,不过看了这个感觉也很好,所以介绍给需要的朋友参考一下。

<?php
//调用实例
require_once 'cart.class.php';
session_start();
if(!isset($_SESSION['cart'])) {
 $_SESSION['cart'] = new Cart;
}
$cart =& $_SESSION['cart'];

if( ($_SERVER['REQUEST_METHOD']=="POST")&&($_POST['action']=='add') ){
 $p = $_POST['p'];
 $items = $cart->add($p);
}
if( ($_GET['action']=='remove')&&($_GET['key']!="") ) {
 $items = $cart->remove($_GET['key']);
}

if( ($_SERVER['REQUEST_METHOD']=="POST")&&($_POST['action']=='modi') ){
 $key = $_POST['key'];
 $value = $_POST['value'];
 for($i=0;$i<count($key);$i  ){
  $items = $cart->modi($key[$i],$value[$i]);
 }
}

$items = $cart->getCart();
//打印
echo "<table border=1>";
setlocale(LC_MONETARY, 'it_IT');
foreach($items as $item){
 echo "<tr><form method="post" action="tmp.php">";
 echo "<td>ID:".$item['ID']."<input type=hidden name=key[] value=".$item['ID'].">";
 echo "<td>产品:".$item['name'];
 echo "<td>单价:".$item['price'];
 echo "<td><input type=text name=value[] value=".$item['count'].">";
  $sum = $item['count']*$item['price'];
 echo "<td>合计:".round($sum,2);
 echo "<td><input type=button value='删除' onclick="location='?action=remove&key=".$item['ID']."'">";
}
echo "<input type=hidden name=action value=modi>";
echo "<tr><td colspan=7><input type=submit />";
echo "</td></form></tr></table>";


?>
<hr>
<form method="post" action="tmp.php">
ID:<input type="text" name="p[]" />
品名:<input type="text" name="p[]" />
单价:<input type="text" name="p[]" />
数量:<input type="text" name="p[]" />
<input type=hidden name=action value=add>
<input type="submit" />
</form>

 

<?
/**
 * Cart
 *
 * 购物车类
 *
 * @author  doodoo<pWtitle@yahoo.com.cn>
 * @package     Cart
 * @category    Cart
 * @license     PHP License
 * @access      public
 * @version     $Revision: 1.10 $
 */
Class Cart{

 var $cart;
 var $totalCount; //商品总数量
 var $totalPrices; //商品总金额

  /**
     * Cart Constructor
     *
     * 类的构造函数,使购物车保持稳定的初始化状态
     *
     * @static
     * @access  public
     * @return  void   无返回值
     * @param   void   无参数
     */
  function Cart(){
  $this->totalCount = 0;
  $this->totalPrice = 0;
  $this->cart = array();
 }
 
 // }}}
    // {{{ add($item)

    /**
 * 增加商品到当前购物车
 *
    * @access public
    * @param  array $item 商品信息(一维数组:array(商品ID,商品名称,商品单价,商品数量))
    * @return array   返回当前购物车内商品的数组
    */
 function add($item){
  if(!is_array($item)||is_null($item)) return $this->cart;
  if(!is_numeric(end($item))||(!is_numeric(prev($item)))) {
   echo "价格和数量必须是数字";
   return $this->cart;
  }
  reset($item); //这一句是必须的,因为上面的判断已经移动了数组的指标
  $key = current($item);
  if($key=="") return $this->cart;
  if($this->_isExists($key)){  //商品是否已经存在?
    $this->cart[$key]['count']  = end($item);
  return $this->cart;
  }

  $this->cart[$key]['ID']  = $key;
  $this->cart[$key]['name'] = next($item);
  $this->cart[$key]['price'] = next($item);
  $this->cart[$key]['count'] = next($item);

 return $this->cart;
 }

 // }}}
    // {{{ add($item)

    /**
 * 从当前购物车中取出部分或全部商品
 * 当 $key=="" 的时候,清空当前购物车
 * 当 $key!=""&&$count=="" 的时候,从当前购物车中拣出商品ID号为 $key 的全部商品
 * 当 $key!=""&&$count!="" 的时候,从当前购物车中拣出 $count个 商品ID号为 $key 的商品
 *
    * @access public
    * @param  string $key 商品ID
    * @return mixed   返回真假或当前购物车内商品的数组
    */
 function remove($key="",$count=""){
  if($key=="") {
   $this->cart = array();
   return true;
  }
  if(!array_key_exists($key,$this->cart)) return false;
  if($count==""){ //移去这一类商品
   unset($this->cart[$key]);
  }else{ //移去$count个商品
   $this->cart[$key]['count'] -= $count;
   if($this->cart[$key]['count']<=0) unset($this->cart[$key]);
  }
  return $this->cart;
 }

 // }}}
    // {{{ modi($key,$value)

    /**
 * 修改购物车内商品ID为 $key 的商品的数量为 $value
 *
    * @access public
    * @param  string $key 商品ID
    * @param  int $value 商品数量
    * @return array  返回当前购物车内商品的数组;
    */
 function modi($key,$value){
  if(!$this->_isExists($key)) return $this->cart();  //不存在此商品,直接返回
  if($value<=0){     // value 太小,全部删除
   unset($this->cart[$key]);
   return $this->cart;
  }
  $this->cart[$key]['count'] = $value;
  return $this->cart;
 }


    /**
 * 返回当前购物车内商品的数组
 *
    * @access public
    * @return array  返回当前购物车内商品的数组;
    */
 function getCart(){
  return $this->cart;
 }

 // }}}
    // {{{ _isExists($key)

    /**
 * 判断当前购物车中是否存在商品ID号为$key的商品
 *
    * @access private
    * @param  string $key 商品ID
    * @return bool   true or false;
    */
    function _isExists($key)
    {
  if(isset($this->cart[$key])&&!empty($this->cart[$key])&&array_key_exists($key,$this->cart))
   return true;
    return false;
    }

 // }}}
    // {{{ isEmpty()

    /**
 * 判断当前购物车是否为空,即没有任何商品
 *
    * @access public
    * @return bool   true or false;
    */
 function isEmpty(){
  return !count($this->cart);
 }

 // }}}
    // {{{ _stat()

    /**
 * 取得部分统计信息
 *
    * @access private
    * @return bool  true or false;
    */
 function _stat(){
  if($this->isEmpty()) return false;
  foreach($this->cart as $item){
   $this->totalCount   = @end($item);
   $this->totalPrices  = @prev($item);
  }
  return true;
 }

 // }}}
    // {{{ totalPrices()

    /**
 * 取得当前购物车所有商品的总金额
 *
    * @access public
    * @return float  返回金额;
    */
 function totalPrices(){
  if($this->_stat())
   return $this->totalPrices;
 return 0;
 }

 // }}}
    // {{{ isEmpty()

    /**
 * 取得当前购物车所有商品的总数量和
 *
    * @access public
    * @return int ;
    */
 function totalCount(){
  if($this->_stat())
   return $this->totalCount; 
 return 0;
 }


}//End Class Cart
?>

php教程图片上传,可实现预览

<?php
header("content-Type: text/html; charset=gb2312");
$uptypes=array('image/jpg',  //上传文件类型列表
 'image/jpeg',
 'image/png',
 'image/pjpeg',
 'image/gif',
 'image/bmp',
 'application/x-shockwave-flash',
 'image/x-png',
 'application/msword',
 'audio/x-ms-wma',
 'audio/mp3',
 'application/vnd.rn-realmedia',
 'application/x-zip-compressed',
 'application/octet-stream');

$max_file_size=10000000;   //上传文件大小限制, 单位BYTE
$path_parts=pathinfo($_SERVER['PHP_SELF']); //取得当前路径
$destination_folder="up/"; //上传文件路径
$watermark=0;   //是否附加水印(1为加水印,0为不加水印);
$watertype=1;   //水印类型(1为文字,2为图片)
$waterposition=2;   //水印位置(1为左下角,2为右下角,3为左上角,4为右上角,5为居中);
$waterstring="www.yinao.tk"; //水印字符串
$waterimg="xplore.gif";  //水印图片
$imgpreview=1;   //是否生成预览图(1为生成,0为不生成);
$imgpreviewsize=1/1;  //缩略图比例
?>
<html xmlns="undefined">
<head>
<title>图片上传储存</title>
<style type="text/css教程">
body,td{font-family:tahoma,verdana,arial;font-size:11px;line-height:15px;background-color:white;color:#666666;
strong{font-size:12px;}
a:link{color:#0066CC;}
a:hover{color:#FF6600;}
a:visited{color:#003366;}
a:active{color:#9DCC00;}
a{TEXT-DECORATION:none}
td.irows{height:20px;background:url("index.php?i=dots") repeat-x bottom}
</style>
</head>
<script type="text/网页特效">function oCopy(obj){obj.select();js=obj.createTextRange();js.execCommand("Copy");};function sendtof(url){window.clipboardData.setData('Text',url);alert('复制地址成功,粘贴给你好友一起分享。');};function select_format(){var on=document.getElementById('fmt').checked;document.getElementById('site').style.display=on?'none':'';document.getElementById('sited').style.display=!on?'none':'';};var flag=false;function DrawImage(ImgD){var image=new Image();image.src=ImgD.src;if(image.width>0&&image.height>0){flag=true;if(image.width/image.height>=120/80){if(image.width>120){ImgD.width=120;ImgD.height=(image.height*120)/image.width;}else {ImgD.width=image.width;ImgD.height=image.height;};ImgD.alt=image.width+"×"+image.height;}else {if(image.height>80){ImgD.height=80;ImgD.width=(image.width*80)/image.height;}else {ImgD.width=image.width;ImgD.height=image.height;};ImgD.alt=image.width+"×"+image.height;}};};function FileChange(Value){flag=false;document.all.uploadimage.width=10;document.all.uploadimage.height=10;document.all.uploadimage.alt="";document.all.uploadimage.src=Value;};</script>
<body bgcolor="#FFFFFF">
<center>
  <form enctype="multipart/form-data" method="post" name="upform">
    <table border="1" width="55%" id="table1" cellspacing=0>
      <tr>
        <td colspan="2"><p align="center">最大文件限制1M </td>
      </tr>
      <tr>
        <td width="10%"><div style="width:120px; height:80px;overflow:hidden;text-align: center;" ><IMG id=uploadimage height=0 width=0 src=""  onload="javascript:DrawImage(this);" ></div></td>
        <td width="71%"><div style="width:361px; height:80px;overflow:hidden;text-align: center;padding:30px; " >
          <input style="width:208;border:1 solid #9a9999; font-size:9pt; background-color:#ffffff; height:18" size="17" name=upfile type=file
onchange="javascript:FileChange(this.value);">
          <input type="submit" value="上传" style="width:60;border:1 solid #9a9999; font-size:9pt; background-color:#ffffff; height:18" size="17"></td>
      </tr>
    </table>
    允许上传的文件类型为:jpg|jpeg|gif|bmp|png|swf|mp3|wma|zip|rar|doc</form>
  <?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (!is_uploaded_file($_FILES["upfile"][tmp_name]))
//是否存在文件
{
echo "<font color='red'>文件不存在!</font>";
exit;
}

 $file = $_FILES["upfile"];
 if($max_file_size < $file["size"])
 //检查文件大小
 {
 echo "<font color='red'>文件太大!</font>";
 exit;
  }

if(!in_array($file["type"], $uptypes))
//检查文件类型
{
 echo "<font color='red'>不能上传此类型文件!</font>";
 exit;
}

if(!file_exists($destination_folder))
mkdir($destination_folder);

$filename=$file["tmp_name"];
$image_size = getimagesize($filename);
$pinfo=pathinfo($file["name"]);
$ftype=$pinfo[extension];
$destination = $destination_folder.time().".".$ftype;
if (file_exists($destination) && $overwrite != true)
{
     echo "<font color='red'>同名文件已经存在了!</a>";
     exit;
  }

 if(!move_uploaded_file ($filename, $destination))
 {
   echo "<font color='red'>移动文件出错!</a>";
     exit;
  }

$pinfo=pathinfo($destination);
$fname=$pinfo[basename];
echo " <font color=red>成功上传,鼠标移动到地址栏自动复制</font><br><table width="348" cellspacing="0" cellpadding="5" border="0" class="table_decoration" align="center"><tr><td><input type="checkbox" id="fmt" onclick="select_format()"/>图片UBB代码<br/><div id="site"><table border="0"><tr><td valign="top">文件地址:</td><td><input type="text" onclick="sendtof(this.value)" onmouseo教程ver="oCopy(this)" style=font-size=9pt;color:blue size="44" value="http://".$_SERVER['SERVER_NAME'].$path_parts["dirname"]."/".$destination_folder.$fname.""/>
</td></tr></table></div><div id="sited" style="display:none"><table border="0"><tr><td valign="top">文件地址:</td><td><input type="text" onclick="sendtof(this.value)" onmouseover="oCopy(this)" style=font-size=9pt;color:blue size="44" value="[img]http://".$_SERVER['SERVER_NAME'].$path_parts["dirname"]."/".$destination_folder.$fname."[/img]"/></td></tr></table></div></td></tr></table>";
echo " 宽度:".$image_size[0];
echo " 长度:".$image_size[1];
if($watermark==1)
{
$iinfo=getimagesize($destination,$iinfo);
$nimage=imagecreatetruecolor($image_size[0],$image_size[1]);
$white=imagecolorallocate($nimage,255,255,255);
$black=imagecolorallocate($nimage,0,0,0);
$red=imagecolorallocate($nimage,255,0,0);
imagefill($nimage,0,0,$white);
switch ($iinfo[2])
{
 case 1:
 $simage =imagecreatefromgif($destination);
 break;
 case 2:
 $simage =imagecreatefromjpeg($destination);
 break;
 case 3:
 $simage =imagecreatefrompng($destination);
 break;
 case 6:
 $simage =imagecreatefromwbmp($destination);
 break;
 default:
 die("<font color='red'>不能上传此类型文件!</a>");
 exit;
}

imagecopy($nimage,$simage,0,0,0,0,$image_size[0],$image_size[1]);
imagefilledrectangle($nimage,1,$image_size[1]-15,80,$image_size[1],$white);

switch($watertype)
{
 case 1:  //加水印字符串
 imagestring($nimage,2,3,$image_size[1]-15,$waterstring,$black);
 break;
 case 2:  //加水印图片
 $simage1 =imagecreatefromgif("xplore.gif");
 imagecopy($nimage,$simage1,0,0,0,0,85,15);
 imagedestroy($simage1);
 break;
}

switch ($iinfo[2])
{
 case 1:
 //imagegif($nimage, $destination);
 imagejpeg($nimage, $destination);
 break;
 case 2:
 imagejpeg($nimage, $destination);
 break;
 case 3:
 imagepng($nimage, $destination);
 break;
 case 6:
 imagewbmp($nimage, $destination);
 //imagejpeg($nimage, $destination);
 break;
}

//覆盖原上传文件
imagedestroy($nimage);
imagedestroy($simage);
}

if($imgpreview==1)
{
echo "<br>图片预览:<br>";
echo "<a href="".$destination."" target='_blank'><img src="".$destination."" width=".($image_size[0]*$imgpreviewsize)." height=".($image_size[1]*$imgpreviewsize);
echo " alt="图片预览:r文件名:".$fname."r上传时间:".date('m/d/Y h:i')."" border='0'></a>";
}
}
?>
</center>
</body>
</html>

主要目的就是测试我的php.ini没有设置upload_dir_tmp的值的时候,上传的文件临时保存在哪里的,经过这个测试发现原来在不配置php.ini的upload_dir_tmp的值的时候,默认的存储位置是在 C:\windows\temp目录,并且临时文件是以.tmp为后缀存储的,该文件马上就会被删除,所以你想通过操作系统的文件修改搜索功能是无法找到的,也就无法找到upload_dir_tmp的默认路径是哪里。

IIS+php教程服务器无法上传图片解决办法

服务器上使用Apache2+PHP正常运行,换成IIS+PHP,先后出现了php.ini的环境变量无法读取,php中验证码无法显示的问题,如今又有人反应无法上传图片的问题。

   从IIS替换Apache2的过程仅仅是开启IIS,关闭Apache2,其它的没什么变化,但是却发生了如此多的差异,看样子IIS支持PHP还是有很多要进行修改的。

分析:

   根据上面的描述,我怀疑问题出在IIS的权限配置上,IUSR_MACHINE的帐户对upload没有写入的权限,于是进行权限修改,IIS下的权限,NTFS下的权限都进行修改,但是终究都没用,查找网络上的资料也没有相应的,对上传页面进行测试,流程为:

   swf文件调用save.php上传文件---->swf文件对上传的文件进行重命名--->名字返回给save.php--->显示出最后的名字。

   现在的问题一直停留在swf对文件重命名的这里,一直没有到显示出最后的名字,并且swf文件不参与上传过程,那就只能在save.php文件中进行问题查找了,在该文件中进行测试,最后显示的名字所使用的变量为fileName,于是插入下面的语句进行测试:

   echo "fileName=2008*****.gif";

   这句话的作用就是使得fileName有值,save.php能正常显示,先把原来的语句一句一句的进行屏蔽测试,都正常的返回了,但是当测试到:
    if (!@move_uploaded_file($f["tmp_name"], $dest_dir.'/'.$fileName)) header("HTTP/1.0 404 Not Found");
   这句话的时候问题出现了,不能上传,查找上下文,一直没发现tmp_name的变量,不过看意思是先把文件上传到一个临时文件,再挪动到目的位置,那这个tmp位置在哪里呢?是不是这个位置不可写,才导致了无法上传文件?

   查找网上资料,发现php.ini下面有2个地方关于上传的配置:
file_uploads = On                          这里设置是否允许HTTP上传,默认应该为ON的
   ;upload_tmp_dir=                          这里设置上传文件存放的临时位置

网上对于这2个地方的相关资料有:
I try to set up file uploading under IIS 7 and PHP 5.

First problem was to set 2 variables in php.ini

file_uploads = On           //这里是说php.ini文件这个地方设置成On

upload_tmp_dir = "C:Inetpubwwwrootuploads"    //这个路径就是自己设置的上传文件临时存储路径

For some reasons such directory name works,
but "upload_tmp" won't work.

The second problem was to set correct user rigths for upload folders where you try to save your file. I set my upload folder rights for the "WORKGROUP/users" for the full access. You may experiment by yourselves if you not need execute access, for example.

    我的php.ini中upload_tmp_dir是被注释的,没有启用,更没有设置,可是为什么Apache2却可以正常上传呢?难道问题真的出在这里?

解决:

   新建一个文件夹做临时上传目录,按照上面的英文说明修改php.ini中相应的那2项,把临时上传目录upload_tmp_dir设置成刚才建立的文件夹,把该文件夹的权限赋予“IUSR_计算机名”用户可写,重新启动IIS,上传试试,问题真的就这样解决了。


最终的分析答案:

   上面的内容写于09年,但是现在2010年7月我新增一台服务器,又出现了这个问题,同时再次按照上面的解决方法实施,在操作的过程中大概是由于哪里出了错,竟然没有成功,不得不抽出点时间来研究具体原因,找到了最终产生这个问题的原因如下。
    无法上传文件,不代表所有文件都无法上传,因为我的一个网站,flash调用fwrite()传头像之类的成功了,但是调用@move_uploaded_file($f["tmp_name"], $dest_dir.'/'.$fileName)这样的函数传照片的时候仍旧无法上传。
   经过我的分析,原因是由于fwrite()是传的二进制文件,而move_uploaded_file()传的是文本文件,而windows操作系统是区分这2种文件的 [参考php手册fwrite()函数的说明],这也就是说这2种不同的文件在php环境下上传时所存储的临时上传目录是不同的,由于在配置IIS环境下的PHP的时候,设置的临时目录为E:tmp,设置该目录的iusr用户可写,二进制文件即可上传,所以我怀疑该目录就是二进制文件上传临时文件的存储位置,那么move_uploaded_file()传的文本文件的临时文件存储位置在哪里呢?其实就是在上面的那段英文里面,upload_tmp_dir设置的路径就是了,但是我的几台服务器中,每台服务器的这个设置的值都是被注释掉的“no value”,为什么有的服务器可以上传,而有的服务器不可以上传呢?这也就回到了以前我提出的问题,为什么Apache2可以上传而iis不可以上传呢?
    这次我再次分析upload.php文件,分析其中造成该故障的代码具体内容如下:

// 检查是否有文件上传
    if (! $_FILES['upload'.$num]['name'] == ""){
      if ($_FILES['upload'.$num]['size'] < $max_size) { 
   1、 echo "文件上传路径:".$location.$_FILES['upload'.$num]['name'];
    2、echo "文件临时文件名:".$_FILES['upload'.$num]['tmp_name'];
    3、    move_uploaded_file($_FILES['upload'.$num]['tmp_name'],$location.$_FILES['upload'.$num]['name']) or $event = "Failure";
    } else {
     $event = "File too large!";
    }

   其中正常代码中第2句是不存在的,为了测试方便我加上来的,它的主要目的就是测试我的php.ini没有设置upload_dir_tmp的值的时候,上传的文件临时保存在哪里的,经过这个测试发现原来在不配置php.ini的upload_dir_tmp的值的时候,默认的存储位置是在 C:windowstemp目录,并且临时文件是以.tmp为后缀存储的,该文件马上就会被删除,所以你想通过操作系统的文件修改搜索功能是无法找到的,也就无法找到upload_dir_tmp的默认路径是哪里。

   既然找到了upload_dir_tmp的默认路径了,那么修改c:windowstemp的访问权限,赋予IUSR_用户可写,重启动IIS Admin服务,上传文件,终于成功了。这就是为什么我的多台服务器upload_dir_tmp的值都为空的时候有的可传,有的不可传的原因。

php教程文件下载实例
这里主要是利用php fopen函数来实现读取文件一个个传送到客户本地,有需要朋友可以参考一下。      

<form method="post">        
<input name="url" size="20" />        
<input name="submit" type="submit" />        
<!-- <input type="hidden" name="MAX_FILE_SIZE" value="2097152" />-->        
</form>        
<?php
    set_time_limit(24*60*60);
    if (!isset($_POST['submit'])) die ();
    $destination_folder = './down/';   // 文件夹保存下载文件。必须以斜杠结尾
    $url = $_POST['url'];
    $newfname = $destination_folder.basename($url);
    $file = fopen($url, "rb");
    if ($file) {
        $newf = fopen($newfname, "wb");
        if ($newf) while (!feof($file)) {
            fwrite($newf, fread($file, 1024*8), 1024*8);
        }
    }
    if ($file) {
        fclose($file);
    }
    if ($newf) {
        fclose($newf);
    }
?>
这里是来自网络朋友的一个实现的文件上传类代码,我们详细的介绍了每个变量的用处,下面看看吧,有需要可以参考一下。

这里是来自网络朋友的一个实现的文件上传类代码,我们详细的介绍了每个变量的用处,下面看看吧,有需要可以参考一下。

<?php教程
 /**
  * 文件上传类
  */
 class uploadFile {

  public $max_size = '1000000';//设置上传文件大小
  public $file_name = 'date';//重命名方式代表以时间命名,其他则使用给予的名称
  public $allow_types;//允许上传的文件扩展名,不同文件类型用“|”隔开
  public $errmsg = '';//错误信息
  public $uploaded = '';//上传后的文件名(包括文件路径)
  public $save_path;//上传文件保存路径
  private $files;//提交的等待上传文件
  private $file_type = array();//文件类型
  private $ext = '';//上传文件扩展名

  /**
   * 构造函数,初始化类
   * @access public
   * @param string $file_name 上传后的文件名
   * @param string $save_path 上传的目标文件夹
   */
  public function __construct($save_path = './upload/',$file_name = 'date',$allow_types = '') {
  $this->file_name   = $file_name;//重命名方式代表以时间命名,其他则使用给予的名称
  $this->save_path   = (preg_match('//$/',$save_path)) ? $save_path : $save_path . '/';
  $this->allow_types = $allow_types == '' ? 'jpg|gif|png|zip|rar' : $allow_types;
  }

  /**
   * 上传文件
   * @access public
   * @param $files 等待上传的文件(表单传来的$_FILES[])
   * @return boolean 返回布尔值
   */
 public function upload_file($files) {
  $name = $files['name'];
  $type = $files['type'];
  $size = $files['size'];
  $tmp_name = $files['tmp_name'];
  $error = $files['error'];

  switch ($error) {
   case 0 : $this->errmsg = '';
    break;
   case 1 : $this->errmsg = '超过了php.ini中文件大小';
    break;
   case 2 : $this->errmsg = '超过了MAX_FILE_SIZE 选项指定的文件大小';
    break;
       case 3 : $this->errmsg = '文件只有部分被上传';
    break;
   case 4 : $this->errmsg = '没有文件被上传';
    break;
   case 5 : $this->errmsg = '上传文件大小为0';
    break;
      default : $this->errmsg = '上传文件失败!';
    break;
   }
  if($error == 0 && is_uploaded_file($tmp_name)) {
   //检测文件类型
   if($this->check_file_type($name) == FALSE){
    return FALSE;
   }
   //检测文件大小
   if($size > $this->max_size){
    $this->errmsg = '上传文件<font color=red>'.$name.'</font>太大,最大支持<font color=red>'.ceil($this->max_size/1024).'</font>kb的文件';
    return FALSE;
   }
   $this->set_save_path();//设置文件存放路径
   $new_name = $this->file_name != 'date' ? $this->file_name.'.'.$this->ext : date('YmdHis').'.'.$this->ext;//设置新文件名
   $this->uploaded = $this->save_path.$new_name;//上传后的文件名
   //移动文件
   if(move_uploaded_file($tmp_name,$this->uploaded)){
    $this->errmsg = '文件<font color=red>'.$this->uploaded.'</font>上传成功!';
    return TRUE;
   }else{
    $this->errmsg = '文件<font color=red>'.$this->uploaded.'</font>上传失败!';
    return FALSE;
   }

  }
 }

  /**
   * 检查上传文件类型
   * @access public
   * @param string $filename 等待检查的文件名
   * @return 如果检查通过返回TRUE 未通过则返回FALSE和错误消息
   */
    public function check_file_type($filename){
  $ext = $this->get_file_type($filename);
  $this->ext = $ext;
    $allow_types = explode('|',$this->allow_types);//分割允许上传的文件扩展名为数组
    //echo $ext;
    //检查上传文件扩展名是否在请允许上传的文件扩展名中
    if(in_array($ext,$allow_types)){
     return TRUE;
    }else{
     $this->errmsg = '上传文件<font color=red>'.$filename.'</font>类型错误,只支持上传<font color=red>'.str_replace('|',',',$this->allow_types).'</font>等文件类型!';
     return FALSE;
    }
    }

    /**
     * 取得文件类型
     * @access public
     * @param string $filename 要取得文件类型的目标文件名
     * @return string 文件类型
     */
    public function get_file_type($filename){
     $info = pathinfo($filename);
     $ext = $info['extension'];
     return $ext;
    }

 /**
  * 设置文件上传后的保存路径
  */
 public function set_save_path(){
  $this->save_path = (preg_match('//$/',$this->save_path)) ? $this->save_path : $this->save_path . '/';
  if(!is_dir($this->save_path)){
   //如果目录不存在,创建目录
   $this->set_dir();
  }
 }


 /**
  * 创建目录
  * @access public
  * @param string $dir 要创建目录的路径
  * @return boolean 失败时返回错误消息和FALSE
  */
 public function set_dir($dir = null){
  //检查路径是否存在
  if(!$dir){
   $dir = $this->save_path;
  }
  if(is_dir($dir)){
   $this->errmsg = '需要创建的文件夹已经存在!';
  }
  $dir = explode('/', $dir);
  foreach($dir as $v){
   if($v){
    $d .= $v . '/';
    if(!is_dir($d)){
     $state = mkdir($d, 0777);
     if(!$state)
      $this->errmsg = '在创建目录<font color=red>' . $d . '时出错!';
    }
   }
  }
  return true;
 }
 }

/*************************************************
 * 图片处理类
 *
 * 可以对图片进行生成缩略图,打水印等操作
 * 本类默认编码为UTF8 如果要在GBK下使用请将img_mark方法中打中文字符串水印iconv注释去掉
 *
 * 由于UTF8汉字和英文字母大小(像素)不好确定,在中英文混合出现太多时可能会出现字符串偏左
 * 或偏右,请根据项目环境对get_mark_xy方法中的$strc_w = strlen($this->mark_str)*7+5进
 * 行调整
 * 需要GD库支持,为更好使用本类推荐使用GD库2.0+
 *
 * @author kickflip@php100 QQ263340607
 *************************************************/

 class uploadImg extends uploadFile {

 public $mark_str = 'kickflip@php100';  //水印字符串
 public $str_r = 0; //字符串颜色R
 public $str_g = 0; //字符串颜色G
 public $str_b = 0; //字符串颜色B
 public $mark_ttf = './upload/SIMSUN.TTC'; //水印文字字体文件(包含路径)
 public $mark_logo = './upload/logo.png';    //水印图片
 public $resize_h;//生成缩略图高
 public $resize_w;//生成缩略图宽
 public $source_img;//源图片文件
 public $dst_path = './upload/';//缩略图文件存放目录,不填则为源图片存放目录

 /**
  * 生成缩略图 生成后的图
  * @access public
  * @param integer $w 缩小后图片的宽(px)
  * @param integer $h 缩小后图片的高(px)
  * @param string $source_img 源图片(路径+文件名)
  */
 public function img_resized($w,$h,$source_img = NULL){
  $source_img = $source_img == NULL ? $this->uploaded : $source_img;//取得源文件的地址,如果为空则默认为上次上传的图片
  if(!is_file($source_img)) { //检查源图片是否存在
   $this->errmsg = '文件'.$source_img.'不存在';
   return FALSE;
  }
  $this->source_img = $source_img;
  $img_info = getimagesize($source_img);
  $source = $this->img_create($source_img); //创建源图片
  $this->resize_w = $w;
  $this->resize_h = $h;
  $thumb = imagecreatetruecolor($w,$h);
  imagecopyresized($thumb,$source,0,0,0,0,$w,$h,$img_info[0],$img_info[1]);//生成缩略图片
  $dst_path = $this->dst_path == '' ? $this->save_path : $this->dst_path; //取得目标文件夹路径
  $dst_path = (preg_match('//$/',$dst_path)) ? $dst_path : $dst_path . '/';//将目标文件夹后加上/
  if(!is_dir($dst_path)) $this->set_dir($dst_path); //如果不存在目标文件夹则创建
  $dst_name = $this->set_newname($source_img);
  $this->img_output($thumb,$dst_name);//输出图片
  imagedestroy($source);
  imagedestroy($thumb);
 }

 /**
  *打水印
  *@access public
  *@param string $source_img 源图片路径+文件名
  *@param integer $mark_type 水印类型(1为英文字符串,2为中文字符串,3为图片logo,默认为英文字符串)
  *@param integer $mark_postion 水印位置(1为左下角,2为右下角,3为左上角,4为右上角,默认为右下角);
  *@return 打上水印的图片
  */
 public function img_mark($source_img = NULL,$mark_type = 1,$mark_postion = 2) {
  $source_img = $source_img == NULL ? $this->uploaded : $source_img;//取得源文件的地址,如果为空则默认为上次上传的图片
  if(!is_file($source_img)) { //检查源图片是否存在
   $this->errmsg = '文件'.$source_img.'不存在';
   return FALSE;
  }
  $this->source_img = $source_img;
  $img_info = getimagesize($source_img);
  $source = $this->img_create($source_img); //创建源图片
  $mark_xy = $this->get_mark_xy($mark_postion);//取得水印位置
  $mark_color = imagecolorallocate($source,$this->str_r,$this->str_g,$this->str_b);

  switch($mark_type) {

   case 1 : //加英文字符串水印
   $str = $this->mark_str;
   imagestring($source,5,$mark_xy[0],$mark_xy[1],$str,$mark_color);
   $this->img_output($source,$source_img);
   break;

            case 2 : //加中文字符串水印
            if(!is_file($this->mark_ttf)) { //检查字体文件是否存在
    $this->errmsg = '打水印失败:字体文件'.$this->mark_ttf.'不存在!';
   return FALSE;
   }
   $str = $this->mark_str;
   //$str = iconv('gbk','utf-8',$str);//转换字符编码 如果使用GBK编码请去掉此行注释
   imagettftext($source,12,0,$mark_xy[2],$mark_xy[3],$mark_color,$this->mark_ttf,$str);
   $this->img_output($source,$source_img);
   break;

   case 3 : //加图片水印
   if(is_file($this->mark_logo)){  //如果存在水印logo的图片则取得logo图片的基本信息,不存在则退出
    $logo_info = getimagesize($this->mark_logo);
   }else{
    $this->errmsg = '打水印失败:logo文件'.$this->mark_logo.'不存在!';
    return FALSE;
   }

   $logo_info = getimagesize($this->mark_logo);
   if($logo_info[0]>$img_info[0] || $logo_info[1]>$img_info[1]) { //如果源图片小于logo大小则退出
    $this->errmsg = '打水印失败:源图片'.$this->source_img.'比'.$this->mark_logo.'小!';
    return FALSE;
   }

   $logo = $this->img_create($this->mark_logo);
   imagecopy ( $source, $logo, $mark_xy[4], $mark_xy[5], 0, 0, $logo_info[0], $logo_info[1]);
   $this->img_output($source,$source_img);
   break;

   default: //其它则为文字图片
   $str = $this->mark_str;
   imagestring($source,5,$mark_xy[0],$mark_xy[1],$str,$mark_color);
   $this->img_output($source,$source_img);
   break;
  }
  imagedestroy($source);
 }

 /**
  * 取得水印位置
  * @access private
  * @param integer $mark_postion 水印的位置(1为左下角,2为右下角,3为左上角,4为右上角,其它为右下角)
  * @return array $mark_xy 水印位置的坐标(索引0为英文字符串水印坐标X,索引1为英文字符串水印坐标Y,
  * 索引2为中文字符串水印坐标X,索引3为中文字符串水印坐标Y,索引4为水印图片坐标X,索引5为水印图片坐标Y)
  */
 private function get_mark_xy($mark_postion){
  $img_info = getimagesize($this->source_img);

  $stre_w = strlen($this->mark_str)*9+5 ; //水印英文字符串的长度(px)(5号字的英文字符大小约为9px 为了美观再加5px)
  //(12号字的中文字符大小为12px,在utf8里一个汉字长度为3个字节一个字节4px 而一个英文字符长度一个字节大小大约为9px
  // 为了在中英文混合的情况下显示完全 设它的长度为字节数*7px)
  $strc_w = strlen($this->mark_str)*7+5 ; //水印中文字符串的长度(px)

  if(is_file($this->mark_logo)){ //如果存在水印logo的图片则取得logo图片的基本信息
   $logo_info = getimagesize($this->mark_logo);
  }

  //由于imagestring函数和imagettftext函数中对于字符串开始位置不同所以英文和中文字符串的Y位置也有所不同
  //imagestring函数是从文字的左上角为参照 imagettftext函数是从文字左下角为参照
  switch($mark_postion){

   case 1: //位置左下角
   $mark_xy[0] = 5; //水印英文字符串坐标X
   $mark_xy[1] = $img_info[1]-20;//水印英文字符串坐标Y
   $mark_xy[2] = 5; //水印中文字符串坐标X
   $mark_xy[3] = $img_info[1]-5;//水印中文字符串坐标Y
   $mark_xy[4] = 5;//水印图片坐标X
   $mark_xy[5] = $img_info[1]-$logo_info[1]-5;//水印图片坐标Y
   break;

   case 2: //位置右下角
   $mark_xy[0] = $img_info[0]-$stre_w; //水印英文字符串坐标X
   $mark_xy[1] = $img_info[1]-20;//水印英文字符串坐标Y
   $mark_xy[2] = $img_info[0]-$strc_w; //水印中文字符串坐标X
   $mark_xy[3] = $img_info[1]-5;//水印中文字符串坐标Y
   $mark_xy[4] = $img_info[0]-$logo_info[0]-5;//水印图片坐标X
   $mark_xy[5] = $img_info[1]-$logo_info[1]-5;//水印图片坐标Y
   break;

   case 3: //位置左上角
   $mark_xy[0] = 5; //水印英文字符串坐标X
   $mark_xy[1] = 5;//水印英文字符串坐标Y
   $mark_xy[2] = 5; //水印中文字符串坐标X
   $mark_xy[3] = 15;//水印中文字符串坐标Y
   $mark_xy[4] = 5;//水印图片坐标X
   $mark_xy[5] = 5;//水印图片坐标Y
   break;

   case 4: //位置右上角
   $mark_xy[0] = $img_info[0]-$stre_w; //水印英文字符串坐标X
   $mark_xy[1] = 5;//水印英文字符串坐标Y
   $mark_xy[2] = $img_info[0]-$strc_w; //水印中文字符串坐标X
   $mark_xy[3] = 15;//水印中文字符串坐标Y
   $mark_xy[4] = $img_info[0]-$logo_info[0]-5;//水印图片坐标X
   $mark_xy[5] = 5;//水印图片坐标Y
   break;

   default : //其它默认为右下角
   $mark_xy[0] = $img_info[0]-$stre_w; //水印英文字符串坐标X
   $mark_xy[1] = $img_info[1]-5;//水印英文字符串坐标Y
   $mark_xy[2] = $img_info[0]-$strc_w; //水印中文字符串坐标X
   $mark_xy[3] = $img_info[1]-15;//水印中文字符串坐标Y
   $mark_xy[4] = $img_info[0]-$logo_info[0]-5;//水印图片坐标X
   $mark_xy[5] = $img_info[1]-$logo_info[1]-5;//水印图片坐标Y
   break;
  }
  return $mark_xy;
 }

 /**
  * 创建源图片
  * @access private
  * @param string $source_img 源图片(路径+文件名)
  * @return img 从目标文件新建的图像
  */
 private function img_create($source_img) {
  $info = getimagesize($source_img);
  switch ($info[2]){
            case 1:
            if(!function_exists('imagecreatefromgif')){
             $source = @imagecreatefromjpeg($source_img);
            }else{
             $source = @imagecreatefromgif($source_img);
            }
            break;
            case 2:
            $source = @imagecreatefromjpeg($source_img);
            break;
            case 3:
            $source = @imagecreatefrompng($source_img);
            break;
            case 6:
            $source = @imagecreatefromwbmp($source_img);
            break;
            default:
   $source = FALSE;
   break;
        }
  return $source;
 }

 /**
  * 重命名图片
  * @access private
  * @param string $source_img 源图片路径+文件名
  * @return string $dst_name 重命名后的图片名(路径+文件名)
  */
 private function set_newname($sourse_img) {
  $info = pathinfo($sourse_img);
  $new_name = $this->resize_w.'_'.$this->resize_h.'_'.$info['basename'];//将文件名修改为:宽_高_文件名
  if($this->dst_path == ''){ //如果存放缩略图路径为空则默认为源文件同文件夹
   $dst_name = str_replace($info['basename'],$new_name,$sourse_img);
  }else{
   $dst_name = $this->dst_path.$new_name;
  }
  return $dst_name;
 }

 /**
  * 输出图片
  * @access private
  * @param $im 处理后的图片
  * @param $dst_name 输出后的的图片名(路径+文件名)
  * @return 输出图片
  */
 public function img_output($im,$dst_name) {
  $info = getimagesize($this->source_img);
  switch ($info[2]){
            case 1:
            if(!function_exists('imagegif')){
             imagejpeg($im,$dst_name);
            }else{
             imagegif($im, $dst_name);
            }
            break;
            case 2:
            imagejpeg($im,$dst_name);
            break;
            case 3:
            imagepng($im,$dst_name);
            break;
            case 6:
            imagewbmp($im,$dst_name);
            break;
        }
 }

 }
?>


这个写成了上传文件类就方便多了,把上面代码保存一个文件它就可以公共调用与修改删除了。

[!--infotagslink--]

相关文章

  • ASP.NET购物车实现过程详解

    这篇文章主要为大家详细介绍了ASP.NET购物车的实现过程,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-22
  • C#开发Windows窗体应用程序的简单操作步骤

    这篇文章主要介绍了C#开发Windows窗体应用程序的简单操作步骤,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-04-12
  • C++调用C#的DLL程序实现方法

    本文通过例子,讲述了C++调用C#的DLL程序的方法,作出了以下总结,下面就让我们一起来学习吧。...2020-06-25
  • 微信小程序 页面传值详解

    这篇文章主要介绍了微信小程序 页面传值详解的相关资料,需要的朋友可以参考下...2017-03-13
  • C#使用Process类调用外部exe程序

    本文通过两个示例讲解了一下Process类调用外部应用程序的基本用法,并简单讲解了StartInfo属性,有需要的朋友可以参考一下。...2020-06-25
  • 使用GruntJS构建Web程序之构建篇

    大概有如下步骤 新建项目Bejs 新建文件package.json 新建文件Gruntfile.js 命令行执行grunt任务 一、新建项目Bejs源码放在src下,该目录有两个js文件,selector.js和ajax.js。编译后代码放在dest,这个grunt会...2014-06-07
  • uniapp微信小程序:key失效的解决方法

    这篇文章主要介绍了uniapp微信小程序:key失效的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-01-20
  • 微信小程序二维码生成工具 weapp-qrcode详解

    这篇文章主要介绍了微信小程序 二维码生成工具 weapp-qrcode详解,教大家如何在项目中引入weapp-qrcode.js文件,通过实例代码给大家介绍的非常详细,需要的朋友可以参考下...2021-10-23
  • 将c#编写的程序打包成应用程序的实现步骤分享(安装,卸载) 图文

    时常会写用c#一些程序,但如何将他们和photoshop一样的大型软件打成一个压缩包,以便于发布....2020-06-25
  • PHP常用的小程序代码段

    本文实例讲述了PHP常用的小程序代码段。分享给大家供大家参考,具体如下:1.计算两个时间的相差几天$startdate=strtotime("2009-12-09");$enddate=strtotime("2009-12-05");上面的php时间日期函数strtotime已经把字符串...2015-11-24
  • 微信小程序 网络请求(GET请求)详解

    这篇文章主要介绍了微信小程序 网络请求(GET请求)详解的相关资料,需要的朋友可以参考下...2016-11-22
  • 微信小程序自定义tabbar组件

    这篇文章主要为大家详细介绍了微信小程序自定义tabbar组件,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-03-14
  • js实现跨域的4种实用方法原理分析

    什么是js跨域呐?js跨域是指通过js在不同的域之间进行数据传输或通信,比如用ajax向一个不同的域请求数据,或者通过js获取页面中不同域的框架中(iframe)的数据。只要协议、域名、端口有任何一个不同,都被当作是不同的域。要...2015-10-30
  • 微信小程序如何获取图片宽度与高度

    这篇文章主要给大家介绍了关于微信小程序如何获取图片宽度与高度的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-10
  • JS实现购物车中商品总价计算

    这篇文章主要为大家详细介绍了JS实现购物车中商品总价的计算 ,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-03-07
  • js实现跨域的4种实用方法原理分析

    什么是js跨域呐?js跨域是指通过js在不同的域之间进行数据传输或通信,比如用ajax向一个不同的域请求数据,或者通过js获取页面中不同域的框架中(iframe)的数据。只要协议、域名、端口有任何一个不同,都被当作是不同的域。要...2015-10-30
  • 微信小程序手势操作之单触摸点与多触摸点

    这篇文章主要介绍了微信小程序手势操作之单触摸点与多触摸点的相关资料,需要的朋友可以参考下...2017-03-13
  • 微信小程序(应用号)开发新闻客户端实例

    这篇文章主要介绍了微信小程序(应用号)开发新闻客户端实例的相关资料,需要的朋友可以参考下...2016-10-25
  • Python爬取微信小程序通用方法代码实例详解

    这篇文章主要介绍了Python爬取微信小程序通用方法代码实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-09-29
  • 微信小程序 页面跳转传递值几种方法详解

    这篇文章主要介绍了微信小程序 页面跳转传递值几种方法详解的相关资料,需要的朋友可以参考下...2017-01-16