一个无限分类的处理类程序代码

 更新时间:2016年11月25日 17:08  点击:1352
本文章来给大家推荐一个不错的php无限分类代码,采用递归调用的方法,对分类数据只需一次数据库查询可生成树状结构。 无限递归层次(视机器堆栈而定) ,有需要了解的朋友可参考。
 代码如下 复制代码

<?php
/* 名称: 对分类操作的业务逻辑封装
*
* 作者: 帅的像人渣 QQ: 1191391 E-mail: netcat2@21cn.com
*
* 完成日期: 2003-12-18 13:33
*
* 说明: 本类中引用的其它类(DB、Table、Item)均未提供,所以本类只能做个参考,不能直接应用
* 不是本人小气不提供其它类,实在是因为那些都是一两年前写的类,很烂。怕大家看后对大
* 造成误导. 在此发表这个类,只希望大家能从中学到一些程序设计的方法。
* 授人以鱼不如授人以渔~
*
* 特点:
* 采用递归调用的方法,对分类数据只需一次数据库查询可生成树状结构。 无限递归层次(视机器堆栈而定)
*
* 数据库定义:
* ID smallint unsigned primary #如果数据量很大可用int
* ParentID smallint unsigned index #如果数据量很大可用int, 请索引此字段
* #如果为根分类,则ParentID = 0
*
* RootID smallint unsigned index #如果数据量很大可用int, 请索引此字段
* #如果是根分类则RootID = 0, 否则RootID = 最上层的父分类ID
* CategoryName varchar(n) #此大小自定
* 如需有其它字段定义附在后面

* 注意事项:
* 不要试图直接调用本类,除非你有和我定义那另外那几个类相对应的接口, 否则不会成功
* 在合适的地方定义 DBTABLE_CATEGORY 这个常量,使其指向你的分类数据表名字
*
* 程序构架:
* ├─基础类 <!-- 完成底层数据库操作、数据抽象、语言、模板、异常、杂项等)操作 -->
* │
* │
* └─业务逻辑层(此类所处层次) <!-- 利用基础类中数据操作、数据抽象等类根据表现层传递的参数完成数据处理,并返回数据或操作结果 -->
* │
* │
* └───表现层(用户界面) <!-- 利用业务逻辑层将取得的数据或操作数据的结果通过基础类中的界面等类进行显示 -->
*/

define('DBTABLE_CATEGORY', 'xxx');

