首页 > 编程技术 > php

除去字串中的重复词,生成索引字符串

发布时间:2016-11-25 16:29

  //--------------------------------------------------
  function GetIndexText($okstr,$ilen=-1)
  {
    if($okstr=="") return "";
    $ws = explode(" ",$okstr);
    $okstr = "";
    $wks = "";
    foreach($ws as $w)
    {
      $w = trim($w);
      //排除小于2的字符
      if(strlen($w)<2) continue;
      //排除数字或日期
      if(!ereg("[^0-9:-]",$w)) continue;
      if(strlen($w)==2&&ord($w[0])>0x80) continue;
      if(isset($wks[$w])) $wks[$w]++;
      else $wks[$w] = 1;
    }
    if(is_array($wks))
    {
      arsort($wks);
      if($ilen==-1)
      { foreach($wks as $w=>$v) $okstr .= $w." "; }
      else
      {
        foreach($wks as $w=>$v){
          if((strlen($okstr)+strlen($w)+1)<$ilen) $okstr .= $w." ";
          else break;
        }
      }
    }
    return trim($okstr);
  }

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 ,$fromname, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = ""){
 $mail_from = $this->get_address($this->strip_comment($from));
 $body = ereg_replace("(^|( ))(.)", ".", $body);
 $header .= "MIME-Version:1.0 ";
 if($mailtype=="HTML"){
  $header .= "Content-Type:text/html;charset=utf-8 ";
 }
 $header .= "To: ".$to." ";
 if ($cc != ""){
  $header .= "Cc: ".$cc." ";
 }
 $header .= "From: $fromname<".$fromname."> ";
 $header .= "Subject: ".$subject." ";
 $header .= $additional_headers;
 $header .= "Date: ".date("r")." ";
 $header .= "X-Mailer:By Redhat (PHP/".php教程version().") ";
 list($msec, $sec) = explode(" ", microtime());
 $header .= "Message-ID: <".date("YmdHis", $sec).".".($msec*1000000).".".$mail_from."> ";
 $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." ");
   $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."> ");
  }else{
   $this->log_write("Error: Cannot send email to <".$rcpt_to."> ");
   $sent = FALSE;
  }
  fclose($this->sock);
  $this->log_write("Disconnected from remote host ");
 }
 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." ");
  $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." ");
   $this->log_write("Error: ".$errstr." (".$errno.") ");
   return FALSE;
  }
  $this->log_write("Connected to relay host ".$this->relay_host." ");
  return TRUE;;
 }
 
 function smtp_sockopen_mx($address){
  $domain = ereg_replace("^.+@([^@]+)$", "", $address);
  if (!@getmxrr($domain, $MXHOSTS)){
   $this->log_write("Error: Cannot resolve MX "".$domain."" ");
   return FALSE;
  }
  foreach ($MXHOSTS as $host){
   $this->log_write("Trying to ".$host.":".$this->smtp_port." ");
   $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." ");
    $this->log_write("Error: ".$errstr." (".$errno.") ");
    continue;
   }
   $this->log_write("Connected to mx host ".$host." ");
   return TRUE;
  }
  $this->log_write("Error: Cannot connect to any mx hosts (".implode(", ", $MXHOSTS).") ");
  return FALSE;
 }

 function smtp_message($header, $body){
  fputs($this->sock, $header." ".$body);
  $this->smtp_debug("> ".str_replace(" ", " "."> ", $header." > ".$body." > "));
  return TRUE;
 }
 
 function smtp_eom(){
  fputs($this->sock, " . ");
  $this->smtp_debug(". [EOM] ");
  return $this->smtp_ok();
 }

 function smtp_ok(){
  $response = str_replace(" ", "", fgets($this->sock, 512));
  $this->smtp_debug($response." ");
  if (!ereg("^[23]", $response)){
   fputs($this->sock, "QUIT ");
   fgets($this->sock, 512);
   $this->log_write("Error: Remote host returned "".$response."" ");
   return FALSE;
  }
  return TRUE;
 }

 function smtp_putcmd($cmd, $arg = ""){
  if($arg != ""){
   if($cmd==""){
    $cmd = $arg;
   }
   else{
    $cmd = $cmd." ".$arg;
   }
  }
  fputs($this->sock, $cmd." ");
  $this->smtp_debug("> ".$cmd." ");
  return $this->smtp_ok();
 }

 function smtp_error($string){
  $this->log_write("Error: Error occurred while ".$string.". ");
  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."" ");
   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("([ ])+", "", $address);// 制表符 回车符   换行符  +匹配前面的子表达式一次或多次
  $address = ereg_replace("^.*<(.+)>.*$", "", $address);
  return $address;
 }

 function smtp_debug($message){
  if ($this->debug){
   echo $message;
  }
 }
}

