PHP网页的编码问题

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

Apache和PHP网页的编码问题分析

谈谈Apache和PHP网页的编码。还有一篇关于MySQL字符集的:http://potatows.eeie.cn/?p=39
谈到Apache的编码我们就要涉及到3个东西

http标记语言中的<META http-equiv="content-type" content="text/html; charset=xxx">标签
PHP中的header("content-type:text/html; charset=xxx");函数
Apache配置文件httpd.conf中的AddDefaultCharset
一、<META http-equiv="content-type" content="text/html; charset=xxx">标签
按顺序来,先说这个<META>标签,这个标签有很多功能的,具体请点这里。
我今天想说只是上面提到的那种形式。解释一下<META http-equiv="content-type" content="text/html; charset=utf-8">,意思是对这个网页进行声明,让浏览器对整个页面的内容采用xxx编码,xxx可以为GB2312,GBK,UTF-8(和MySQL不同,MySQL是UTF8)等等。因此,大部分页面可以采用这种方式来告诉浏览器显示这个页面的时候采用什么编码,这样才不会造成编码错误而产生乱码。但是有的时候我们会发现有了这句还是不行,不管xxx是哪一种,浏览器采用的始终都是一种编码,这个情况我后面会谈到。
请注意,<meta>是属于html信息的,仅仅是一个声明,它起作用表明服务器已经把HTML信息传到了浏览器。

二、header("content-type:text/html; charset=xxx");
这个函数header()的作用是把括号里面的信息发到http标头。关于此函数具体用法请点击这里。
如果括号里面的内容为文中所说那样,那作用和<META>标签基本相同,大家对照第一个看发现字符都差不多的。但是不同的是如果有这段函数,浏览器就会永远采用你所要求的xxx编码,绝对不会不听话,因此这个函数是很有用的。为什么会这样呢?那就得说说HTTPS标头和HTML信息的差别了:
引用:
https标头是服务器以HTTP协议传送HTML信息到浏览器前所送出的字串。
因为meta标签是属于html信息的,所以header()发送的内容先到达浏览器,通俗点就是header()的优先级高于meta(不知道可不可以这样讲)。加入一个php页面既有header("content-type:text/html; charset=xxx"),又有<META http-equiv="content-type" content="text/html; charset=xxx">,浏览器就只认前者http标头而不认meta了。当然这个函数只能在php页面内使用。
同样也留有一个问题,为什么前者就绝对起作用,而后者有时候就不行呢?这就是接下来要谈的Apache的原因了。

三、AddDefaultCharset
Apache根目录的conf文件夹里,有整个Apache的配置文档httpd.conf。具体如何配置apache请点击这里([url=thread-2674-1-1.html]windows[/url],[url=thread-1381-1-1.html]linux[/url])。
用文本编辑器打开httpd.conf,第708行(不同版本可能不同)有AddDefaultCharset xxx,xxx为编码名称。这行代码的意思:设置整个服务器内的网页文件https标头里的字符集为你默认的xxx字符集。有这行,就相当于给每个文件都加了一行header("content-type:text/html; charset=xxx")。这下就明白为什么明明meta设置了是utf-8,可浏览器始终采用gb2312的原因。
如果网页里有header("content-type:text/html; charset=xxx"),就把默认的字符集改为你设置的字符集,所以这个函数永远有用。如果把AddDefaultCharset xxx前面加个“#”,注释掉这句,而且页面里不含header("content-type…"),那这个时候就轮到meta标签起作用了。


总结:
来个排序

header("content-type:text/html; charset=xxx")
AddDefaultCharset xxx
<META http-equiv="content-type" content="text/html; charset=xxx">
如果你是web程序员,给你的每个页面都加个header("content-type:text/html; charset=xxx"),保证它在任何服务器都能正确显示,可移植性强。
至于那句AddDefaultCharset xxx,要不要注释就仁者见仁了。反正我是注释掉了,不过我写页子也要写header(),便于放到不同的服务器上能正常显示。

MySQL由于它本身的小巧和操作的高效, 在数据库应用中越来越多的被采用.我在开发一个P2P应用的时候曾经使用MySQL来保存P2P节点,由于P2P的应用中,结点数动辄上万个,而且节点变化频繁,因此一定要保持查询和插入的高效.以下是我在使用过程中做的提高效率的三个有效的尝试.

