新程php培训–就业率100%的php培训中心 全国免费咨询热线 400-668-8834 了解更多,请访问 http://www.phppx.com
2010/09/04php技术

评论关闭

如何判断字符串$a是否在字符串$b中出现?

<?php

//这个比较简单,考察的是对strpos掌握情况
//一定要用===,因为strpos可能会返回0
$a = ‘http://www.phppx.com’;
$b = ‘h’;
if (strpos($a,$b,0) === false) {
 echo ‘没有’;
} else {
 echo ‘有’;
}

?>

2010/04/08php技术

评论关闭

一个不依靠ZLib模块可以创建、操作 ZIP 文件的PHP类

这个类的所有操作不需要 zLib 模块的支持,有的时候可能会用到这个类。

<?
/**
* @copyright 互联网
* @author bouchon
* 整理:www.phppx.com
* @desc 建立、操作、控制 ZIP 文件的类
*/

class zip
{
        var $datasec, $ctrl_dir = array();
        var $eof_ctrl_dir = “\x50\x4b\x05\x06\x00\x00\x00\x00″;
        var $old_offset = 0; var $dirs = Array(“.”);

        function get_List($zip_name)
        {
                $zip = @fopen($zip_name, ‘rb’);
                if(!$zip) return(0);
                $centd = $this->ReadCentralDir($zip,$zip_name);

                @rewind($zip);
                @fseek($zip, $centd['offset']);

                for ($i=0; $i<$centd['entries']; $i++)
                {
                        $header = $this->ReadCentralFileHeaders($zip);
                        $header['index'] = $i;$info['filename'] = $header['filename'];
                        $info['stored_filename'] = $header['stored_filename'];
                        $info['size'] = $header['size'];$info['compressed_size']=$header['compressed_size'];
                        $info['crc'] = strtoupper(dechex( $header['crc'] ));
                        $info['mtime'] = $header['mtime']; $info['comment'] = $header['comment'];
                        $info['folder'] = ($header['external']==0×41FF0010||$header['external']==16)?1:0;
                        $info['index'] = $header['index'];$info['status'] = $header['status'];
                        $ret[]=$info; unset($header);
                }
                return $ret;
        }

        function Add($files,$compact)
        {
                if(!is_array($files[0])) $files=Array($files);

                for($i=0;$files[$i];$i++){
                        $fn = $files[$i];
                        if(!in_Array(dirname($fn[0]),$this->dirs))
                        $this->add_Dir(dirname($fn[0]));
                        if(basename($fn[0]))
                        $ret[basename($fn[0])]=$this->add_File($fn[1],$fn[0],$compact);
                }
                return $ret;
        }

        function get_file()
        {
                $data = implode(”, $this -> datasec);
                $ctrldir = implode(”, $this -> ctrl_dir);

                return $data . $ctrldir . $this -> eof_ctrl_dir .
                pack(‘v’, sizeof($this -> ctrl_dir)).pack(‘v’, sizeof($this -> ctrl_dir)).
                pack(‘V’, strlen($ctrldir)) . pack(‘V’, strlen($data)) . “\x00\x00″;
        }

        function add_dir($name)
        {
                $name = str_replace(“\\”, “/”, $name);
                $fr = “\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00″;

                $fr .= pack(“V”,0).pack(“V”,0).pack(“V”,0).pack(“v”, strlen($name) );
                $fr .= pack(“v”, 0 ).$name.pack(“V”, 0).pack(“V”, 0).pack(“V”, 0);
                $this -> datasec[] = $fr;

                $new_offset = strlen(implode(“”, $this->datasec));

                $cdrec = “\x50\x4b\x01\x02\x00\x00\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00″;
                $cdrec .= pack(“V”,0).pack(“V”,0).pack(“V”,0).pack(“v”, strlen($name) );
                $cdrec .= pack(“v”, 0 ).pack(“v”, 0 ).pack(“v”, 0 ).pack(“v”, 0 );
                $ext = “\xff\xff\xff\xff”;
                $cdrec .= pack(“V”, 16 ).pack(“V”, $this -> old_offset ).$name;

                $this -> ctrl_dir[] = $cdrec;
                $this -> old_offset = $new_offset;
                $this -> dirs[] = $name;
        }