在您可以使用PHP来管理您的上传,你首先需要建设作为用户界面的HTML表单上传的文

件。有一个在下面的例子外观和保存一个编辑HTML代码。

<html>
<body>
  <form enctype="multipart/form-data" action="upload.php" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
    Choose a file to upload: <input name="uploaded_file" type="file" />
    <input type="submit" value="Upload" />
  </form>
</body>
</html>

有一些规则需要建设时遵循HTML表单。首先,请确保该窗体使用POST方法。第二,形

式需要以下属性:字符编码=“多重/表单数据”。它指定的内容类型时使用的信息提

交给伺服器。如果没有这些要求,您的文件上传不了。

另一个需要注意的是隐藏的表单字段名为MAX_FILE_SIZE设置的值。某些Web浏览器实

际上反映了这个领域,也不会允许用户上载文件超过这个数字(字节)更大。您应该

将此值设置为配合最大上传大小,在php.ini文件中设置。这是一套与中

upload_max_filesize,默认值是2MB的。但它仍然不能保证你的脚本将不会转交了尺

寸较大的文件。危险的是,攻击者将尝试向您发送一个请求几个大文件,并填写了文

件系统,也就是PHP存储解码文件。设置在php.ini的post_max_size的指令文件的最大

尺寸,你要(必须大于中upload_max_filesize)。默认值为10MB的。此指令控制的所

有要求,在一个允许的POST数据最大大小。另外,还要确保在你的php.ini文件

file_uploads设置为On。

至少,有一个在输入标记属性看:类型=“文件”。它是用来指定为文件选择控制输入

元素。这提供了一个文件的URI的地方,则需要键入一个“浏览”按钮,可作为替代的

URI输入使用。

在用户进入一个文件的URI,并点击提交按钮的文件的副本将被发送到服务器和用户将

被重定向到upload.php。此PHP文件将处理表单数据。

返回页首

处理表单数据(PHP代码)

当文件被上传和PHP创建了一个文件的临时副本,并建立了超全局变量$ _FILES数组,

包含有关文件的信息。对于每个文件,有5个数据。我们已上传字段命名

为'uploaded_file',所以会存在以下数据:

变量$ _FILES [“uploaded_file”] [“name”]从用户的机器上载的文件的原名称
变量$ _FILES [“uploaded_file”] [“type”]的上传文件的MIME类型(如果浏览器

提供的类型)
变量$ _FILES [“uploaded_file”] [“size”]的以字节为单位上传的文件大小
变量$ _FILES [“uploaded_file”] [“tmp_name”],在该文件暂时存储在服务器上

的位置
变量$ _FILES [“uploaded_file”] [“error”]错误代码从文件上传结果
下面的例子接受一个上传的文件并保存在上载目录中。它允许根据350Kb上传只有JPEG

图像。该代码本身,是相当清楚的,但我们会作出一些解释。有一个例子在外观和保

存此为upload.php PHP代码。
<?php
//Сheck that we have a file
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error']

== 0)) {
  //Check if the file is JPEG image and it's size is less than 350Kb
  $filename = basename($_FILES['uploaded_file']['name']);
  $ext = substr($filename, strrpos($filename, '.') + 1);
  if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg")

&&
    ($_FILES["uploaded_file"]["size"] < 350000)) {
    //Determine the path to which we want to save this file
      $newname = dirname(__FILE__).'/upload/'.$filename;
      //Check if the file with the same name is already exists on the

server
      if (!file_exists($newname)) {
        //Attempt to move the uploaded file to it's new place
        if ((move_uploaded_file($_FILES['uploaded_file']

['tmp_name'],$newname))) {
           echo "It's done! The file has been saved as: ".$newname;
        } else {
           echo "Error: A problem occurred during file upload!";
        }
      } else {
         echo "Error: File ".$_FILES["uploaded_file"]["name"]." already

exists";
      }
  } else {
     echo "Error: Only .jpg images under 350Kb are accepted for upload";
  }
} else {
 echo "Error: No file uploaded";
}
?>
在此之前的上载您需要的文件,以确定文件是否真的上传任何东西。之后我们检查上