l
使用statement进行绑定查询
使用statement可以提前构建查询语法树,在查询时不再需要构建语法树就直接查询.因此可以很好的提高查询的效率. 这个方法适合于查询条件固定但查询非常频繁的场合.
使用方法是:

绑定, 创建一个MYSQL_STMT变量,与对应的查询字符串绑定,字符串中的问号代表要传入的变量,每个问号都必须指定一个变量.
查询, 输入每个指定的变量, 传入MYSQL_STMT变量用可用的连接句柄执行.
代码如下:

//1.绑定
bool CDBManager::BindInsertStmt(MYSQL * connecthandle)
{
       //作插入操作的绑定
       MYSQL_BIND insertbind[FEILD_NUM];
       if(m_stInsertParam == NULL)
              m_stInsertParam = new CHostCacheTable;
       m_stInsertStmt = mysql_stmt_init(connecthandle);
       //构建绑定字符串
       char insertSQL[SQL_LENGTH];
       strcpy(insertSQL, "insert into HostCache(SessionID, ChannelID, ISPType, "
              "ExternalIP, ExternalPort, InternalIP, InternalPort) "
              "values(?, ?, ?, ?, ?, ?, ?)");
       mysql_stmt_prepare(m_stInsertStmt, insertSQL, strlen(insertSQL));
       int param_count= mysql_stmt_param_count(m_stInsertStmt);
       if(param_count != FEILD_NUM)
              return false;
       //填充bind结构数组, m_sInsertParam是这个statement关联的结构变量
       memset(insertbind, 0, sizeof(insertbind));
       insertbind[0].buffer_type = MYSQL_TYPE_STRING;
       insertbind[0].buffer_length = ID_LENGTH /* -1 */;
       insertbind[0].buffer = (char *)m_stInsertParam->sessionid;
       insertbind[0].is_null = 0;
       insertbind[0].length = 0;

       insertbind[1].buffer_type = MYSQL_TYPE_STRING;
       insertbind[1].buffer_length = ID_LENGTH /* -1 */;
       insertbind[1].buffer = (char *)m_stInsertParam->channelid;
       insertbind[1].is_null = 0;
       insertbind[1].length = 0;

       insertbind[2].buffer_type = MYSQL_TYPE_TINY;
       insertbind[2].buffer = (char *)&m_stInsertParam->ISPtype;
       insertbind[2].is_null = 0;
       insertbind[2].length = 0;

       insertbind[3].buffer_type = MYSQL_TYPE_LONG;
       insertbind[3].buffer = (char *)&m_stInsertParam->externalIP;
       insertbind[3].is_null = 0;
       insertbind[3].length = 0;


       insertbind[4].buffer_type = MYSQL_TYPE_SHORT;
       insertbind[4].buffer = (char *)&m_stInsertParam->externalPort;
       insertbind[4].is_null = 0;
       insertbind[4].length = 0;

       insertbind[5].buffer_type = MYSQL_TYPE_LONG;
       insertbind[5].buffer = (char *)&m_stInsertParam->internalIP;
       insertbind[5].is_null = 0;
       insertbind[5].length = 0;

       insertbind[6].buffer_type = MYSQL_TYPE_SHORT;
       insertbind[6].buffer = (char *)&m_stInsertParam->internalPort;
       insertbind[6].is_null = 0;
       insertbind[6].is_null = 0;
       //绑定
       if (mysql_stmt_bind_param(m_stInsertStmt, insertbind))
              return false;
       return true;
}

//2.查询
bool CDBManager::InsertHostCache2(MYSQL * connecthandle, char * sessionid, char * channelid, int ISPtype, \
              unsigned int eIP, unsigned short eport, unsigned int iIP, unsigned short iport)
{
       //填充结构变量m_sInsertParam
       strcpy(m_stInsertParam->sessionid, sessionid);
       strcpy(m_stInsertParam->channelid, channelid);
       m_stInsertParam->ISPtype = ISPtype;
       m_stInsertParam->externalIP = eIP;
       m_stInsertParam->externalPort = eport;
       m_stInsertParam->internalIP = iIP;
       m_stInsertParam->internalPort = iport;
       //执行statement,性能瓶颈处
       if(mysql_stmt_execute(m_stInsertStmt))
              return false;
       return true;
}