class Category_Logic
{
var $KernelRef = NULL; //系统核心的引用
var $tblObj = NULL; //包含当前分类数据 Table 类的实例

var $_CurrentItem = NULL; //包含当前分类数据 TItem类的实例

var $CategoryID = 0; //当前分类ID,如果没有当前分类此项为 0

//---------------------------------------------------------------------------
//private array GetNodeData(array $Data, int $ParentNode)
// 根据一颗指定根的并且以兄弟双亲法表示的树和当前分类的ID,返回当前分类在整个分类表中所处的位置
//
// @param: $Data 2维数组 Array(
// Array(
// 'ID' => 分类ID,
// 'ParentID' => 父分类ID,
// 'RootID' => 根分类ID,
// 'CategoryName' => 分类名称,
// ),
// ……
// );
// 表示的一颗树
//
// @param: $ParentNode 父分类ID, 每一次由调用者给出,递归时由程序计算传递
//
// return value: 返回以兄弟双亲法表示的所有分类的树
// 注意: 确保当前分类已经设置,否则此函数无返回
//
//---------------------------------------------------------------------------
function GetNodeData($Data, $ParentNode)
{
$arr = Array();

$ArrayCount = 0;

for($i = 0, $cnt = Count($Data); $i < $cnt; $i++)
{
if($Data[$i]['ParentID'] == $ParentNode)
{
$arr[$ArrayCount] = $Data[$i];
$arr[$ArrayCount++]['Child'] = $this->GetNodeData($Data, $Data[$i]['ID']);
}
}

return $arr;
}

//---------------------------------------------------------------------------
//private String _CurrentLevel(array $Data, int $Current, String $ProcessFunc = '')
// 根据一颗指定根的并且以兄弟双亲法表示的树和当前分类的ID,返回当前分类在整个分类表中所处的位置
//
// @param: $Data 兄弟双亲法表示的树, 由调用者传递
//
// @param: $Current 当前分类ID,第一次调用时由调用者给出,递归时由程序自行计算
//
// @param: $ProcessFunc 指定对分类数据的处理函数, 函数原型定义见 $this->PrintCurrentLevel 中的注释
//
// return value: 返回当前分类在分类树中的位置
// 注意: 确保当前分类已经设置,否则此函数无返回
//
//---------------------------------------------------------------------------
function _CurrentLevel($Data, $Current, $ProcessFunc = '')
{
for($i = 0; $i < Count($Data); $i++)
{
if($Data[$i]['ID'] == $Current)
{
if($Data[$i]['ParentID'] != 0)
{
$str = $this->_CurrentLevel($Data, $Data[$i]['ParentID'], $ProcessFunc) . ' -&gt; ';

if($ProcessFunc) $str .= $ProcessFunc($Data[$i]);
else $str .= $Data[$i]['CategoryName'];
}
else
{
if($ProcessFunc) $str = $ProcessFunc($Data[$i]);
else $str = $Data[$i]['CategoryName'];
}
break;
}
}

return $str;
}

//---------------------------------------------------------------------------
//public Category_Logic(Object &$Kernel, int $CategoryID = -1)
// 本类构造函数
//
// @param: $Kernel 此参数为当前系统核心类的一个引用, 核心类中包括
// 数据库类、输入输出类、系统配置类等
//
// @param: $CategoryID 当前分类ID。
// 当想调用 PrintCurrentLevel、GetRootID、GetParentID、GenerateTypeTreeList及
// 调用_CurrentItem成员的方法时请先设置此值.
//
// 调用GenerateTypeTreeList时设置此值,则没有ID为此的分类默认被选择,没设置则无默认
//
// return value: none
//
//---------------------------------------------------------------------------
function &Category_Logic(&$Kernel, $CategoryID = -1)
{
$this->KernelRef = &$Kernel;

$this->tblObj = new Table($Kernel->DBObj, DBTABLE_CATEGORY);

if($CategoryID != -1)
{
$this->SetCategoryID($CategoryID);
}
}

//---------------------------------------------------------------------------
//public void SetCategoryID(int $CategoryID)
// 设置当前分类ID
//
// return value: none
//
//---------------------------------------------------------------------------
function SetCategoryID($CategoryID)
{
if(!$CategoryID) return;

$Item = new TItem($this->KernelRef->DBObj, DBTABLE_CATEGORY, '*', $CategoryID ,'ID');

$this->_SelfData = &$Item;

$this->CategoryID = $CategoryID;
}

//---------------------------------------------------------------------------
//public int GetRootID()
// 返回当前分类的根分类ID
// 注意:只有设置的当前分类时此函数才有效
//
// return value: 返回当前分类的根分类ID
//
//---------------------------------------------------------------------------
function GetRootID()
{
return $this->_SelfData->Get('RootID');
}

//---------------------------------------------------------------------------
//public int GetParentID()
// 返回当前分类的父分类ID
// 注意:只有设置的当前分类时此函数才有效
//
// return value: 返回当前分类的父分类ID
//
//---------------------------------------------------------------------------
function GetParentID()
{
if($this->CategoryID) return $this->_SelfData->Get('ParentID');
}


//---------------------------------------------------------------------------
//public String GenerateTypeTreeList(array $Data, String $ProcessFunc, int $floor = 0)
// 返回整个分类的树状结构放在OptionList中的列表
//
// @param: $Data 此参数由 $this->DumpTypeDataToTree() 返回
//
// @param: $ProcessFunc 处理显示分类信息的回调函数, 函数原型请参照: $this->PrintCurrentLevel()
//
// @param: $floor 本参数不能人为给出,是程序自动计算的中间值
//
// return value:
// 结构为一颗兄弟双亲表示法表示的树
// 设如分类数据如下:
// ├──1级分类
// │
// │
// │
// ├─2级分类
// │ │
// │ └─3级分类
// │
// └─2级分类
//
// 则返回值为 Array(
// 0 => Array(
// 'ID' => '',
// 'ParentID' => '',
// 'RootID' => '',
// 'CategoryName' => '',
// 'Child' => ....
// )
// .....
// )
//
//---------------------------------------------------------------------------
function DumpTypeDataToTree($RootID = 0, $Fields = '*')
{
$this->tblObj->SetFields($Fields);
$this->tblObj->SetCondition('');

$List = $this->tblObj->MapResult($this->tblObj->Select());

return $this->GetNodeData($List, $RootID);
}

//---------------------------------------------------------------------------
//public String GenerateTypeTreeList(array $Data, String $ProcessFunc = '', int $floor = 0)
// 返回整个分类的树状结构放在OptionList中的列表
//
// @param: $Data 此参数由 $this->DumpTypeDataToTree() 返回
//
// @param: $ProcessFunc 处理显示分类信息的回调函数, 函数原型请参照: $this->PrintCurrentLevel()
//
// @param: $floor 本参数不能人为给出,是程序自动计算的中间值
//
// return value: 返回一个<option>分类名称1</option> ... <option>分类名称n</option>
//
// ps: 调用时echo "<select name='xxxx'>" . $_c->GenerateTypeTreeList($Data, 'ProcessFunc') . "</select>";
//
//---------------------------------------------------------------------------
function GenerateTypeTreeList($Data, $ProcessFunc, $floor = 0)
{
$Str = '';
for($i = 0, $cnt = Count($Data); $i < $cnt; $i++)
{
if($this->CategoryID == $Data[$i]['ID'])
{
$Str .= "<option value='{$Data[$i]['ID']}' selected>"
. str_repeat("&nbsp;", $floor * 3)
. '├'
. ($ProcessFunc ? $ProcessFunc($Data[$i]) : $Data[$i]['CategoryName'])
. "</option>n";
}
else
{
$Str .= "<option value='{$Data[$i]['ID']}'>"
. str_repeat("&nbsp;", $floor * 3)
. '├'
. ($ProcessFunc ? $ProcessFunc($Data[$i]) : $Data[$i]['CategoryName'])
. "</option>n";
}

if($Data[$i]['Child']) $Str .= $this->GenerateTypeTreeList($Data[$i]['Child'], $ProcessFunc, $floor + 1);
}

return $Str;
}

//---------------------------------------------------------------------------
//public String GenerateTypeTreeView(array $Data, String $ProcessFunc = '')
// 返回整个分类的树状结构视图
//
// @param: $Data 此参数由 $this->DumpTypeDataToTree() 返回
//
// @param: $ProcessFunc 处理显示分类信息的回调函数, 函数原型请参照: $this->PrintCurrentLevel()
//
// return value: 返回生成的一颗HTML形式显示的树
//
//---------------------------------------------------------------------------
function GenerateTypeTreeView($Data, $ProcessFunc)
{
$Str = '<ul style="Line-Height:200%">';

for($i = 0, $cnt = Count($Data); $i < $cnt; $i++)
{
if($ProcessFunc) $Str .= '<li>' . $ProcessFunc($Data[$i]) . '</li>' . "n";
else $Str .= '<li>' . $Data[$i]['CategoryName'] . '</li>' . "n";

if($Data[$i]['Child']) $Str .= '<li>' . $this->GenerateTypeTreeView($Data[$i]['Child'], $ProcessFunc) . '</li>';
}

$Str .= '</ul>';

return $Str;
}

//---------------------------------------------------------------------------
//public String PrintCurrentLevel(String $ProcessFunc = '')
// 对多级分类生成当前位置字符串
// 设如分类数据如下,当前分类为3级分类, 则调用返回 1级分类 -> 2级分类 -> 3级分类
// ├──1级分类
// │
// │
// │
// ├─2级分类
// │ │
// │ └─3级分类
// │
// └─2级分类
//
//
//
//
// @param: $ProcessFunc 此为对分类数据如何显示的回调函数,不设置则直接显示分类名称
// 函数定义原型为 function (&$arr);
// 其中$arr参数为每一个分类信息的一维数组如下:
// array(ID => 1, ParentID => 0, RootID => 0, CategoryName => '1级分类')
// 返回值为对上述数据处理的结果,比如返回带链接的分类名字、更改显示颜色等
//
// return value: 返回当前分类在整个分类树中所处位置
//
//---------------------------------------------------------------------------
function PrintCurrentLevel($ProcessFunc = '')
{
if(!$this->CategoryID) return '';

if($this->_SelfData->Get("RootID") == 0)
{
if($ProcessFunc) return $ProcessFunc($this->_SelfData->fetchDataToArray());
else return $this->_SelfData->Get("CategoryName");
}

$Current = $this->CategoryID;

$this->tblObj->SetCondition('RootID = ' . $this->_SelfData->Get('RootID') . " or ID = " . $this->_SelfData->Get('RootID'));

$Data = $this->tblObj->MapResult($this->tblObj->Select());

return $this->_CurrentLevel($Data, $Current, $ProcessFunc);
}

//---------------------------------------------------------------------------
//public boolean Add(array $arr)
// 添加新分类到分类表中
//
// @param: $arr 在此数组中包括对新添加分类的定义, 定义如下:
//
// $arr['RootID'] 新分类所属的根分类ID
// $arr['ParentID'] 新分类的父分类ID
// $arr['CategoryName'] 新分类的名称
//
// return value: 返回添加分类操作结果
//
//---------------------------------------------------------------------------
function Add($arr)
{
$this->tblObj->SetFields(
Array(
'RootID',
'ParentID',
'CategoryName',
)
);

return $this->tblObj->Insert(
Array(
$arr['RootID'],
$arr['ParentID'],
$arr['CategoryName'],
)
);
}

//---------------------------------------------------------------------------
//public boolean Delete(int $ID)
// 删除已经存在的分类
//
// @param: $ID 要删除的分类ID
//
// return value: 返回删除分类操作结果
//
//---------------------------------------------------------------------------
function Delete($ID)
{
$sysOption = &$this->KernelRef->Config;

$this->tblObj->SetFields('*');
$this->tblObj->SetCondition('ID = ' . (int)$ID);

return $this->tblObj->Delete();
}

//---------------------------------------------------------------------------
//public boolean Modify(int $ID, array $arr)
// 修改已经存在的分类
//
// @param: $ID 要修改的分类ID
// @param: $arr 在此数组中包括修改后的分类定义, 定义如下:
//
// $arr['RootID'] 新分类所属的根分类ID
// $arr['ParentID'] 新分类的父分类ID
// $arr['CategoryName'] 新分类的名称
//
// return value: 返回修改分类操作结果
//
//---------------------------------------------------------------------------
function Modify($ID, $arr)
{
$this->tblObj->SetCondition('ID = ' . (int)$ID);

$prev = $this->tblObj->MapOneRow($this->tblObj->Select());

$this->tblObj->SetFields(
Array(
'RootID',
'ParentID',
'CategoryName',
)
);

return $this->tblObj->Update($arr);
}

//---------------------------------------------------------------------------
//public array Modify(int $ID)
// 修改已经存在的分类
//
// @param: $ID 指定的分类ID
//
// return value: 返回指定ID分类的信息
// 数组中包括:
// Array(
// 'ID' => 分类ID,
// 'ParentID' => 父分类ID,
// 'RootID' => 根分类ID,
// 'CategoryName' => 分类名称,
// );
//
//---------------------------------------------------------------------------
function GetCategory($ID)
{
$this->tblObj->SetCondition('ID = ' . (int)$ID);

return $this->tblObj->MapOneRow($this->tblObj->Select());
}
}
?>
 