        function add_File($data, $name, $compact = 1)
        {
                $name     = str_replace(‘\\’, ‘/’, $name);
                $dtime    = dechex($this->DosTime());

                $hexdtime = ‘\x’ . $dtime[6] . $dtime[7].’\x’.$dtime[4] . $dtime[5]
                . ‘\x’ . $dtime[2] . $dtime[3].’\x’.$dtime[0].$dtime[1];
                eval(‘$hexdtime = “‘ . $hexdtime . ‘”;’);

                if($compact)
                $fr = “\x50\x4b\x03\x04\x14\x00\x00\x00\x08\x00″.$hexdtime;
                else $fr = “\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00″.$hexdtime;
                $unc_len = strlen($data); $crc = crc32($data);

                if($compact){
                        $zdata = gzcompress($data); $c_len = strlen($zdata);
                        $zdata = substr(substr($zdata, 0, strlen($zdata) – 4), 2);
                }else{
                        $zdata = $data;
                }
                $c_len=strlen($zdata);
                $fr .= pack(‘V’, $crc).pack(‘V’, $c_len).pack(‘V’, $unc_len);
                $fr .= pack(‘v’, strlen($name)).pack(‘v’, 0).$name.$zdata;

                $fr .= pack(‘V’, $crc).pack(‘V’, $c_len).pack(‘V’, $unc_len);

                $this -> datasec[] = $fr;
                $new_offset        = strlen(implode(”, $this->datasec));
                if($compact)
                $cdrec = “\x50\x4b\x01\x02\x00\x00\x14\x00\x00\x00\x08\x00″;
                else $cdrec = “\x50\x4b\x01\x02\x14\x00\x0a\x00\x00\x00\x00\x00″;
                $cdrec .= $hexdtime.pack(‘V’, $crc).pack(‘V’, $c_len).pack(‘V’, $unc_len);
                $cdrec .= pack(‘v’, strlen($name) ).pack(‘v’, 0 ).pack(‘v’, 0 );
                $cdrec .= pack(‘v’, 0 ).pack(‘v’, 0 ).pack(‘V’, 32 );
                $cdrec .= pack(‘V’, $this -> old_offset );

                $this -> old_offset = $new_offset;
                $cdrec .= $name;
                $this -> ctrl_dir[] = $cdrec;
                return true;
        }

        function DosTime() {
                $timearray = getdate();
                if ($timearray['year'] < 1980) {
                        $timearray['year'] = 1980; $timearray['mon'] = 1;
                        $timearray['mday'] = 1; $timearray['hours'] = 0;
                        $timearray['minutes'] = 0; $timearray['seconds'] = 0;
                }
                return (($timearray['year'] – 1980) << 25) | ($timearray['mon'] << 21) |     ($timearray['mday'] << 16) | ($timearray['hours'] << 11) |
                ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
        }

        function Extract ( $zn, $to, $index = Array(-1) )
        {
                $ok = 0; $zip = @fopen($zn,’rb’);
                if(!$zip) return(-1);
                $cdir = $this->ReadCentralDir($zip,$zn);
                $pos_entry = $cdir['offset'];

                if(!is_array($index)){ $index = array($index);  }
                for($i=0; $index[$i];$i++){
                        if(intval($index[$i])!=$index[$i]||$index[$i]>$cdir['entries'])
                        return(-1);
                }

                for ($i=0; $i<$cdir['entries']; $i++)
                {
                        @fseek($zip, $pos_entry);
                        $header = $this->ReadCentralFileHeaders($zip);
                        $header['index'] = $i; $pos_entry = ftell($zip);
                        @rewind($zip); fseek($zip, $header['offset']);
                        if(in_array(“-1″,$index)||in_array($i,$index))
                        $stat[$header['filename']]=$this->ExtractFile($header, $to, $zip);

                }
                fclose($zip);
                return $stat;
        }