l
随机的获取记录
在某些数据库的应用中, 我们并不是要获取所有的满足条件的记录,而只是要随机挑选出满足条件的记录. 这种情况常见于数据业务的统计分析,从大容量数据库中获取小量的数据的场合.

有两种方法可以做到
1.       常规方法,首先查询出所有满足条件的记录,然后随机的挑选出部分记录.这种方法在满足条件的记录数很多时效果不理想.
2.       使用limit语法,先获取满足条件的记录条数, 然后在sql查询语句中加入limit来限制只查询满足要求的一段记录. 这种方法虽然要查询两次,但是在数据量大时反而比较高效.
示例代码如下:

//1.常规的方法
//性能瓶颈,10万条记录时,执行查询140ms, 获取结果集500ms,其余可忽略
int CDBManager::QueryHostCache(MYSQL* connecthandle, char * channelid, int ISPtype, CDBManager::CHostCacheTable * &hostcache)
{

       char selectSQL[SQL_LENGTH];
       memset(selectSQL, 0, sizeof(selectSQL));
       sprintf(selectSQL,"select * from HostCache where ChannelID = '%s' and ISPtype = %d", channelid, ISPtype);
       if(mysql_real_query(connecthandle, selectSQL, strlen(selectSQL)) != 0)   //检索
              return 0;
       //获取结果集
       m_pResultSet = mysql_store_result(connecthandle);
       if(!m_pResultSet)   //获取结果集出错
              return 0;
       int iAllNumRows = (int)(mysql_num_rows(m_pResultSet));      ///<所有的搜索结果数
       //计算待返回的结果数
       int iReturnNumRows = (iAllNumRows <= RETURN_QUERY_HOST_NUM)? iAllNumRows:RETURN_QUERY_HOST_NUM;
       if(iReturnNumRows <= RETURN_QUERY_HOST_NUM)
       {
              //获取逐条记录
              for(int i = 0; i<iReturnNumRows; i++)
              {
                     //获取逐个字段
                     m_Row = mysql_fetch_row(m_pResultSet);
                     if(m_Row[0] != NULL)
                            strcpy(hostcache.sessionid, m_Row[0]);
                     if(m_Row[1] != NULL)
                            strcpy(hostcache.channelid, m_Row[1]);
                     if(m_Row[2] != NULL)
                            hostcache.ISPtype      = atoi(m_Row[2]);
                     if(m_Row[3] != NULL)
                            hostcache.externalIP   = atoi(m_Row[3]);
                     if(m_Row[4] != NULL)
                            hostcache.externalPort = atoi(m_Row[4]);
                     if(m_Row[5] != NULL)
                            hostcache.internalIP   = atoi(m_Row[5]);
                     if(m_Row[6] != NULL)
                            hostcache.internalPort = atoi(m_Row[6]);             
              }
       }
       else
       {
              //随机的挑选指定条记录返回
              int iRemainder = iAllNumRows%iReturnNumRows;    ///<余数
              int iQuotient = iAllNumRows/iReturnNumRows;      ///<商
              int iStartIndex = rand()%(iRemainder + 1);         ///<开始下标

              //获取逐条记录
        for(int iSelectedIndex = 0; iSelectedIndex < iReturnNumRows; iSelectedIndex++)
        {
                            mysql_data_seek(m_pResultSet, iStartIndex + iQuotient * iSelectedIndex);
                            m_Row = mysql_fetch_row(m_pResultSet);
                  if(m_Row[0] != NULL)
                       strcpy(hostcache[iSelectedIndex].sessionid, m_Row[0]);
                   if(m_Row[1] != NULL)
                                   strcpy(hostcache[iSelectedIndex].channelid, m_Row[1]);
                   if(m_Row[2] != NULL)
                       hostcache[iSelectedIndex].ISPtype      = atoi(m_Row[2]);
                   if(m_Row[3] != NULL)
                       hostcache[iSelectedIndex].externalIP   = atoi(m_Row[3]);
                    if(m_Row[4] != NULL)
                       hostcache[iSelectedIndex].externalPort = atoi(m_Row[4]);
                   if(m_Row[5] != NULL)
                       hostcache[iSelectedIndex].internalIP   = atoi(m_Row[5]);
                   if(m_Row[6] != NULL)
                       hostcache[iSelectedIndex].internalPort = atoi(m_Row[6]);
        }
      }
       //释放结果集内容
       mysql_free_result(m_pResultSet);
       return iReturnNumRows;
}