本文章给大家分享的文件操作类包括对文件和文件夹创建,复制,移动和删除,有需要对文件操作学习的同学可进入参考参考。

实例

 代码如下 复制代码

<?php
/**
* 操纵文件类
*
* 例子:
* FileUtil::createDir('a/1/2/3');                    测试建立文件夹 建一个a/1/2/3文件夹
* FileUtil::createFile('b/1/2/3');                    测试建立文件        在b/1/2/文件夹下面建一个3文件
* FileUtil::createFile('b/1/2/3.exe');             测试建立文件        在b/1/2/文件夹下面建一个3.exe文件
* FileUtil::copyDir('b','d/e');                    测试复制文件夹 建立一个d/e文件夹,把b文件夹下的内容复制进去
* FileUtil::copyFile('b/1/2/3.exe','b/b/3.exe'); 测试复制文件        建立一个b/b文件夹,并把b/1/2文件夹中的3.exe文件复制进去
* FileUtil::moveDir('a/','b/c');                    测试移动文件夹 建立一个b/c文件夹,并把a文件夹下的内容移动进去,并删除a文件夹
* FileUtil::moveFile('b/1/2/3.exe','b/d/3.exe'); 测试移动文件        建立一个b/d文件夹,并把b/1/2中的3.exe移动进去                  
* FileUtil::unlinkFile('b/d/3.exe');             测试删除文件        删除b/d/3.exe文件
* FileUtil::unlinkDir('d');                      测试删除文件夹 删除d文件夹
*/
class FileUtil {
/**
    * 建立文件夹
    *
    * @param string $aimUrl
    * @return viod
    */
function createDir($aimUrl) {
       $aimUrl = str_replace('', '/', $aimUrl);
       $aimDir = '';
       $arr = explode('/', $aimUrl);
       foreach ($arr as $str) {
         $aimDir .= $str . '/';
         if (!file_exists($aimDir)) {
            mkdir($aimDir);
         }
       }
}
/**
    * 建立文件
    *
    * @param string $aimUrl
    * @param boolean $overWrite 该参数控制是否覆盖原文件
    * @return boolean
    */
function createFile($aimUrl, $overWrite = false) {
       if (file_exists($aimUrl) && $overWrite == false) {
         return false;
       } elseif (file_exists($aimUrl) && $overWrite == true) {
         FileUtil::unlinkFile($aimUrl);
       }
       $aimDir = dirname($aimUrl);
       FileUtil::createDir($aimDir);
       touch($aimUrl);
       return true;
}
/**
    * 移动文件夹
    *
    * @param string $oldDir
    * @param string $aimDir
    * @param boolean $overWrite 该参数控制是否覆盖原文件
    * @return boolean
    */
function moveDir($oldDir, $aimDir, $overWrite = false) {
       $aimDir = str_replace('', '/', $aimDir);
       $aimDir = substr($aimDir, -1) == '/' ? $aimDir : $aimDir . '/';
       $oldDir = str_replace('', '/', $oldDir);
       $oldDir = substr($oldDir, -1) == '/' ? $oldDir : $oldDir . '/';
       if (!is_dir($oldDir)) {
         return false;
       }
       if (!file_exists($aimDir)) {
         FileUtil::createDir($aimDir);
       }
       @$dirHandle = opendir($oldDir);
       if (!$dirHandle) {
         return false;
       }
       while(false !== ($file = readdir($dirHandle))) {
         if ($file == '.' || $file == '..') {
            continue;
         }
         if (!is_dir($oldDir.$file)) {
            FileUtil::moveFile($oldDir . $file, $aimDir . $file, $overWrite);
         } else {
            FileUtil::moveDir($oldDir . $file, $aimDir . $file, $overWrite);
         }
       }
       closedir($dirHandle);
       return rmdir($oldDir);
}
/**
    * 移动文件
    *
    * @param string $fileUrl
    * @param string $aimUrl
    * @param boolean $overWrite 该参数控制是否覆盖原文件
    * @return boolean
    */
function moveFile($fileUrl, $aimUrl, $overWrite = false) {
       if (!file_exists($fileUrl)) {
         return false;
       }
       if (file_exists($aimUrl) && $overWrite = false) {
         return false;
       } elseif (file_exists($aimUrl) && $overWrite = true) {
         FileUtil::unlinkFile($aimUrl);
       }
       $aimDir = dirname($aimUrl);
       FileUtil::createDir($aimDir);
       rename($fileUrl, $aimUrl);
       return true;
}
/**
    * 删除文件夹
    *
    * @param string $aimDir
    * @return boolean
    */
function unlinkDir($aimDir) {
       $aimDir = str_replace('', '/', $aimDir);
       $aimDir = substr($aimDir, -1) == '/' ? $aimDir : $aimDir.'/';
       if (!is_dir($aimDir)) {
         return false;
       }
       $dirHandle = opendir($aimDir);
       while(false !== ($file = readdir($dirHandle))) {
         if ($file == '.' || $file == '..') {
            continue;
         }
         if (!is_dir($aimDir.$file)) {
            FileUtil::unlinkFile($aimDir . $file);
         } else {
            FileUtil::unlinkDir($aimDir . $file);
         }
       }
       closedir($dirHandle);
       return rmdir($aimDir);
}
/**
    * 删除文件
    *
    * @param string $aimUrl
    * @return boolean
    */
function unlinkFile($aimUrl) {
       if (file_exists($aimUrl)) {
         unlink($aimUrl);
         return true;
       } else {
         return false;
       }
}
/**
    * 复制文件夹
    *
    * @param string $oldDir
    * @param string $aimDir
    * @param boolean $overWrite 该参数控制是否覆盖原文件
    * @return boolean
    */
function copyDir($oldDir, $aimDir, $overWrite = false) {
       $aimDir = str_replace('', '/', $aimDir);
       $aimDir = substr($aimDir, -1) == '/' ? $aimDir : $aimDir.'/';
       $oldDir = str_replace('', '/', $oldDir);
       $oldDir = substr($oldDir, -1) == '/' ? $oldDir : $oldDir.'/';
       if (!is_dir($oldDir)) {
         return false;
       }
       if (!file_exists($aimDir)) {
         FileUtil::createDir($aimDir);
       }
       $dirHandle = opendir($oldDir);
       while(false !== ($file = readdir($dirHandle))) {
         if ($file == '.' || $file == '..') {
            continue;
         }
         if (!is_dir($oldDir . $file)) {
            FileUtil::copyFile($oldDir . $file, $aimDir . $file, $overWrite);
         } else {
            FileUtil::copyDir($oldDir . $file, $aimDir . $file, $overWrite);
         }
       }
       return closedir($dirHandle);
}
/**
    * 复制文件
    *
    * @param string $fileUrl
    * @param string $aimUrl
    * @param boolean $overWrite 该参数控制是否覆盖原文件
    * @return boolean
    */
function copyFile($fileUrl, $aimUrl, $overWrite = false) {
       if (!file_exists($fileUrl)) {
         return false;
       }
       if (file_exists($aimUrl) && $overWrite == false) {
         return false;
       } elseif (file_exists($aimUrl) && $overWrite == true) {
         FileUtil::unlinkFile($aimUrl);
       }
       $aimDir = dirname($aimUrl);
       FileUtil::createDir($aimDir);
       copy($fileUrl, $aimUrl);
       return true;
}
}
?>

