当前位置:  编程技术>php
本页文章导读:
    ▪php 备份数据库代码(生成word,excel,json,xml,sql)       单表备份代码: 代码如下:<?php    class Db    {        var $conn;        function Db($host="localhost",$user="root",$pass="root",$db="test")        {          if(!$this->conn=mysql_connect($host,$user,$.........
    ▪PHP获取MSN好友列表类的实现代码       代码如下:<?phperror_reporting(7);class msn{    private $startcomm = 0;    private $username = '';    private $password = '';    private $commend = '';    private $domain = '';    private $socket = '';    private $challeng.........
    ▪使用php统计字符串中中英文字符的个数       代码如下:<?phpecho $str = "43fdf测试fdsfadaf43543543职工问防盗锁防盗锁5345gfdgd";preg_match_all("/[0-9]{1}/",$str,$arrNum);preg_match_all("/[a-zA-Z]{1}/",$str,$arrAl);preg_match_all("/([/x{4e00}-/x{9fa5}]){1}/u",$str,$arrCh);echo ".........

[1]php 备份数据库代码(生成word,excel,json,xml,sql)
    来源: 互联网  发布时间: 2013-11-30
单表备份
代码:
代码如下:

<?php   
class Db   
{   
    var $conn;   

    function Db($host="localhost",$user="root",$pass="root",$db="test")   
    {   
      if(!$this->conn=mysql_connect($host,$user,$pass))   
      die("can't connect to mysql sever");   
      mysql_select_db($db,$this->conn);   
      mysql_query("SET NAMES 'UTF-8'");   
    }   

    function execute($sql)   
    {   
       return mysql_query($sql,$this->conn);   
    }   

    function findCount($sql)   
    {   
        $result=$this->execute($sql);   
        return mysql_num_rows($result);   
    }   

    function findBySql($sql)   
    {   
        $array=array();   
        $result=mysql_query($sql);   
        $i=0;   
        while($row=mysql_fetch_assoc($result))   
           {   
          $array[$i]=$row;    
       $i++;   
           }   
        return $array;   
    }   

    //$con的几种情况   
    //空:返回全部记录   
    //array:eg. array('id'=>'1') 返回id=1的记录   
    //string :eg. 'id=1' 返回id=1的记录   
    function toExtJson($table,$start="0",$limit="10",$cons="")   
    {   
       $sql=$this->generateSql($table,$cons);   
       $totalNum=$this->findCount($sql);   
       $result=$this->findBySql($sql." LIMIT ".$start." ,".$limit);   
       $resultNum = count($result);//当前结果数   
      $str="";   
      $str.= "{";   
      $str.= "'totalCount':'$totalNum',";   
      $str.="'rows':";   
      $str.="[";   
      for($i=0;$i<$resultNum;$i++){   
       $str.="{";    
       $count=count($result[$i]);   
       $j=1;   
       foreach($result[$i] as $key=>$val)   
       {   
       if($j<$count)   
       {   
       $str.="'".$key."':'".$val."',";   
       }   
       elseif($j==$count)   
       {   
       $str.="'".$key."':'".$val."'";   
       }   
       $j++;   
                }   

       $str.="}";   
       if ($i != $resultNum-1) {   
                 $str.= ",";   
             }   
      }   
      $str.="]";   
      $str.="}";   
      return $str;     
    }   

    function generateSql($table,$cons)   
    {   
        $sql="";//sql条件   
       $sql="select * from ".$table;   
       if($cons!="")   
       {   
       if(is_array($cons))   
       {   
         $k=0;   
         foreach($cons as $key=>$val)   
      {   
      if($k==0)   
      {   
      $sql.="where '";   
      $sql.=$key;   
      $sql.="'='";   
      $sql.=$val."'";   
      }else 
      {   
      $sql.="and '";   
      $sql.=$key;   
      $sql.="'='";   
      $sql.=$val."'";   
      }   
      $k++;   
      }   
       }else 
       {   
       $sql.=" where ".$cons;   
       }   
       }   
       return $sql;   
    }   

    function toExtXml($table,$start="0",$limit="10",$cons="")   
    {   
       $sql=$this->generateSql($table,$cons);   
       $totalNum=$this->findCount($sql);   
       $result=$this->findBySql($sql." LIMIT ".$start." ,".$limit);   
       $resultNum = count($result);//当前结果数   
       header("Content-Type: text/xml");   
       $xml="<?xml version=\"1.0\"  encoding=\"utf-8\" ?>\n";   
       $xml.="<xml>\n";   
       $xml.="\t<totalCount>".$totalNum."</totalCount>\n";   
       $xml.="\t<items>\n";   
       for($i=0;$i<$resultNum;$i++){   
       $xml.="\t\t<item>\n";   
       foreach($result[$i] as $key=>$val)   
       $xml.="\t\t\t<".$key.">".$val."</".$key.">\n";   
       $xml.="\t\t</item>\n";   
       }   
        $xml.="\t</items>\n";   
        $xml.="</xml>\n";   
        return $xml;   
    }   

    //输出word表格   
    function toWord($table,$mapping,$fileName)   
    {   
       header('Content-type: application/doc');    
          header('Content-Disposition: attachment; filename="'.$fileName.'.doc"');    
          echo '<html xmlns:o="urn:schemas-microsoft-com:office:office"   
           xmlns:w="urn:schemas-microsoft-com:office:word"   
           xmlns="[url=http://www.w3.org/TR/REC-html40]http://www.w3.org/TR/REC-html40[/url]">   
        <head>   
           <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />   
        <title>'.$fileName.'</title>   
        </head>   
        <body>';    
        echo'<table border=1><tr>';   
        if(is_array($mapping))   
        {   
          foreach($mapping as $key=>$val)   
       echo'<td>'.$val.'</td>';   
        }   
        echo'</tr>';   
        $results=$this->findBySql('select * from '.$table);   
        foreach($results as $result)   
        {   
          echo'<tr>';   
          foreach($result as $key=>$val)   
       echo'<td>'.$val.'</td>';   
       echo'</tr>';   
        }   
        echo'</table>';   
        echo'</body>';   
        echo'</html>';   
    }   

    function toExcel($table,$mapping,$fileName)   
    {   
      header("Content-type:application/vnd.ms-excel");   
         header("Content-Disposition:filename=".$fileName.".xls");   
      echo'<html xmlns:o="urn:schemas-microsoft-com:office:office" 
           xmlns:x="urn:schemas-microsoft-com:office:excel" 
           xmlns="[url=http://www.w3.org/TR/REC-html40]http://www.w3.org/TR/REC-html40[/url]">   
           <head>   
           <meta http-equiv="expires" content="Mon, 06 Jan 1999 00:00:01 GMT">   
           <meta http-equiv=Content-Type content="text/html; charset=iso-8859-1">   
           <!--[if gte mso 9]><xml>   
           <x:ExcelWorkbook>   
               <x:ExcelWorksheets>   
                       <x:ExcelWorksheet>   
                           <x:Name></x:Name>   
                           <x:WorksheetOptions>   
                               <x:DisplayGridlines/>   
                           </x:WorksheetOptions>   
                       </x:ExcelWorksheet>   
               </x:ExcelWorksheets>   
           </x:ExcelWorkbook>   
           </xml><![endif]-->   
           </head>   
        <body link=blue vlink=purple leftmargin=0 topmargin=0>';    
        echo'<table width="100%" border="0" cellspacing="0" cellpadding="0">';   
           echo'<tr>';   
        if(is_array($mapping))   
        {   
          foreach($mapping as $key=>$val)   
       echo'<td>'.$val.'</td>';   
        }   
        echo'</tr>';   
        $results=$this->findBySql('select * from '.$table);   
        foreach($results as $result)   
        {   
          echo'<tr>';   
          foreach($result as $key=>$val)   
       echo'<td>'.$val.'</td>';   
       echo'</tr>';   
        }   
        echo'</table>';   
        echo'</body>';   
        echo'</html>';   
    }   

    function Backup($table)   
    {   
      if(is_array ($table))   
      {   
       $str="";   
       foreach($table as $tab)   
       $str.=$this->get_table_content($tab);   
       return $str;   
      }else{   
       return $this->get_table_content($table);   
      }   
    }   

    function Backuptofile($table,$file)   
    {   
      header("Content-disposition: filename=$file.sql");//所保存的文件名   
      header("Content-type: application/octetstream");   
      header("Pragma: no-cache");   
      header("Expires: 0");   
      if(is_array ($table))   
      {   
       $str="";   
       foreach($table as $tab)   
       $str.=$this->get_table_content($tab);   
       echo $str;   
      }else{   
       echo $this->get_table_content($table);   
      }   
    }   

    function Restore($table,$file="",$content="")   
    {   
      //排除file,content都为空或者都不为空的情况   
      if(($file==""&&$content=="")||($file!=""&&$content!=""))   
      echo"参数错误";   
      $this->truncate($table);   
      if($file!="")   
      {   
       if($this->RestoreFromFile($file))   
       return true;   
       else 
       return false;   
      }   
      if($content!="")   
      {   
       if($this->RestoreFromContent($content))   
       return true;   
       else 
       return false;   
      }   
    }   

    //清空表,以便恢复数据   
    function truncate($table)   
    {   
      if(is_array ($table))   
      {   
       $str="";   
       foreach($table as $tab)   
       $this->execute("TRUNCATE TABLE $tab");   
      }else{   
       $this->execute("TRUNCATE TABLE $table");   
      }   
    }   

    function get_table_content($table)   
    {   
      $results=$this->findBySql("select * from $table");   
      $temp = "";   
      $crlf="<br>";   
      foreach($results as $result)   
      {   

       /*(";  
      foreach($result as $key=>$val)  
      {  
       $schema_insert .= " `".$key."`,";  
      }  
      $schema_insert = ereg_replace(",$", "", $schema_insert);  
      $schema_insert .= ")   
      */ 
      $schema_insert = "INSERT INTO  $table VALUES (";   
      foreach($result as $key=>$val)   
      {   
       if($val != "")   
       $schema_insert .= " '".addslashes($val)."',";   
       else 
       $schema_insert .= "NULL,";   
      }   
      $schema_insert = ereg_replace(",$", "", $schema_insert);   
      $schema_insert .= ");$crlf";   
      $temp = $temp.$schema_insert ;   
      }   
      return $temp;   
    }   

    function RestoreFromFile($file){   
      if (false !== ($fp = fopen($file, 'r'))) {   
       $sql_queries = trim(fread($fp, filesize($file)));   
       $this->splitMySqlFile($pieces, $sql_queries);   
       foreach ($pieces as $query) {   
        if(!$this->execute(trim($query)))   
        return false;   
       }   
       return true;   
      }   
      return false;   
    }   

    function RestoreFromContent($content)   
    {   
      $content = trim($content);   
      $this->splitMySqlFile($pieces, $content);   
      foreach ($pieces as $query) {   
       if(!$this->execute(trim($query)))   
       return false;   
      }   
      return true;   
    }   

    function splitMySqlFile(&$ret, $sql)   
    {   
      $sql= trim($sql);   
      $sql=split(';',$sql);   
      $arr=array();   
      foreach($sql as $sq)   
      {   
        if($sq!="");   
        $arr[]=$sq;   
      }   
      $ret=$arr;   
      return true;   
    }   
}    

$db=new db();   

// 生成 word    
//$map=array('No','Name','Email','Age');   
//echo  $db->toWord('test',$map,'档案');   

// 生成 Excel    
//$map=array('No','Name','Email','Age');   
//echo  $db->toExcel('test',$map,'档案');   

// 生成 Xml    
//echo  $db->toExtXml('test',0,20);   

// 生成 Json    
//echo  $db->toExtJson('test',0,20);   

//备份       
//echo $db->Backuptofile('test','backup');    
?>

整表备份
代码如下:

$link = mysql_connect(DB_HOST,DB_USER,DB_PASS);
$tables = mysql_list_tables(DB_NAME);
$cachetables = array(); $tableselected = array();
while ($table = mysql_fetch_row($tables))
{
   $cachetables[$table[0]] = $table[0];
   $tableselected[$table[0]] = 1;
}
$table = $cachetables;
$filename =  DB_NAME . "_" . date("Y_m_d_H_i_s") . ".sql";
$path = "sql/" . $filename;
$filehandle = fopen($path, "w");
$result = mysql_query("SHOW tables");
while ($currow = mysql_fetch_array($result))
{
   if (isset($table[$currow[0]]))
   {
     sqldumptable($currow[0], $filehandle);
     fwrite($filehandle, "\n\n\n");
   }
}
fclose($filehandle);
$update_data = array('filename' => $filename, 'postdate' => mktime());
$db->insert('backup_db', $update_data);
// data dump functions
function sqldumptable($table, $fp = 0)
{
    $tabledump = "DROP TABLE IF EXISTS " . $table . ";\n";
    $result = mysql_fetch_array(mysql_query("SHOW CREATE TABLE " . $table));
    //echo "SHOW CREATE TABLE $table";
    $tabledump .= $result[1] . ";\r\n";
    if ($fp) {
        fwrite($fp, $tabledump);
    } else {
        echo $tabledump;
    }
    // get data
    $rows = mysql_query("SELECT * FROM " . $table);
    // $numfields=$DB->num_fields($rows);
    $numfields = mysql_num_fields($rows);
    while ($row = mysql_fetch_array($rows)) {
        $tabledump = "INSERT INTO " . $table . " VALUES(";
        $fieldcounter = -1;
        $firstfield = 1;
        // get each field's data
        while (++$fieldcounter < $numfields) {
            if (!$firstfield) {
                $tabledump .= ", ";
            } else {
                $firstfield = 0;
            }
            if (!isset($row[$fieldcounter])) {
                $tabledump .= "NULL";
            } else {
                $tabledump .= "'" . mysql_escape_string($row[$fieldcounter]) . "'";
            }
        }
        $tabledump .= ");\n";
        if ($fp) {
            fwrite($fp, $tabledump);
        } else {
            echo $tabledump;
        }
    }
    mysql_free_result($rows);
}

导入数据库
代码如下:

<?php
/************
*
PHP导入.sql文件
运行版本:php5,php4 使用的时候请选择
作者:panxp
邮件:coolpan123@gmail.com
*
*************/
    $file_dir = dirname(__FILE__);
    $file_name = "2010-05-09-bak.sql";
    $conn = mysql_connect(DB_HOST,DB_USER,DB_PASS);
    mysql_select_db(DB_NAME, $conn);
    /** PHP5 版本 **/
    $get_sql_data = file_get_contents($file_name, $file_dir);
    /** 
    * PHP4 版本
    if(file_exists($file_dir."/".$file_name))
    {
        $get_sql_data = fopen($file_dir."/".$file_name,"r");  
        if(!$get_sql_data)
        {
            echo "不能打开文件";
        }
        else
        {
            $get_sql_data = fread($get_sql_data, filesize ($file_dir."/".$file_name));
        }
    }
    ***/
    $explode = explode(";", $get_sql_data);
    $cnt = count($explode);
    for ($i=0; $i<$cnt; $i++)
    {
        $sql = $explode[$i];
        $result = mysql_query($sql);
        mysql_query("set names 'utf8'");
        if ($result) {
            echo "成功:".$i."个查询<br>";
        } else {
            echo "导入失败:".mysql_error();
        }
    }
?>


    
[2]PHP获取MSN好友列表类的实现代码
    来源: 互联网  发布时间: 2013-11-30

代码如下:

<?php
error_reporting(7);
class msn
{
    private $startcomm = 0;
    private $username = '';
    private $password = '';
    private $commend = '';
    private $domain = '';
    private $socket = '';
    private $challenge = '';
    private $status = array();
    private $data = array();

    function set_account($username, $password)
    {
        $this->username = $username;
        $this->password = $password;
    }

    function getData(){
        $buffer="";
        while (!feof($this->socket)) {
            $buffer .= fread($this->socket,1024);
            if (preg_match("//r/",$buffer)) {
                break;
            }
        }
        $this->checkData($buffer);
    }

    function getData2() {
        $buffer="";
        while (!feof($this->socket)) {
            $buffer .= fread($this->socket,1024);
            if (preg_match("//r/n/r/n/",$buffer)) {
                break;
            }
        }
        $this->checkData($buffer);
    }
    function checkData($buffer) {
        if (preg_match("/lc/=(.+?)/Ui",$buffer,$matches)) {   
            $this->challenge = "lc=" . $matches[1];
        }
        if (preg_match("/(XFR 3 NS )([0-9/./:]+?) (.*) ([0-9/./:]+?)/is",$buffer,$matches)) {
            $split = explode(":",$matches[2]);
            $this->startcomm = 1;
            $this->msn_connect($split[0],$split[1]);
        }
        if (preg_match("/tpf/=([a-zA-Z0-9]+?)/Ui",$buffer,$matches)) {
            $this->nexus_connect($matches[1]);
        }
        $split = explode("/n",$buffer);
        for ($i=0;$i<count($split);$i++) { 
            $detail = explode(" ",$split[$i]);
            if ($detail[0] == "LST") {
                if(isset($detail[2])) $this->data[] = array($detail[1], urldecode($detail[2]));
            }
        }
        $this->status = array(200, $this->data);
        //echo $buffer;
    }
    function msn_connect($server,$port) {
        if ($this->socket) {
            fclose($this->socket);
        }
        $this->socket = @fsockopen($server,$port, $errno, $errstr, 20);
        if (!$this->socket) {
            $this->status = array(500,'MSN验证服务器无法连接');
            return false;

        } else {

            $this->startcomm++;
            $this->send_command("VER " . $this->startcomm . " MSNP8 CVR0",1);
            $this->send_command("CVR " . $this->startcomm . " 0x0409 win 4.10 i386 MSNMSGR 6.2 MSMSGS " . $this->username,1);
            $this->send_command("USR " . $this->startcomm . " TWN I " . $this->username,1);
        }
    }
    function send_command($command) {
        $this->commend = $command;
        $this->startcomm++;      
        fwrite($this->socket,$command . "/r/n");
        $this->getData();
    }
    function nexus_connect($tpf) {
        $arr[] = "GET /rdr/pprdr.asp HTTP/1.0/r/n/r/n";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, "https://nexus.passport.com:443/rdr/pprdr.asp");
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_VERBOSE, 0);
        curl_setopt($curl, CURLOPT_HEADER,1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $arr);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        $data = curl_exec($curl);
        curl_close($curl);
        preg_match("/DALogin=(.+?),/",$data,$matches);
        if(!isset($matches[1])) return false;
        $split = explode("/",$matches[1]);
        $headers[0] = "GET /$split[1] HTTP/1.1/r/n";
        $headers[1] = "Authorization: Passport1.4 OrgVerb=GET,OrgURL=http%3A%2F%2Fmessenger%2Emsn%2Ecom,sign-in=" . $this->username . ",pwd=" . $this->password . ", " . trim($this->challenge) . "/r/n";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, "https://" . $split[0] . ":443/". $split[1]);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_VERBOSE, 0);
        curl_setopt($curl,CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_HEADER,1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        $data = curl_exec($curl);
        curl_close($curl);
        preg_match("/t=(.+?)'/",$data,$matches);
        if(!isset($matches[1])){

            $this->status = array(404, '你输入的MSN帐号或者密码错误');
            return false;
        }
        $this->send_command("USR " . $this->startcomm . " TWN S t=" . trim($matches[1]) . "",2);
        $this->send_command("CHG " . $this->startcomm . " HDN",2);
        $this->send_command("SYN " . $this->startcomm . " 0",2);
        $this->getData2();
        $this->send_command("SYN " . $this->startcomm . " 1 46 2",2);
        $this->getData2();
        $this->send_command("CHG ". $this->startcomm . " BSY");
        $this->getData();    
    }
    public function getStatus()
    {
        return $this->status;
    }
}

$msn = new MSN;
$msn->set_account('xx@hotmail.com', 'xxxxx');
$msn->msn_connect("messenger.hotmail.com",1863);
$data = $msn->getStatus();
print_r($data);
?>


    
[3]使用php统计字符串中中英文字符的个数
    来源: 互联网  发布时间: 2013-11-30
代码如下:

<?php
echo $str = "43fdf测试fdsfadaf43543543职工问防盗锁防盗锁5345gfdgd";
preg_match_all("/[0-9]{1}/",$str,$arrNum);
preg_match_all("/[a-zA-Z]{1}/",$str,$arrAl);
preg_match_all("/([/x{4e00}-/x{9fa5}]){1}/u",$str,$arrCh);
echo "<pre>";
echo "数字个数:".count($arrNum[0])."<br/>";
echo "字母个数:".count($arrAl[0])."<br/>";
echo "中文个数:".count($arrCh[0]);
?>

    
最新技术文章:
▪PHP函数microtime()时间戳的定义与用法
▪PHP单一入口之apache配置内容
▪PHP数组排序方法总结(收藏)
▪php数组排序方法大全(脚本学堂整理奉献)
▪php数组排序的几个函数(附实例)
▪php二维数组排序(实例)
▪php根据键值对二维数组排序的小例子
▪php验证码(附截图)
▪php数组长度的获取方法(三个实例)
▪php获取数组长度的方法举例
▪判断php数组维度(php数组长度)的方法
▪php获取图片的exif信息的示例代码
▪PHP 数组key长度对性能的影响实例分析
▪php函数指定默认值的方法示例
▪php提交表单到当前页面、提交表单后页面重定...
▪php四舍五入的三种实现方法
▪php获得数组长度(元素个数)的方法
▪php日期函数的简单示例代码
javascript开源软件 iis7站长之家
▪php字符串函数的简单示例代码
▪php文件下载代码(多浏览器兼容、支持中文文...
▪php实现文件下载、支持中文文件名的示例代码...
▪php文件下载(防止中文文件名乱码)的示例代码
▪解决PHP文件下载时中文文件名乱码的问题
▪php数组去重(一维、二维数组去重)的简单示例
▪php小数点后取两位的三种实现方法
▪php Redis 队列服务的简单示例
▪PHP导出excel时数字变为科学计数的解决方法
▪PHP数组根据值获取Key的简单示例
▪php数组去重的函数代码示例
 


站内导航:


特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

©2012-2021,,E-mail:www_#163.com(请将#改为@)

浙ICP备11055608号-3