//2.使用limit版
int CDBManager::QueryHostCache(MYSQL * connecthandle, char * channelid, unsigned int myexternalip, int ISPtype, CHostCacheTable * hostcache)
{
       //首先获取满足结果的记录条数,再使用limit随机选择指定条记录返回
       MYSQL_ROW row;
       MYSQL_RES * pResultSet;
       char selectSQL[SQL_LENGTH];
       memset(selectSQL, 0, sizeof(selectSQL));

       sprintf(selectSQL,"select count(*) from HostCache where ChannelID = '%s' and ISPtype = %d", channelid, ISPtype);
       if(mysql_real_query(connecthandle, selectSQL, strlen(selectSQL)) != 0)   //检索
              return 0;
       pResultSet = mysql_store_result(connecthandle);
       if(!pResultSet)      
              return 0;
       row = mysql_fetch_row(pResultSet);
       int iAllNumRows = atoi(row[0]);
       mysql_free_result(pResultSet);
       //计算待取记录的上下范围
       int iLimitLower = (iAllNumRows <= RETURN_QUERY_HOST_NUM)?
              0:(rand()%(iAllNumRows - RETURN_QUERY_HOST_NUM));
       int iLimitUpper = (iAllNumRows <= RETURN_QUERY_HOST_NUM)?
              iAllNumRows:(iLimitLower + RETURN_QUERY_HOST_NUM);
       //计算待返回的结果数
       int iReturnNumRows = (iAllNumRows <= RETURN_QUERY_HOST_NUM)?
               iAllNumRows:RETURN_QUERY_HOST_NUM;


       //使用limit作查询
       sprintf(selectSQL,"select SessionID, ExternalIP, ExternalPort, InternalIP, InternalPort "
              "from HostCache where ChannelID = '%s' and ISPtype = %d limit %d, %d"
              , channelid, ISPtype, iLimitLower, iLimitUpper);
       if(mysql_real_query(connecthandle, selectSQL, strlen(selectSQL)) != 0)   //检索
              return 0;
       pResultSet = mysql_store_result(connecthandle);
       if(!pResultSet)
              return 0;
       //获取逐条记录
       for(int i = 0; i<iReturnNumRows; i++)
       {
              //获取逐个字段
              row = mysql_fetch_row(pResultSet);
              if(row[0] != NULL)
                     strcpy(hostcache.sessionid, row[0]);
              if(row[1] != NULL)
                     hostcache.externalIP   = atoi(row[1]);
              if(row[2] != NULL)
                     hostcache.externalPort = atoi(row[2]);
              if(row[3] != NULL)
                     hostcache.internalIP   = atoi(row[3]);
              if(row[4] != NULL)
                     hostcache.internalPort = atoi(row[4]);            
       }
       //释放结果集内容
       mysql_free_result(pResultSet);
       return iReturnNumRows;
}

l
使用连接池管理连接.
在有大量节点访问的数据库设计中,经常要使用到连接池来管理所有的连接.
一般方法是:建立两个连接句柄队列,空闲的等待使用的队列和正在使用的队列.
当要查询时先从空闲队列中获取一个句柄,插入到正在使用的队列,再用这个句柄做数据库操作,完毕后一定要从使用队列中删除,再插入到空闲队列.
设计代码如下:

//定义句柄队列
typedef std::list<MYSQL *> CONNECTION_HANDLE_LIST;
typedef std::list<MYSQL *>::iterator CONNECTION_HANDLE_LIST_IT;

//连接数据库的参数结构
class CDBParameter

{
public:
       char *host;                                 ///<主机名
       char *user;                                 ///<用户名
       char *password;                         ///<密码
       char *database;                           ///<数据库名
       unsigned int port;                 ///<端口,一般为0
       const char *unix_socket;      ///<套接字,一般为NULL
       unsigned int client_flag; ///<一般为0
};

//创建两个队列
CONNECTION_HANDLE_LIST m_lsBusyList;                ///<正在使用的连接句柄
CONNECTION_HANDLE_LIST m_lsIdleList;                  ///<未使用的连接句柄