        function ReadFileHeader($zip)
        {
                $binary_data = fread($zip, 30);
                $data = unpack(‘vchk/vid/vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len’, $binary_data);

                $header['filename'] = fread($zip, $data['filename_len']);
                if ($data['extra_len'] != 0) {
                        $header['extra'] = fread($zip, $data['extra_len']);
                } else { $header['extra'] = ”; }

                $header['compression'] = $data['compression'];$header['size'] = $data['size'];
                $header['compressed_size'] = $data['compressed_size'];
                $header['crc'] = $data['crc']; $header['flag'] = $data['flag'];
                $header['mdate'] = $data['mdate'];$header['mtime'] = $data['mtime'];

                if ($header['mdate'] && $header['mtime']){
                        $hour=($header['mtime']&0xF800)>>11;$minute=($header['mtime']&0×07E0)>>5;
                        $seconde=($header['mtime']&0×001F)*2;$year=(($header['mdate']&0xFE00)>>9)+1980;
                        $month=($header['mdate']&0×01E0)>>5;$day=$header['mdate']&0×001F;
                        $header['mtime'] = mktime($hour, $minute, $seconde, $month, $day, $year);
                }else{$header['mtime'] = time();}

                $header['stored_filename'] = $header['filename'];
                $header['status'] = “ok”;
                return $header;
        }

        function ReadCentralFileHeaders($zip){
                $binary_data = fread($zip, 46);
                $header = unpack(‘vchkid/vid/vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset’, $binary_data);

                if ($header['filename_len'] != 0)
                $header['filename'] = fread($zip,$header['filename_len']);
                else $header['filename'] = ”;

                if ($header['extra_len'] != 0)
                $header['extra'] = fread($zip, $header['extra_len']);
                else $header['extra'] = ”;

                if ($header['comment_len'] != 0)
                $header['comment'] = fread($zip, $header['comment_len']);
                else $header['comment'] = ”;

                if ($header['mdate'] && $header['mtime'])
                {
                        $hour = ($header['mtime'] & 0xF800) >> 11;
                        $minute = ($header['mtime'] & 0×07E0) >> 5;
                        $seconde = ($header['mtime'] & 0×001F)*2;
                        $year = (($header['mdate'] & 0xFE00) >> 9) + 1980;
                        $month = ($header['mdate'] & 0×01E0) >> 5;
                        $day = $header['mdate'] & 0×001F;
                        $header['mtime'] = mktime($hour, $minute, $seconde, $month, $day, $year);
                } else {
                        $header['mtime'] = time();
                }
                $header['stored_filename'] = $header['filename'];
                $header['status'] = ‘ok’;
                if (substr($header['filename'], -1) == ‘/’)
                $header['external'] = 0×41FF0010;
                return $header;
        }

        function ReadCentralDir($zip,$zip_name)
        {
                $size = filesize($zip_name);
                if ($size < 277) $maximum_size = $size;
                else $maximum_size=277;

                @fseek($zip, $size-$maximum_size);
                $pos = ftell($zip); $bytes = 0×00000000;

                while ($pos < $size)
                {
                        $byte = @fread($zip, 1); $bytes=($bytes << 8) | Ord($byte);
                        if ($bytes == 0×504b0506){ $pos++; break; } $pos++;
                }

                $data=unpack(‘vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size’,
                fread($zip, 18));

                if ($data['comment_size'] != 0)
                $centd['comment'] = fread($zip, $data['comment_size']);
                else $centd['comment'] = ”; $centd['entries'] = $data['entries'];
                $centd['disk_entries'] = $data['disk_entries'];
                $centd['offset'] = $data['offset'];$centd['disk_start'] = $data['disk_start'];
                $centd['size'] = $data['size'];  $centd['disk'] = $data['disk'];
                return $centd;
        }