在php中我们经常会来利用正则表达式来验证用户输入的信息是不是邮箱地址了,下面我来给大家介绍判断邮箱地址的正则表达式详解

判断邮件的一个正则表达式,逐句解释下是什么意思

 代码如下 复制代码

^(w+((-w+)|(.w+))*)+w+((-w+)|(.w+))*@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+)*.[A-Za-z0-9]+$

 
^   匹配字符串头

(w+((-w+)|(.w+))*) 1:这里匹配laidfj456、sfi-lsoke、fe.23i这样的字符串

+   匹配加号

w+((-w+)|(.w+))* 同1

@   匹配@

[A-Za-z0-9]+  2:由大小写字母和数字?成的字符串,等价于w+

((.|-)[A-Za-z0-9]+)*   匹配0个或多个由"."或"-"开头的字符串,如.oeiu234mJ、-oiwuer4

.   匹配"."

[A-Za-z0-9]+  同2

$   匹配字符串的?尾

实例

 代码如下 复制代码

<?php
/**
 * 邮件的正则表达式  @author:lijianghai
 */
 function  isEmail($input = null)
 {  //用户名:以数字、字母、下滑线组成;
  $email = $input;
  /*使用preg_ereg()出错:因为第二个参数需要是数组
   * if(preg_grep("^[a-zA-Z][a-zA-Z0-9_]{3,19}@[0-9A-Za-z]{1,10}(.)(com|cn|net|com.cn)$", array($input)))
  {
   echo $email.'是符合条件的邮件地址';
  }else
  {
   echo $email.'格式错误';
  }
  */
  if(ereg("^[a-zA-Z][a-zA-Z0-9_]{3,9}@[0-9a-zA-Z]{1,10}(.)(com|cn|com.cn|net)$",$email))
  {
   echo $email."符合格式规范";
  }
  else
  {
   echo  $email.'格式错误';
  }
 }
 $email = "";
 isEmail($email);
?>

PHP CURL的作用对于很多应用来说有很大的用处,下面我来详细介绍php curl用法详解,有需要了解的朋友可进入参考。

PHP中的CURL函数库(Client URL Library Function)

curl_close — 关闭一个curl会话
curl_copy_handle — 拷贝一个curl连接资源的所有内容和参数
curl_errno — 返回一个包含当前会话错误信息的数字编号
curl_error — 返回一个包含当前会话错误信息的字符串
curl_exec — 执行一个curl会话
curl_getinfo — 获取一个curl连接资源句柄的信息
curl_init — 初始化一个curl会话
curl_multi_add_handle — 向curl批处理会话中添加单独的curl句柄资源
curl_multi_close — 关闭一个批处理句柄资源
curl_multi_exec — 解析一个curl批处理句柄
curl_multi_getcontent — 返回获取的输出的文本流
curl_multi_info_read — 获取当前解析的curl的相关传输信息
curl_multi_init — 初始化一个curl批处理句柄资源
curl_multi_remove_handle — 移除curl批处理句柄资源中的某个句柄资源
curl_multi_select — Get all the sockets associated with the cURL extension, which can then be "selected"
curl_setopt_array — 以数组的形式为一个curl设置会话参数
curl_setopt — 为一个curl设置会话参数
curl_version — 获取curl相关的版本信息