//所有的连接句柄先连上数据库,加入到空闲队列中,等待使用.
bool CDBManager::Connect(char * host /* = "localhost" */, char * user /* = "chenmin" */, \
                                           char * password /* = "chenmin" */, char * database /* = "HostCache" */)
{
       CDBParameter * lpDBParam = new CDBParameter();
       lpDBParam->host = host;
       lpDBParam->user = user;
       lpDBParam->password = password;
       lpDBParam->database = database;
       lpDBParam->port = 0;
       lpDBParam->unix_socket = NULL;
       lpDBParam->client_flag = 0;
       try
       {
              //连接
              for(int index = 0; index < CONNECTION_NUM; index++)
              {
                     MYSQL * pConnectHandle = mysql_init((MYSQL*) 0);     //初始化连接句柄
                     if(!mysql_real_connect(pConnectHandle, lpDBParam->host, lpDBParam->user, lpDBParam->password,\
       lpDBParam->database,lpDBParam->port,lpDBParam->unix_socket,lpDBParam->client_fla))
                            return false;
//加入到空闲队列中
                     m_lsIdleList.push_back(pConnectHandle);
              }
       }
       catch(...)
       {
              return false;
       }
       return true;
}

//提取一个空闲句柄供使用
MYSQL * CDBManager::GetIdleConnectHandle()
{
       MYSQL * pConnectHandle = NULL;
       m_ListMutex.acquire();
       if(m_lsIdleList.size())
       {
              pConnectHandle = m_lsIdleList.front();      
              m_lsIdleList.pop_front();
              m_lsBusyList.push_back(pConnectHandle);
       }
       else //特殊情况,闲队列中为空,返回为空
       {
              pConnectHandle = 0;
       }
       m_ListMutex.release();

       return pConnectHandle;
}

//从使用队列中释放一个使用完毕的句柄,插入到空闲队列
void CDBManager::SetIdleConnectHandle(MYSQL * connecthandle)
{
       m_ListMutex.acquire();
       m_lsBusyList.remove(connecthandle);
       m_lsIdleList.push_back(connecthandle);
       m_ListMutex.release();
}
//使用示例,首先获取空闲句柄,利用这个句柄做真正的操作,然后再插回到空闲队列
bool CDBManager::DeleteHostCacheBySessionID(char * sessionid)
{
       MYSQL * pConnectHandle = GetIdleConnectHandle();
       if(!pConnectHandle)
              return 0;
       bool bRet = DeleteHostCacheBySessionID(pConnectHandle, sessionid);
       SetIdleConnectHandle(pConnectHandle);
       return bRet;
}
//传入空闲的句柄,做真正的删除操作
bool CDBManager::DeleteHostCacheBySessionID(MYSQL * connecthandle, char * sessionid)
{
       char deleteSQL[SQL_LENGTH];
       memset(deleteSQL, 0, sizeof(deleteSQL));
       sprintf(deleteSQL,"delete from HostCache where SessionID = '%s'", sessionid);
       if(mysql_query(connecthandle,deleteSQL) != 0) //删除
              return false;
       return true;
}