        function ExtractFile($header,$to,$zip)
        {
                $header = $this->readfileheader($zip);

                if(substr($to,-1)!=”/”) $to.=”/”;
                if(!@is_dir($to)) @mkdir($to,0777);

                $pth = explode(“/”,dirname($header['filename']));
                for($i=0;isset($pth[$i]);$i++){
                        if(!$pth[$i]) continue;
                        if(!is_dir($to.$pth[$i])) @mkdir($to.$pth[$i],0777);
                }
                if (!($header['external']==0×41FF0010)&&!($header['external']==16))
                {
                        if ($header['compression']==0)
                        {
                                $fp = @fopen($to.$header['filename'], ‘wb’);
                                if(!$fp) return(-1);
                                $size = $header['compressed_size'];

                                while ($size != 0)
                                {
                                        $read_size = ($size < 2048 ? $size : 2048);
                                        $buffer = fread($zip, $read_size);
                                        $binary_data = pack(‘a’.$read_size, $buffer);
                                        @fwrite($fp, $binary_data, $read_size);
                                        $size -= $read_size;
                                }
                                fclose($fp);
                                touch($to.$header['filename'], $header['mtime']);

                        }else{
                                $fp = @fopen($to.$header['filename'].’.gz’,'wb’);
                                if(!$fp) return(-1);
                                $binary_data = pack(‘va1a1Va1a1′, 0×8b1f, Chr($header['compression']),
                                Chr(0×00), time(), Chr(0×00), Chr(3));

                                fwrite($fp, $binary_data, 10);
                                $size = $header['compressed_size'];

                                while ($size != 0)
                                {
                                        $read_size = ($size < 1024 ? $size : 1024);
                                        $buffer = fread($zip, $read_size);
                                        $binary_data = pack(‘a’.$read_size, $buffer);
                                        @fwrite($fp, $binary_data, $read_size);
                                        $size -= $read_size;
                                }

                                $binary_data = pack(‘VV’, $header['crc'], $header['size']);
                                fwrite($fp, $binary_data,8); fclose($fp);

                                $gzp = @gzopen($to.$header['filename'].’.gz’,'rb’) or die(“Cette archive est compress閑”);
                                if(!$gzp) return(-2);
                                $fp = @fopen($to.$header['filename'],’wb’);
                                if(!$fp) return(-1);
                                $size = $header['size'];

                                while ($size != 0)
                                {
                                        $read_size = ($size < 2048 ? $size : 2048);
                                        $buffer = gzread($gzp, $read_size);
                                        $binary_data = pack(‘a’.$read_size, $buffer);
                                        @fwrite($fp, $binary_data, $read_size);
                                        $size -= $read_size;
                                }
                                fclose($fp); gzclose($gzp);

                                touch($to.$header['filename'], $header['mtime']);
                                @unlink($to.$header['filename'].’.gz’);

                        }}
                        return true;
        }
}

?>

继续阅读 »

一个操作xml的PHP类(附使用方法)

<?php
/**
* @copyright 互联网
* 整理:[url]www.phppx.com[/url]
* @desc 一个操作xml的PHP类
*/

/*
   (c) 2000 Hans Anderson Corporation.  All Rights Reserved.
   You are free to use and modify this class under the same
   guidelines found in the PHP License.

   ———–

   bugs/me:
   [url]http://www.hansanderson.com/php/[/url]
   [email]me@hansanderson.com[/email]
   [email]showstv@163.com[/email]

   ———–

   Version 1.0

      – 1.0 is the first actual release of the class.  It”s 
       finally what I was hoping it would be, though there
       are likely to still be some bugs in it.  This is
       a much changed version, and if you have downloaded
       a previous version, this WON”T work with your existing
       scripts!  You”ll need to make some SIMPLE changes.

      – .92 fixed bug that didn”t include tag attributes

       (to use attributes, add _attributes[array_index]
        to the end of the tag in question:
        $xml_html_head_body_img would become
        $xml_html_head_body_img_attributes[0], 
        for example)

        — Thanks to Nick Winfield <[email]nick@wirestation.co.uk[/email]>
          for reporting this bug.

      – .91 No Longer requires PHP4!

      – .91 now all elements are array.  Using objects has
       been discontinued.
*/

class xml_container{

   function store($k,$v) {
      $this->{$k}[] = $v;
   }
}
/* parses the information */
/*********************************
*   类定义开始
*
*********************************/
class xml{
  
   // initialize some variables
   var $current_tag=array();
   var $xml_parser;
   var $Version = 1.0;
   var $tagtracker = array();

   /* Here are the XML functions needed by expat */
   /* when expat hits an opening tag, it fires up this function */
   function startElement($parser, $name, $attrs){

      array_push($this->current_tag, $name); // add tag to the cur. tag array
      $curtag = implode(“_”,$this->current_tag); // piece together tag

      /* this tracks what array index we are on for this tag */

      if(isset($this->tagtracker["$curtag"])) {
        $this->tagtracker["$curtag"]++;
      }
      else{
        $this->tagtracker["$curtag"]=0;
      }

      /* if there are attributes for this tag, we set them here. */

      if(count($attrs)>0) {
        $j = $this->tagtracker["$curtag"];
        if(!$j) $j = 0;

        if(!is_object($GLOBALS[$this->identifier]["$curtag"][$j])) {
           $GLOBALS[$this->identifier]["$curtag"][$j] = new xml_container;
        }

        $GLOBALS[$this->identifier]["$curtag"][$j]->store(“attributes”,$attrs);
      }
  
   }// end function startElement

   /* when expat hits a closing tag, it fires up this function */
   function endElement($parser, $name) {
      $curtag = implode(“_”,$this->current_tag); // piece together tag
     
      // before we pop it off,
      // so we can get the correct
      // cdata

      if(!$this->tagdata["$curtag"]) {
        $popped = array_pop($this->current_tag); // or else we screw up where we are
        return; // if we have no data for the tag
      }
      else{
        $TD = $this->tagdata["$curtag"];
        unset($this->tagdata["$curtag"]);
      }

      $popped = array_pop($this->current_tag);
      // we want the tag name for
      // the tag above this, it 
      // allows us to group the
      // tags together in a more
      // intuitive way.

      if(sizeof($this->current_tag) == 0) return; // if we aren”t in a tag

      $curtag = implode(“_”,$this->current_tag); // piece together tag
      // this time for the arrays

      $j = $this->tagtracker["$curtag"];
     
      if(!$j) $j = 0;

      if(!is_object($GLOBALS[$this->identifier]["$curtag"][$j])) {
        $GLOBALS[$this->identifier]["$curtag"][$j] = new xml_container;
      }

      $GLOBALS[$this->identifier]["$curtag"][$j]->store($name,$TD);
      #$this->tagdata["$curtag"]);
      unset($TD);
      return TRUE;
   } // end function endElement
   /* when expat finds some internal tag character data,
     it fires up this function */

   function characterData($parser, $cdata) {
      $curtag = implode(“_”,$this->current_tag); // piece together tag
      $this->tagdata["$curtag"] .= $cdata;
   }
   function xml($data,$identifier=”xml”) { 

      $this->identifier = $identifier;

      // create parser object
      $this->xml_parser = xml_parser_create();

      // set up some options and handlers
      xml_set_object($this->xml_parser,$this);
      xml_parser_set_option($this->xml_parser,XML_OPTION_CASE_FOLDING,0);
      xml_set_element_handler($this->xml_parser, “startElement”, “endElement”);
      xml_set_character_data_handler($this->xml_parser, “characterData”);

      if (!xml_parse($this->xml_parser, $data, TRUE)) {
        sprintf(“XML error: %s at line %d”,
        xml_error_string(xml_get_error_code($this->xml_parser)),
        xml_get_current_line_number($this->xml_parser));
      }

      // we are done with the parser, so let”s free it
      xml_parser_free($this->xml_parser);

   }//end constructor: function xml()
}//thus, we end our class xml

?>

使用方法:

<?php
require(“class.xml.php”);
$file = “data.xml”;
$data = implode(“”,file($file)) or die(“could not open XML input file”);
$obj = new xml($data,”xml”);
print $xml["hans"][0]->num_results[0];
for($i=0;$i<sizeof($xml["hans"]);$i++) {
        print $xml["hans"][$i]->tag[0] . ” “;
}

//To print url attributes (if they exist):

print $xml["hans"][0]->attributes[0]["size"];

?>

PHP邮件发送类(附使用方法)

email.class.php  代码:

<?
/**
* 来源:互联网
* 整理:www.phppx.com
*/
class smtp
{
        /* Public Variables */
        var $smtp_port;
        var $time_out;
        var $host_name;
        var $log_file;
        var $relay_host;
        var $debug;
        var $auth;
        var $user;
        var $pass;

        /* Private Variables */
        var $sock;

        /* Constractor */
        function smtp($relay_host = “”, $smtp_port = 25,$auth = false,$user,$pass)
        {
                $this->debug = FALSE;
                $this->smtp_port = $smtp_port;
                $this->relay_host = $relay_host;
                $this->time_out = 30; //is used in fsockopen()
                #
                $this->auth = $auth;//auth
                $this->user = $user;
                $this->pass = $pass;
                #
                $this->host_name = “localhost”; //is used in HELO command
                $this->log_file =”";

                $this->sock = FALSE;
        }

        /* Main Function */
        function sendmail($to, $from, $subject = “”, $body = “”, $mailtype, $cc = “”, $bcc = “”, $additional_headers = “”)
        {
                $mail_from = $this->get_address($this->strip_comment($from));
                $body = ereg_replace(“(^|(\r\n))(\\.)”, “\\1.\\3“, $body);
                $header .= “MIME-Version:1.0\r\n”;
                if($mailtype==”HTML”){
                        $header .= “Content-Type:text/html\r\n”;
                }
                $header .= “To: “.$to.”\r\n”;
                if ($cc != “”) {
                        $header .= “Cc: “.$cc.”\r\n”;
                }
                $header .= “From: $from<”.$from.”>\r\n”;
                $header .= “Subject: “.$subject.”\r\n”;
                $header .= $additional_headers;
                $header .= “Date: “.date(“r”).”\r\n”;
                $header .= “X-Mailer:By Redhat (PHP/”.phpversion().”)\r\n”;
                list($msec, $sec) = explode(” “, microtime());
                $header .= “Message-ID: <”.date(“YmdHis”, $sec).”.”.($msec*1000000).”.”.$mail_from.”>\r\n”;
                $TO = explode(“,”, $this->strip_comment($to));

                if ($cc != “”) {
                        $TO = array_merge($TO, explode(“,”, $this->strip_comment($cc)));
                }

                if ($bcc != “”) {
                        $TO = array_merge($TO, explode(“,”, $this->strip_comment($bcc)));
                }

                $sent = TRUE;
                foreach ($TO as $rcpt_to) {
                        $rcpt_to = $this->get_address($rcpt_to);
                        if (!$this->smtp_sockopen($rcpt_to)) {
                                $this->log_write(“Error: Cannot send email to “.$rcpt_to.”\n”);
                                $sent = FALSE;
                                continue;
                        }
                        if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $header, $body)) {
                                $this->log_write(“E-mail has been sent to <”.$rcpt_to.”>\n”);
                        } else {
                                $this->log_write(“Error: Cannot send email to <”.$rcpt_to.”>\n”);
                                $sent = FALSE;
                        }
                        fclose($this->sock);
                        $this->log_write(“Disconnected from remote host\n”);
                }
                echo “<br>”;
                echo $header;
                return $sent;
        }