curl_init()函数的作用初始化一个curl会话,curl_init()函数唯一的一个参数是可选的,表示一个url地址。
curl_exec()函数的作用是执行一个curl会话,唯一的参数是curl_init()函数返回的句柄。
curl_close()函数的作用是关闭一个curl会话,唯一的参数是curl_init()函数返回的句柄。

1. php curl的默认调用方法,get方式访问url

 代码如下 复制代码

....
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //设置http头
curl_setopt($ch, CURLOPT_ENCODING, "gzip" ); //设置为客户端支持gzip压缩
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30 ); //设置连接等待时间
curl_setopt($ch, CURLOPT_URL, $url );
curl_exec( $ch );
if ($error = curl_error($ch) ) {
//出错处理
return -1;
}
fclose($fp);

$curl_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //获取http返回值
if( $curl_code == 200 ) {
//正常访问url
}
//异常
....

2. 设置http header支持curl访问lighttpd服务器
Java代码

 代码如下 复制代码
$header[]= 'Expect:';

$header[]= 'Expect:';
3. 设置curl,只获取http header,不获取body:
Java代码

 代码如下 复制代码

curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);

curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);

或者只获取body:
Java代码

 代码如下 复制代码

curl_setopt($ch, CURLOPT_HEADER, 0); // make sure we get the body
curl_setopt($ch, CURLOPT_NOBODY, 0);

curl_setopt($ch, CURLOPT_HEADER, 0); // make sure we get the body
curl_setopt($ch, CURLOPT_NOBODY, 0);

4. 访问虚拟主机,需设置Host

 代码如下 复制代码
$header[]= 'Host: '.$host;

5. 使用post, put, delete等REStful方式访问url
post:

 代码如下 复制代码
curl_setopt($ch, CURLOPT_POST, 1 );
put, delete:
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); //或者PUT,需要服务器支持这些方法。

6. 保存下载内容为文件

 代码如下 复制代码
curl_setopt($ch, CURLOPT_FILE, $fp);

模拟POST请求

 

 代码如下 复制代码
<?PHP
    $url = 'POST_URL';
    $fields=array(
        'a' => 'a',
        'b'   => 'b',
    );
     
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, count($fields));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    ob_start();
    curl_exec($ch);
     
    $result = ob_get_contents();
     
    ob_end_clean();
    echo $result;
    curl_close($ch);
?>

模仿get登录

 代码如下 复制代码


<?
session_start();
$url = 'http://localhost/test/loginAct.php';
$post = 1;
$returntransfer = 1;
$port = 80;
$header = 0;
$nobody = 0;
$followlocation = 1;
$cookie_jar = $_SESSION['cookie_jar'];
$request = 'userName=huyan&pwd='.sha1(yanyan).'&ac=login';
$ch = curl_init();
$options = array(CURLOPT_URL => $url,
                    CURLOPT_HEADER => $header,
                    CURLOPT_NOBODY => $nobody,
                    CURLOPT_PORT => $port,
                    CURLOPT_POST => $post,
                    CURLOPT_POSTFIELDS => $request,
                    CURLOPT_RETURNTRANSFER => $returntransfer,
                    CURLOPT_FOLLOWLOCATION => $followlocation,
                    CURLOPT_COOKIEJAR => $cookie_jar,
                    CURLOPT_COOKIEFILE => $cookie_jar,
                    CURLOPT_REFERER => $url
                    );
curl_setopt_array($ch, $options);
$temp = curl_exec($ch);
curl_errno($ch);
curl_close($ch);
echo $temp;
?>

注意,如果你的curl不可以使用我们可以参考下面方法来打开

启php curl函数库的步骤

  1).去掉windows/php.ini 文件里;extension=php_curl.dll前面的; /*用 echo phpinfo();查看php.ini的路径*/

  2).把php5/libeay32.dll,ssleay32.dll复制到系统目录windows/下

  3).重启apache


配置php支持curl

  curl是一个利用URL语法在命令行方式下工作的文件传输工具。它支持很多协议:FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE 以及 LDAP。curl同样支持HTTPS认证,HTTP POST方法, HTTP PUT方法, FTP上传, kerberos认证, HTTP上传, 代理服务器, cookies, 用户名/密码认证, 下载文件断点续传, 上载文件断点续传, http代理服务器管道( proxy tunneling), 甚至它还支持IPv6, socks5代理服务器, 通过http代理服务器上传文件到FTP服务器等等,功能十分强大。Windows操作系统下的网络蚂蚁,网际快车(FlashGet)的功能它都可以做到。准确的说,curl支持文件的上传和下载,所以是一个综合传输工具,但是按照传统,用户习惯称curl为下载工具。

  配置方法:

  1、拷贝PHP目录中的libeay32.dll 和 ssleay32.dll 两个文件到 system32 目录。

  2、修改php.ini:配置好 extension_dir ,去掉 extension = php_curl.dll 前面的分号。

  ---------------------------

  php下扩展php_curl.dll的安装

  ---------------------------

  已经内置有php_curl.dll,在ext目录下,此DLL用于支持SSL和zlib.

  在php.ini中找到有extension=php_curl.dll, 去掉前面的注释.

  设置extension_dir=c:phpext, 刷新PHP页面时报错, 说找不到模块php_curl.dll.

  拷贝php_curl.dll 到windowssystem32,还是同样的错.

  在网上找了一下,需要将:

  libeay32.dll, ssleay32.dll, php5ts.dll, php_curl.dll

  都拷贝到system32目录下,重启IIS即可.

在php中匹配数字与字母很简单,但是匹配中文汉字时就会出现一些问题了,下面我来给大家介绍在php中匹配中文,数字,字母的一些方法。

方法一

 代码如下 复制代码

if(preg_match("/^d*$/",   "4312"))
{
echo   "全数字
";
}

if(preg_match("/^[a-z]*$/i",   "fdsFDfd"))
{
echo   "全字母
";
}

if(preg_match("/^[a-zd]*$/i",   "fd4fd34"))
{
echo   "有数字有字母
";
}

中文汉字

 代码如下 复制代码

$username=$_REQUEST['username'];
if(!preg_match("/^[a-z0-9xa1-xff]{3,10}$/",$username))
 {
  echo"34r345";
  exit;
 }


上面是比较散的,下面把几个总结到一起来

 代码如下 复制代码

$input_tag = $_POST['tag'];
$input_tag = explode(',', $input_tag);
$input_tag = array_unique($input_tag);
$input_tag = array_diff($input_tag, array(null));
$leng      = '';
$true      = '';
$comma     = '';
 
foreach ($input_tag as $v) {
    if (strlen($v) > 18) {
        $leng  .= $comma . $v;
        $comma = ',';
    }
 
    $true .= $comma . $v;
    $comma = ',';
}
 
$true = str_replace(',', '', $true);
if (!preg_match('/^[x80-xff_a-zA-Z0-9]+$/', $true)) {
    echo "<script>alert('不允许特殊符号的!!!');</script>";
    exit;
}
 
if (!empty($leng)) {
    echo "<script>alert('一个标签只能是6个汉字以内哦!!!');</script>";
    exit;
}

[!--infotagslink--]

相关文章

  • Windows批量搜索并复制/剪切文件的批处理程序实例

    这篇文章主要介绍了Windows批量搜索并复制/剪切文件的批处理程序实例,需要的朋友可以参考下...2020-06-30
  • BAT批处理判断服务是否正常运行的方法(批处理命令综合应用)

    批处理就是对某对象进行批量的处理,通常被认为是一种简化的脚本语言,它应用于DOS和Windows系统中。这篇文章主要介绍了BAT批处理判断服务是否正常运行(批处理命令综合应用),需要的朋友可以参考下...2020-06-30
  • PHP file_get_contents设置超时处理方法

    file_get_contents的超时处理话说,从PHP5开始,file_get_content已经支持context了(手册上写着:5.0.0 Added the context support. ),也就是说,从5.0开始,file_get_contents其实也可以POST数据。今天说的这篇是讲超时的,确实在...2013-10-04
  • C#多线程中的异常处理操作示例

    这篇文章主要介绍了C#多线程中的异常处理操作,涉及C#多线程及异常的捕获、处理等相关操作技巧,需要的朋友可以参考下...2020-06-25
  • postgresql 中的时间处理小技巧(推荐)

    这篇文章主要介绍了postgresql 中的时间处理小技巧(推荐),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-03-29
  • Python同时处理多个异常的方法

    这篇文章主要介绍了Python同时处理多个异常的方法,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下...2020-07-29
  • C#异常处理中try和catch语句及finally语句的用法示例

    这篇文章主要介绍了C#异常处理中try和catch语句及finally语句的用法示例,finally语句的使用涉及到了C#的垃圾回收特性,需要的朋友可以参考下...2020-06-25
  • python用moviepy对视频进行简单的处理

    这篇文章主要介绍了python如何用moviepy对视频进行简单的处理,帮助大家更好的利用python处理视频,感兴趣的朋友可以了解下...2021-03-11
  • php无限分类使用concat如何实现

    一、数据库设计 -- -- Table structure for table `category` -- CREATE TABLE `category` ( `id` int(11) NOT NULL auto_increment, `catpath` varchar(255) default NULL, `name` varchar(255) default NULL...2015-11-08
  • C#异常处理详解

    这篇文章介绍了C#异常处理,有需要的朋友可以参考一下...2020-06-25
  • sql server日志处理不当造成的隐患详解

    这篇文章主要给大家介绍了关于sql server日志处理不当造成的隐患的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用sql server具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧...2020-07-11
  • PHP无限分类(树形类)

    复制代码 代码如下:<?php//模拟PHP无限分类查询结果return array( array( 'id'=>1, 'pid'=>0, 'name'=>'主页' ), array( 'id'=>2, 'pid'=>0, 'name...2013-10-04
  • Spring MVC 处理一个请求的流程

    Spring MVC是Spring系列框架中使用频率最高的部分。不管是Spring Boot还是传统的Spring项目,只要是Web项目都会使用到Spring MVC部分。因此程序员一定要熟练掌握MVC部分。本篇博客简要分析Spring MVC处理一个请求的流程。...2021-02-06
  • go语言中的Carbon库时间处理技巧

    这篇文章主要介绍了go语言中的Carbon库时间处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-02-05
  • C++异常处理入门(try和catch)

    C++ 提供了异常机制,让我们能够捕获运行时错误,本文就详细的介绍了C++异常处理入门,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-08-09
  • C#事务处理(Execute Transaction)实例解析

    这篇文章主要介绍了C#事务处理(Execute Transaction)实例解析,对于理解和学习事务处理有一定的帮助,需要的朋友可以参考下...2020-06-25
  • php图像处理(缩放、剪裁、缩放、翻转、旋转、透明、锐化)

    本文章来给各同学总结了一些常用的图像处理函数,包括有缩放、剪裁、缩放、翻转、旋转、透明、锐化功能,大家可参考参考。 注意事项:如果要使用php gd处理我们需要...2016-11-25
  • Python编程OpenCV和Numpy图像处理库实现图片去水印

    这篇文章主要介绍了Python编程中如何实现图片去水印本文采用了OpenCV和Numpy的图像处理的方法来实现,文中附含详细示例代码,有需要的朋友可以借鉴参考下...2021-09-26
  • javascript表单处理具体实现代码(表单、链接、按钮)

    这篇文章主要介绍了javascript表单处理具体实现代码,包括各种表单、链接、按钮控件介绍,感兴趣的朋友可以参考一下...2016-05-09
  • JavaScript 事件流、事件处理程序及事件对象总结

    JS与HTML之间的交互通过事件实现。事件就是文档或浏览器窗口中发生的一些特定的交互瞬间。可以使用监听器(或处理程序)来预定事件,以便事件发生时执行相应的代码。本文将介绍JS事件相关的基础知识。...2017-04-03