增加中文水印
<?php
/*-------------------------------------------------------------
**描述:这是用于给指定图片加底部水印(不占用图片显示区域)的自定义类,需创建对象调用
**版本:v1.0
**创建:2007-10-09
**更新:2007-10-09
**人员:老肥牛([email]fatkenme@163.com[/email]  QQ:70177108)
**说明:1、需要gd库支持,需要iconv支持(php5已经包含不用加载)
        2、只适合三种类型的图片,jpg/jpeg/gif/png,其它类型不处理
        3、注意图片所在目录的属性必须可写
        4、调用范例:
            $objImg = new MyWaterDownChinese();
            $objImg->Path = "images/";
            $objImg->FileName = "1.jpg";
            $objImg->Text = "胖胖交友网 [url]www.ppfriend.com[/url]";
            $objImg->Font = "./font/simhei.ttf";
            $objImg->Run();
**成员函数:
----------------------------------------------------------------*/
class MyWaterDownChinese{
          var $Path = "./";  //图片所在目录相对于调用此类的页面的相对路径
          var $FileName = ""; //图片的名字,如“1.jpg”
          var $Text = "";   //图片要加上的水印文字,支持中文
          var $TextColor = "#ffffff"; //文字的颜色,gif图片时,字体颜色只能为黑色
          var $TextBgColor = "#000000"; //文字的背景条的颜色
          var $Font = "c://windows//fonts//simhei.ttf"; //字体的存放目录,相对路径
          var $OverFlag = true; //是否要覆盖原图,默认为覆盖,不覆盖时,自动在原图文件名后+"_water_down",如“1.jpg”=> "1_water_down.jpg"
          var $BaseWidth = 200; //图片的宽度至少要>=200,才会加上水印文字。
        
//------------------------------------------------------------------
//功能:类的构造函数(php5.0以上的形式)
//参数:无
//返回:无
function __construct(){;}

//------------------------------------------------------------------
//功能:类的析构函数(php5.0以上的形式)
//参数:无
//返回:无
function __destruct(){;}
//------------------------------------------------------------------

//------------------------------------
//功能:对象运行函数,给图片加上水印
//参数:无
//返回:无
function Run()
{
    if($this->FileName == "" || $this->Text == "")
        return;
    //检测是否安装GD库
    if(false == function_exists("gd_info"))
    {
        echo "系统没有安装GD库,不能给图片加水印.";
        return;
    }
    //设置输入、输出图片路径名
    $arr_in_name = explode(".",$this->FileName);
    //
    $inImg = $this->Path.$this->FileName;
    $outImg = $inImg;
    $tmpImg = $this->Path.$arr_in_name[0]."_tmp.".$arr_in_name[1]; //临时处理的图片,很重要
    if(!$this->OverFlag)
        $outImg = $this->Path.$arr_in_name[0]."_water_down.".$arr_in_name[1];
    //检测图片是否存在
    if(!file_exists($inImg))
        return ;
    //获得图片的属性
    $groundImageType = @getimagesize($inImg);
    $imgWidth = $groundImageType[0];
    $imgHeight = $groundImageType[1];
    $imgType = $groundImageType[2];
    if($imgWidth < $this->BaseWidth)  //小于基本宽度,不处理
        return;
   
    //图片不是jpg/jpeg/gif/png时,不处理
    switch($imgType)
    {
         case 1:
              $image = imagecreatefromgif($inImg);
              $this->TextBgColor = "#ffffff"; //gif图片字体只能为黑,所以背景颜色就设置为白色
              break; 
         case 2:
              $image = imagecreatefromjpeg($inImg);
              break; 
         case 3:
              $image = imagecreatefrompng($inImg);
              break; 
         default:
              return;
              break;
    }
    //创建颜色
    $color = @imagecolorallocate($image,hexdec(substr($this->TextColor,1,2)),hexdec(substr($this->TextColor,3,2)),hexdec(substr($this->TextColor,5,2))); //文字颜色
    //生成一个空的图片,它的高度在底部增加水印高度
    $newHeight = $imgHeight+20;
    $objTmpImg = @imagecreatetruecolor($imgWidth,$newHeight);
    $colorBg = @imagecolorallocate($objTmpImg,hexdec(substr($this->TextBgColor,1,2)),hexdec(substr($this->TextBgColor,3,2)),hexdec(substr($this->TextBgColor,5,2))); //背景颜色   
    //填充图片的背景颜色
    @imagefill ($objTmpImg,0,0,$colorBg);
    //把原图copy到临时图片中
    @imagecopy($objTmpImg,$image,0,0,0,0,$imgWidth,$imgHeight);
    //创建要写入的水印文字对象
    $objText = $this->createText($this->Text);
    //计算要写入的水印文字的位置
    $x = 5;
    $y = $newHeight-5;
    //写入文字水印
    @imagettftext($objTmpImg,10,0,$x,$y,$color,$this->Font,$objText);   
    //生成新的图片,临时图片
    switch($imgType)
    {
         case 1:
              imagegif($objTmpImg,$tmpImg);
              break; 
         case 2:
              imagejpeg($objTmpImg,$tmpImg);
              break; 
         case 3:
              imagepng($objTmpImg,$tmpImg);
              break; 
         default:
              return;
              break;
    }   
    //释放资源
    @imagedestroy($objTmpImg);
    @imagedestroy($image);
    //重新命名文件
    if($this->OverFlag)
    {
        //覆盖原图
        @unlink($inImg);
        @rename($tmpImg,$outImg);
    }
    else
    {
        //不覆盖原图
        @rename($tmpImg,$outImg);
    }
}

//--------------------------------------
//功能:创建水印文字对象
//参数:无
//返回:创建的水印文字对象
function createText($instring)
{
   $outstring="";
   $max=strlen($instring);
   for($i=0;$i<$max;$i++)
   {
       $h=ord($instring[$i]);
       if($h>=160 && $i<$max-1)
       {
           $outstring .= "&#".base_convert(bin2hex(iconv("gb2312","ucs-2",substr($instring,$i,2))),16,10).";";
           $i++;
       }
       else
       {
           $outstring .= $instring[$i];
       }
   }
   return $outstring;
}

}//class
?>

 


<?php
$ch 
curl_init
();
curl_setopt($chCURLOPT_URL'http://www.111cn.net'
);
curl_setopt($chCURLOPT_HEADERtrue
);
curl_setopt($chCURLOPT_RETURNTRANSFER1
);
curl_setopt($chCURLOPT_NOBODYtrue
);
$order curl_exec($ch
);
echo 
''
;
echo 
strip_tags($order
);
echo 
''
;
curl_close($ch);?>


有的服务器是看不到了,原因要根据服务器的配置而定了,在这里我就不多说了.

$f_id =isset($_GET['id'])?$_GET['id']:'';
$t_id =isset($_GET['tid'])?$_GET['tid']:'';
$t_na =($t_id==1)?"su_photo":"su_video";
if($t_id==1){
$t_na='su_photo';
}else if($t_id==2){
$t_na='su_video';
}else{
$t_na='su_cert';
}
$sql ="select * from $t_na where id=$f_id and uid='".$_SESSION['xm']."' ";
$result =mysql_query($sql) or exit("system busy...");
if(!mysql_num_rows($result)){exit("
alert('记录不存在!');history.back();
");}
$rs =mysql_fetch_object($result);
$file_name=substr($rs->path,strrpos($rs->path,"/")+1);
$file_dir =substr($rs->path,0,strlen($rs->path)-strlen($file_name));
$file_dir=realpath(str_replace('../','',$file_dir))."\\";
$rpath=$file_dir.$file_name;
if (!file_exists($rpath)) { //检查文件是否存在
exit("
alert('文件找不到!');history.back();
");
} else {
$tent=substr($rpath,strrpos($rpath,".")+1);
$file = fopen($rpath,"r"); // 打开文件
Header("Content-type: ".headertype($tent)."");
Header("Accept-Ranges: bytes");
Header("Accept-Length: ".filesize($file_dir . $file_name));
Header("Content-Disposition: attachment; filename=" . $file_name);
echo fread($file,filesize($file_dir . $file_name));
fclose($file);
exit("
alert('下载完毕!');history.back();
");
}
function headertype($type){
switch($type){
case 'gif':
return 'image/gif';
break;
case 'jpg':
return 'image/pjpeg';
break;
case 'bmp':
return 'image/bmp';
break;
case 'png':
return 'image/x-png';
break;
case 'txt':
return 'application/octet-stream';
break;
case 'zip':
return 'application/x-zip-compressed';
break;
case 'rar':
return 'application/x-rar-compressed';
break;
case 'doc':
return 'application/msword';
break;
case 'swf':
return 'application/x-shockwave-flash';
break;
case 'wma':
return 'audio/x-ms-wma';
break;
case 'rm':
return "application/vnd.rn-realmedia";
break;
case 'mp3':
return "audio/mp3";
break;
default:
return 'text/plain';
}
}
?>

[!--infotagslink--]

相关文章

  • PHP传值到不同页面的三种常见方式及php和html之间传值问题

    在项目开发中经常见到不同页面之间传值在web工作中,本篇文章给大家列出了三种常见的方式。接触PHP也有几个月了,本文总结一下这段日子中,在编程过程里常用的3种不同页面传值方法,希望可以给大家参考。有什么意见也希望大...2015-11-24
  • js修改input的type属性问题探讨

    js修改input的type属性有些限制。当input元素还未插入文档流之前,是可以修改它的值的,在ie和ff下都没问题。但如果input已经存在于页面,其type属性在ie下就成了只读属性了,不可以修改。...2013-10-19
  • Mysql常见问题集锦

    1,utf8_bin跟utf8_general_ci的区别 ci是 case insensitive, 即 "大小写不敏感", a 和 A 会在字符判断中会被当做一样的; bin 是二进制, a 和 A 会别区别对待. 例如你运行: SELECT * FROM table WHERE txt = 'a'...2013-10-04
  • Mysql大小写敏感的问题

    一、1 CREATE TABLE NAME(name VARCHAR(10)); 对这个表,缺省情况下,下面两个查询的结果是一样的:复制代码 代码如下: SELECT * FROM TABLE NAME WHERE name='clip'; SELECT * FROM TABLE NAME WH...2015-03-15
  • php根据用户语言跳转相应网页

    当来访者浏览器语言是中文就进入中文版面,国外的用户默认浏览器不是中文的就跳转英文页面。 <&#63;php $lan = substr(&#8194;$HTTP_ACCEPT_LANGUAGE,0,5); if ($lan == "zh-cn") print("<meta http-equiv='refresh' c...2015-11-08
  • linux mint 下mysql中文支持问题

    一.mysql默认不支持中文,它的server和db默认是latin1编码.所以我们要将其改变为utf-8编码,因为utf-8包含了地球上大部分语言的二进制编码 1.关闭mysql服务 sudo /etc/init.d/mysql stop 2.修改mysql配置文件 mysql配...2015-10-21
  • 腾讯视频怎么放到自己的网页上?

    腾讯视频怎么放到自己的网页上?这个问题是一个基本的问题,要把腾讯视频放到自己的网页有许多的办法,当然一般情况就是直接使用它们的网页代码了,如果你要下载资源再放到...2016-09-20
  • 基于JavaScript实现网页倒计时自动跳转代码

    这篇文章主要介绍了基于JavaScript实现网页倒计时自动跳转代码 的相关资料,需要的朋友可以参考下...2015-12-29
  • 网页头部声明lang=”zh-cn”、lang=“zh”、lang=“zh-cmn-Hans”区别

    我们现在使用的软件都会自动在前面加一个申明了,那么在网页头部声明lang=”zh-cn”、lang=“zh”、lang=“zh-cmn-Hans”区别是什么呢?下面我们就一起来看看吧. 单...2016-09-20
  • c#字符串编码编码(encoding)使用方法示例

    System.Text提供了Encoding的抽象类,这个类提供字符串编码的方法。使Unicode字符数组的字符串,转换为指定编码的字节数组,或者反之,看下面的例子...2020-06-25
  • C#使用队列(Queue)解决简单的并发问题

    这篇文章主要介绍了使用队列(Queue)解决简单的并发问题,讲解的很细致,喜欢的朋友们可以了解一下...2020-06-25
  • 通过javascript进行UTF-8编码的实现方法

    下面小编就为大家带来一篇通过javascript进行UTF-8编码的实现方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2016-07-01
  • php中把unicode编码转化为中文

    小编在网上看到最多的就是汉字转换unicode编码了,今天我们看到一个反过来的操作就是把unicode转换成中文了,下面一起来看看 这两天帮别人开发微信平台好友板块,存...2016-11-25
  • .Net(c#)汉字和Unicode编码互相转换实例

    下面小编就为大家带来一篇.Net(c#)汉字和Unicode编码互相转换实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • windows 10 安装和使用中5个常见问题

    2015年7月29日0点起,Windows 10推送全面开启,Windows7、Windows8.1用户可以免费升级到Windows 10,用户也可以通过系统升级到Windows10,在这过程中,用户会遇到这样那样的问题,下面小编总结了windows 10 安装和使用中5个常见问题,需要的朋友可以参考下...2016-01-27
  • C#实现Winform中打开网页页面的方法

    这篇文章主要介绍了C#实现Winform中打开网页页面的方法,涉及WinForm中WebBrowser的相关使用技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • php中session常见问题分析

    PHP的session功能,一直为许多的初学者为难。就连有些老手,有时都被搞得莫名其妙。本文,将这些问题,做一个简单的汇总,以便大家查阅。 1. 错误提示 引用 代...2016-11-25
  • javascript学习指南之回调问题

    回调函数被认为是一种高级函数,一种被作为参数传递给另一个函数(在这称作"otherFunction")的高级函数,回调函数会在otherFunction内被调用(或执行)。回调函数的本质是一种模式(一种解决常见问题的模式),因此回调函数也被称为回调模式。...2016-04-25
  • Go语言通过http抓取网页的方法

    这篇文章主要介绍了Go语言通过http抓取网页的方法,实例分析了Go语言通过http操作页面的技巧,需要的朋友可以参考下...2020-05-05
  • R语言变量重编码、重命名的操作

    这篇文章主要介绍了R语言变量重编码、重命名的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-05-06