        /* Private Functions */

        function smtp_send($helo, $from, $to, $header, $body = “”)
        {
                if (!$this->smtp_putcmd(“HELO”, $helo)) {
                        return $this->smtp_error(“sending HELO command”);
                }
                #auth
                if($this->auth){
                        if (!$this->smtp_putcmd(“AUTH LOGIN”, base64_encode($this->user))) {
                                return $this->smtp_error(“sending HELO command”);
                        }

                        if (!$this->smtp_putcmd(“”, base64_encode($this->pass))) {
                                return $this->smtp_error(“sending HELO command”);
                        }
                }
                #
                if (!$this->smtp_putcmd(“MAIL”, “FROM:<”.$from.”>”)) {
                        return $this->smtp_error(“sending MAIL FROM command”);
                }

                if (!$this->smtp_putcmd(“RCPT”, “TO:<”.$to.”>”)) {
                        return $this->smtp_error(“sending RCPT TO command”);
                }

                if (!$this->smtp_putcmd(“DATA”)) {
                        return $this->smtp_error(“sending DATA command”);
                }

                if (!$this->smtp_message($header, $body)) {
                        return $this->smtp_error(“sending message”);
                }

                if (!$this->smtp_eom()) {
                        return $this->smtp_error(“sending <CR><LF>.<CR><LF> [EOM]“);
                }

                if (!$this->smtp_putcmd(“QUIT”)) {
                        return $this->smtp_error(“sending QUIT command”);
                }

                return TRUE;
        }

        function smtp_sockopen($address)
        {
                if ($this->relay_host == “”) {
                        return $this->smtp_sockopen_mx($address);
                } else {
                        return $this->smtp_sockopen_relay();
                }
        }

        function smtp_sockopen_relay()
        {
                $this->log_write(“Trying to “.$this->relay_host.”:”.$this->smtp_port.”\n”);
                $this->sock = @fsockopen($this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out);
                if (!($this->sock && $this->smtp_ok())) {
                        $this->log_write(“Error: Cannot connenct to relay host “.$this->relay_host.”\n”);
                        $this->log_write(“Error: “.$errstr.” (“.$errno.”)\n”);
                        return FALSE;
                }
                $this->log_write(“Connected to relay host “.$this->relay_host.”\n”);
                return TRUE;;
        }

        function smtp_sockopen_mx($address)
        {
                $domain = ereg_replace(“^.+@([^@]+)$“, “\\1“, $address);
                if (!@getmxrr($domain, $MXHOSTS)) {
                        $this->log_write(“Error: Cannot resolve MX \”".$domain.”\”\n”);
                        return FALSE;
                }
                foreach ($MXHOSTS as $host) {
                        $this->log_write(“Trying to “.$host.”:”.$this->smtp_port.”\n”);
                        $this->sock = @fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out);
                        if (!($this->sock && $this->smtp_ok())) {
                                $this->log_write(“Warning: Cannot connect to mx host “.$host.”\n”);
                                $this->log_write(“Error: “.$errstr.” (“.$errno.”)\n”);
                                continue;
                        }
                        $this->log_write(“Connected to mx host “.$host.”\n”);
                        return TRUE;
                }
                $this->log_write(“Error: Cannot connect to any mx hosts (“.implode(“, “, $MXHOSTS).”)\n”);
                return FALSE;
        }

        function smtp_message($header, $body)
        {
                fputs($this->sock, $header.”\r\n”.$body);
                $this->smtp_debug(“> “.str_replace(“\r\n”, “\n”.”> “, $header.”\n> “.$body.”\n> “));

                return TRUE;
        }

        function smtp_eom()
        {
                fputs($this->sock, “\r\n.\r\n”);
                $this->smtp_debug(“. [EOM]\n”);

                return $this->smtp_ok();
        }

        function smtp_ok()
        {
                $response = str_replace(“\r\n”, “”, fgets($this->sock, 512));
                $this->smtp_debug($response.”\n”);

                if (!ereg(“^[23]“, $response)) {
                        fputs($this->sock, “QUIT\r\n”);
                        fgets($this->sock, 512);
                        $this->log_write(“Error: Remote host returned \”".$response.”\”\n”);
                        return FALSE;
                }
                return TRUE;
        }

        function smtp_putcmd($cmd, $arg = “”)
        {
                if ($arg != “”) {
                        if($cmd==”") $cmd = $arg;
                        else $cmd = $cmd.” “.$arg;
                }

                fputs($this->sock, $cmd.”\r\n”);
                $this->smtp_debug(“> “.$cmd.”\n”);

                return $this->smtp_ok();
        }

        function smtp_error($string)
        {
                $this->log_write(“Error: Error occurred while “.$string.”.\n”);
                return FALSE;
        }

        function log_write($message)
        {
                $this->smtp_debug($message);

                if ($this->log_file == “”) {
                        return TRUE;
                }

                $message = date(“M d H:i:s “).get_current_user().”[".getmypid()."]: “.$message;
                if (!@file_exists($this->log_file) || !($fp = @fopen($this->log_file, “a”))) {
                        $this->smtp_debug(“Warning: Cannot open log file \”".$this->log_file.”\”\n”);
                        return FALSE;
                }
                flock($fp, LOCK_EX);
                fputs($fp, $message);
                fclose($fp);

                return TRUE;
        }

        function strip_comment($address)
        {
                $comment = “\\([^()]*\\)”;
                while (ereg($comment, $address)) {
                        $address = ereg_replace($comment, “”, $address);
                }

                return $address;
        }

        function get_address($address)
        {
                $address = ereg_replace(“([ \t\r\n])+”, “”, $address);
                $address = ereg_replace(“^.*<(.+)>.*$”, “\\1“, $address);

                return $address;
        }

        function smtp_debug($message)
        {
                if ($this->debug) {
                        echo $message.”<br>”;
                }
        }

        function get_attach_type($image_tag) { //

                $filedata = array();

                $img_file_con=fopen($image_tag,”r”);
                unset($image_data);
                while ($tem_buffer=AddSlashes(fread($img_file_con,filesize($image_tag))))
                $image_data.=$tem_buffer;
                fclose($img_file_con);

                $filedata['context'] = $image_data;
                $filedata['filename']= basename($image_tag);
                $extension=substr($image_tag,strrpos($image_tag,”.”),strlen($image_tag)-strrpos($image_tag,”.”));
                switch($extension){
                        case “.gif”:
                                $filedata['type'] = “image/gif”;
                                break;
                        case “.gz”:
                                $filedata['type'] = “application/x-gzip”;
                                break;
                        case “.htm”:
                                $filedata['type'] = “text/html”;
                                break;
                        case “.html”:
                                $filedata['type'] = “text/html”;
                                break;
                        case “.jpg”:
                                $filedata['type'] = “image/jpeg”;
                                break;
                        case “.tar”:
                                $filedata['type'] = “application/x-tar”;
                                break;
                        case “.txt”:
                                $filedata['type'] = “text/plain”;
                                break;
                        case “.zip”:
                                $filedata['type'] = “application/zip”;
                                break;
                        default:
                                $filedata['type'] = “application/octet-stream”;
                                break;
                }
                return $filedata;
        }

}
?>

继续阅读 »

如何修改Apache最大连接数

  • 在apache中 可以采用 MaxClients 指令改变 apache最大链接数。

    apache手册原文: 

    对于非线程型的MPM(也就是prefork),MaxClients表示可以用于伺服客户端请求的最大子进程数量,默认值是256。要增大这个值,你必须同时增大ServerLimit

    对于线程型或者混合型的MPM(也就是beosworker),MaxClients表示可以用于伺服客户端请求的最大线程数量。线程型的beos的默认值是50。对于混合型的MPM默认值是16(ServerLimit)乘以25(ThreadsPerChild)的结果。因此要将MaxClients增加到超过16个进程才能提供的时候,你必须同时增加ServerLimit的值。

      在httpd.conf中配置:

    1、对于apache1.x

    增加apache最大连接数的方法:

             找到MaxClients n , n是整数,表示最大连接数,取值范围在1和256之间,如果要让apache支持更多的连接数,那么需要修改源码中的httpd.h文件,编辑/httpd-2.0.59/include/httpd.h中的HARD_SERVER_LIMIT值改大然后再编译。

    2、对于apache2.x

    系统默认150个连接数,有个数有点太少了,网站流量大一些时候就不够用了。现在服务器配置要比前几年好很多,我们可以修改更大一些。下面的例子修改为2500个。

    在httpd.conf文件中找到

     

    <IfModule prefork.c>
    StartServers       8
    MinSpareServers    5
    MaxSpareServers   20
    MaxClients       150
    MaxRequestsPerChild  1000
    </IfModule>
    修改
    MaxClients       150
    为
    ServerLimit        2500
    MaxClients         2500

     

    注意:要同时修改ServerLimit这个选项。

             然后保存退出重新启动apache 服务,ok !
     

  • 关键词:修改Apache最大连接数

    从零开始学php类(1)– 类的基础知识(原创连载)

    什么是类?
    简单的说,类是属性和方法的集合。

    定义一个最简单的类
    <?php
    class person{}
    ?>
    这样我们就定义了一个叫person的类。

    关于php类的命名规则
    php类的命名,包括php变量,php方法的命名都比较混乱,完全不像java那样有严谨的命名规则。
    例如,对于上面的类,可以采用完全小写的写法,或者首个字母大写Person,甚至命名中有下划线写法,这些都是允许的。在不同大型的开源项目中,命名也是不同,完全凭个人习惯。

    注意事项:
    1.不能把类写在不同文件里,也不能把类写在不同的php块中。例如,
    <?php
    class person{
    ?>
    <?php }?>
    这样会产生一个”Parse error” 错误。
    2.我们也不能把类命名为stdClass ,这样会产生一个”Fatal error” 。stdClass是保留类名,具体作用以后再讲。

    如何初始化一个类?
    可以采用new这个关键字来实例化一个类。例如:
    $p = new person();

    类的数据类型
    我们可以用gettype这个函数来得到数据类型。echo gettype($p) ,得到的类型是 object ,说明类的类型是对象。

    返回顶部