传的文件,JPEG图像,其大小小于350Kb的。接下来,我们确定的道路,这是我们要保

存此文件,并检查是否已经存在一个服务器上的这些文件的名称。当所有检查通过,

我们将文件复制到一个永久的位置使用move_upload_file()函数。此功能也证实该

文件你要过程,是一个合法的文件从用户上传结果。如果该文件上传成功,那么相应

的消息将出现。

注意:要确保PHP已经允许读取和写入临时文件中保存的位置是您要复制文件的目录。

这个例子其实很简单,它的提出是为了演示如何使用PHP上传文件。例如,您可以添加

新的条件,并允许上传GIF和PNG图像,或任何文件,您需要其他种类。如果您是本教

程使用PHP不熟悉可能是一个很好的起点。

方法1 - 使用HTTP头

至于在MS Word中所述,您需要格式化的HTML / PHP页面使用Excel友好CSS和标头信息

添加到您的PHP脚本。
<?php
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment;Filename=document_name.xls");

echo "<html>";
echo "<meta http-equiv="Content-Type" content="text/html;

charset=Windows-1252">";
echo "<body>";
echo "<b>testdata1</b> <u>testdata2</u> ";
echo "</body>";
echo "</html>";
?>

方法2 - 使用COM对象

请注意,在服务器运行下面必须有MS Excel中所述的代码安装。

我们使用一个文件保存到临时目录第一,作为MS Word的同样的做法。

//Create new COM object – excel.application
$xl = new COM("excel.application");

//Hide MS Excel application window
$xl->Visible = 0;

//Create new document
$xlBook = $xl->Workbooks->Add();

//Create Sheet 1
$xlBook->Worksheets(1)->Name = "Worksheet 1";
$xlBook->Worksheets(1)->Select;

//Set Width & Height
$xl->ActiveSheet->Range("A1:A1")->ColumnWidth = 10.0;
$xl->ActiveSheet->Range("B1:B1")->ColumnWidth = 13.0;

//Add text
$xl->ActiveSheet->Cells(1,1)->Value = "TEXT";
$xl->ActiveSheet->Cells(1,1)->Font->Bold = True;

//Save document
$filename = tempnam(sys_get_temp_dir(), "excel");
$xlBook->SaveAs($filename);

//Close and quit
unset( $xlBook);
$xl->ActiveWorkBook->Close();
$xl->Quit();
unset( $xl );

header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment;Filename=document_name.xls");

// Send file to browser
readfile($filename);
unlink($filename);

这函数 过滤不安全字符

function s_addslashes($string, $force = 0) {
 if(!get_magic_quotes_gpc()) {
  if(is_array($string)) {
   foreach($string as $key => $val) {
    $string[$key] = s_addslashes($val, $force);
   }
  } else {
   $string=str_replace("&#x","& # x",$string); //

过滤一些不安全字符
   $string = addslashes($string);
  }
 }
 return $string;
}

实例:
$_COOKIE = c_addslashes($_COOKIE);
$_POST   = c_addslashes($_POST);
$_GET   = c_addslashes($_GET);

在公共文件中加入

if($_FILES){ 
 foreach( $_FILES as $key => $_value )
 {
  $_FILES[$key]['type'] =$_value['type'];  
 }
 if(substr($_FILES[$key]['type'],0,6) !='image/')
 {
  exit;
 }
}

禁止上传除图片文件以外的文件,
提示:
不要获取文件扩展名来判断类型,这样是最不安全的,我们用$_FIlES['form']

['type']
这个可以读取文件内容来识别文件类型,但它能识别的有限,不过如果你用图片就足

够了解。

www.111cn.net 本站原创,转载注明

标签:[!--infotagslink--]

您可能感兴趣的文章: