php身份证校验码的计算例子

 更新时间:2016年11月25日 15:39  
下面来给各位同学介绍一个php身份证校验码的计算例子,希望本函数代码能帮助到各位同学哦。 例子


代码如下
复制代码



public function id_ver
下面来给各位同学介绍一个php身份证校验码的计算例子,希望本函数代码能帮助到各位同学哦。

例子

 代码如下 复制代码

public function id_verify($my_id) {
 
    $coefficient = array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);
 
    $remainder_map = array(1,0,'X',9,8,7,6,5,4,3,2);
 
    $count = 0;
     
    for ($i=0; $i < 17; $i++) {
         
        $count += $my_id[$i] * $coefficient[$i];
    }
 
    $remainder = $count % 11;
 
    if ($my_id[17] == $remainder_map[$remainder]){
 
        echo 'true';
    }else{
 
        echo 'false';
    }
}

使用方法很简单

 代码如下 复制代码

$body = '44010221990101001';
id_verify($my_id) //就会有结果输出的哦

php中SOAP WebService的wsdl文件生成类是一段老外写的代码非常的简单好用了并且我用了很久没碰到过什么问题,希望对各位有帮助。

代码如下

 代码如下 复制代码

class SoapDiscovery {

    private $class_name = '';
    private $service_name = '';

    /**
     * SoapDiscovery::__construct() SoapDiscovery class Constructor.
     *
     * @param string $class_name
     * @param string $service_name
     * */
    public function __construct($class_name = '', $service_name = '') {
        $this->class_name = $class_name;
        $this->service_name = $service_name;
    }

    /**
     * SoapDiscovery::getWSDL() Returns the WSDL of a class if the class is instantiable.
     *
     * @return string
     * */
    public function getWSDL() {
        if (empty($this->service_name)) {
            throw new Exception('No service name.');
        }
        $headerWSDL = "<!--?xml version=\"1.0\" ?-->\n";
        $headerWSDL.= "<definitions name="\"$this-">service_name\" targetNamespace=\"urn:$this->service_name\" xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" xmlns:tns=\"urn:$this->service_name\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns=\"http://schemas.xmlsoap.org/wsdl/\">\n";
        $headerWSDL.= "<types xmlns="\"http://schemas.xmlsoap.org/wsdl/\"">\n";

        if (empty($this->class_name)) {
            throw new Exception('No class name.');
        }

        $class = new ReflectionClass($this->class_name);

        if (!$class->isInstantiable()) {
            throw new Exception('Class is not instantiable.');
        }

        $methods = $class->getMethods();

        $portTypeWSDL = '<porttype name="' . $this->service_name . 'Port">';
        $bindingWSDL = '<binding name="' . $this->service_name . 'Binding" type="tns:' . $this->service_name . " port\"="">\n<soap:binding style="\"rpc\"" transport="\"http://schemas.xmlsoap.org/soap/http\"">\n";
        $serviceWSDL = '<service name="' . $this->service_name . " \"="">\n<documentation>\n<port name="\""" .="" $this-="">service_name . 'Port" binding="tns:' . $this->service_name . "Binding\"><soap:address location="\"http://"" .="" $_server['server_name']="" ':'="" $_server['server_port']="" $_server['php_self']="" "\"="">\n</soap:address></port>\n</documentation></service>\n";
        $messageWSDL = '';
        foreach ($methods as $method) {
            if ($method->isPublic() && !$method->isConstructor()) {
                $portTypeWSDL.= '<operation name="' . $method->getName() . " \"="">\n" . '<input message="tns:' . $method->getName() . " request\"="">\n<output message="\"tns:"" .="" $method-="">getName() . "Response\" />\n</output></operation>\n";
                $bindingWSDL.= '<operation name="' . $method->getName() . " \"="">\n" . '<soap:operation soapaction="urn:' . $this->service_name . '#' . $this->class_name . '#' . $method->getName() . " \"="">\n<input><soap:body use="\"encoded\"" namespace="\"urn:$this-">service_name\" encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" />\n\n<output>\n<soap:body use="\"encoded\"" namespace="\"urn:$this-">service_name\" encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" />\n</soap:body></output>\n</soap:body></soap:operation></operation>\n";
                $messageWSDL.= '<message name="' . $method->getName() . " request\"="">\n";
                $parameters = $method->getParameters();
                foreach ($parameters as $parameter) {
                    $messageWSDL.= '<part name="' . $parameter->getName() . " \"="" type="\"xsd:string\"">\n";
                }
                $messageWSDL.= "</part></message>\n";
                $messageWSDL.= '<message name="' . $method->getName() . " response\"="">\n";
                $messageWSDL.= '<part name="' . $method->getName() . " \"="" type="\"xsd:string\"">\n";
                $messageWSDL.= "</part></message>\n";
            }
        }
        $portTypeWSDL.= "</soap:binding></binding></porttype>\n";
        $bindingWSDL.= "\n";
        return sprintf('%s%s%s%s%s%s', $headerWSDL, $portTypeWSDL, $bindingWSDL, $serviceWSDL, $messageWSDL, '</types></definitions>');
    }

    /**
     * SoapDiscovery::getDiscovery() Returns discovery of WSDL.
     *
     * @return string
     * */
    public function getDiscovery() {
        return "<!--?xml version=\"1.0\" ?-->\n<disco:discovery xmlns:disco="\"http://schemas.xmlsoap.org/disco/\"" xmlns:scl="\"http://schemas.xmlsoap.org/disco/scl/\"">\n<scl:contractref ref="\"http://"" .="" $_server['server_name']="" ':'="" $_server['server_port']="" $_server['php_self']="" "?wsdl\"="">\n</scl:contractref></disco:discovery>";
    }

}

使用方法

 代码如下 复制代码
$a = new SoapDiscovery();

然后里面的方法与类就可以直接调用了哦。

在网上看到有很多关于截取中文字符串的一些函数,在此本文章就为各位整理一下这些常用的截取中文字符串的例子吧,希望例子能帮助到大家哦。

常用的php函数

strstr(string,string)            //从前面第一次出现某个字符串的地方截取到最后
strrchr(string,string)         //从某个字符串从最后出现的位置截取到结尾
strpos(string,string[,int])  //某个字符串第一次出现的位置
strrpos(string,string)      //某个字符串最后一次出现的位置
substr(string,int[,int])    //从指定位置开始截取字符串,可以指定截取的长度。
strlen(string)               //获取字符串的长度PHP截取开始和结束标记间的字符

方法一:利用explode对字符串进行分

 代码如下 复制代码

/**
* Get the content between $start and $end
*
* @param string $content 原始字符
* @param string $start     起始字符
* @param string $end      结束字符
* @return string
*/
function GetStringBetween($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
        return $r[0];
    }
    return '';
}


方法二:利用substr截取字符,由于php组件函数,因此字符串处理效率比explode方法要高一些

 代码如下 复制代码

/**
* Get the content between $start and $end
*
* @param string $content 原始字符
* @param string $start     起始字符
* @param string $end      结束字符
* @return string
*/
function get_string_between($string, $start, $end){
    $string = " ".$string;
    $ini = strpos($string,$start);
    if ($ini == 0) return "";
    $ini += strlen($start);
    $len = strpos($string,$end,$ini) - $ini;
    return substr($string,$ini,$len);
}


 

PHP截取所有符合起始与结束标记的字符串

 代码如下 复制代码


/**
* Get all every strings between two tags
*
* @param string $string 原始字符串
* @param string $start  起始字符串
* @param string $end   结束字符串
* @return array
*/
function get_all_strings_between($string,$start,$end)
{
    //Returns an array of all values which are between two tags in a set of data
    $strings = array();
    $startPos = 0;
    $i = 0;
    //echo strlen($string)."n";
    while($startPos < strlen($string) && $matched = get_string_between(substr($string,$startPos),$start,$end))
    {
        if ($matched == null || $matched[1] == null || $matched[1] == '') break;
        $startPos = $matched[0]+$startPos+1;
        array_push($strings,$matched[1]);
        $i++;
    }
    return $strings;
}

function get_string_between($string, $start, $end){
    $ini = strpos($string,$start);
    if ($ini == 0) return null;
    $ini += strlen($start);
    $len = strpos($string,$end,$ini) - $ini;
    return array($ini+$len,substr($string,$ini,$len));
}


php截取起始与结束标记间字符,带截取次数、是否允许重复选项

 代码如下 复制代码

 

/**
* Get all every strings between two tags
*
* @param string $string 原始字符串
* @param string $start  起始字符串
* @param string $end   结束字符串
* @return array
*/
function get_all_strings_between($string,$start,$end)
{
    //Returns an array of all values which are between two tags in a set of data
    $strings = array();
    $startPos = 0;
    $i = 0;
    //echo strlen($string)."n";
    while($startPos < strlen($string) && $matched = get_string_between(substr($string,$startPos),$start,$end))
    {
        if ($matched == null || $matched[1] == null || $matched[1] == '') break;
        $startPos = $matched[0]+$startPos+1;
        array_push($strings,$matched[1]);
        $i++;
    }
    return $strings;
}

function get_string_between($string, $start, $end){
    $ini = strpos($string,$start);
    if ($ini == 0) return null;
    $ini += strlen($start);
    $len = strpos($string,$end,$ini) - $ini;
    return array($ini+$len,substr($string,$ini,$len));
}

截取GB2312中文字符串

 代码如下 复制代码

< ?php
//截取中文字符串
function mysubstr($str, $start, $len) {
$tmpstr = "";
$strlen = $start + $len;
for($i = 0; $i < $strlen; $i++) {
if(ord(substr($str, $i, 1)) > 0xa0) {
$tmpstr .= substr($str, $i, 2);
$i++;
} else
$tmpstr .= substr($str, $i, 1);
}
return $tmpstr;
}
?>


截取utf8编码的多字节字符串

 代码如下 复制代码

< ?php
//截取utf8字符串
function utf8Substr($str, $from, $len)
{
return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
'((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
'$1',$str);
}
?>

下面一个自己开发应用中会常用到的一款数据库操作类代码,下面有两个文件一个是配置文件一个是操作数据库类,最后简单的列举了这个例类的调用方法。

配置文件 config.db.php

 代码如下 复制代码


<?php
    $db_config["hostname"] = "localhost"; //服务器地址
    $db_config["username"] = "root"; //数据库用户名
    $db_config["password"] = "123"; //数据库密码
    $db_config["database"] = "test"; //数据库名称
    $db_config["charset"] = "utf8";//数据库编码
    $db_config["pconnect"] = 1;//开启持久连接
    $db_config["log"] = 1;//开启日志
    $db_config["logfilepath"] = './';//开启日志
?>

数据库操作类

 代码如下 复制代码

<!--?php
Class DB {
 
    private $link_id;
    private $handle;
    private $is_log;
    private $time;
 
    //构造函数
    public function __construct() {
        $this--->time = $this->microtime_float();
        require_once("config.db.php");
        $this->connect($db_config["hostname"], $db_config["username"], $db_config["password"], $db_config["database"], $db_config["pconnect"]);
        $this->is_log = $db_config["log"];
        if($this->is_log){
            $handle = fopen($db_config["logfilepath"]."dblog.txt", "a+");
            $this->handle=$handle;
        }
    }
     
    //数据库连接
    public function connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect = 0,$charset='utf8') {
        if( $pconnect==0 ) {
            $this->link_id = @mysql_connect($dbhost, $dbuser, $dbpw, true);
            if(!$this->link_id){
                $this->halt("数据库连接失败");
            }
        } else {
            $this->link_id = @mysql_pconnect($dbhost, $dbuser, $dbpw);
            if(!$this->link_id){
                $this->halt("数据库持久连接失败");
            }
        }
        if(select_db($dbname,$this-%3Elink_id">[email protected]_select_db($dbname,$this->link_id)) {
            $this->halt('数据库选择失败');
        }
        @mysql_query("set names ".$charset);
    }
     
    //查询
    public function query($sql) {
        $this->write_log("查询 ".$sql);
        $query = mysql_query($sql,$this->link_id);
        if(!$query) $this->halt('Query Error: ' . $sql);
        return $query;
    }
     
    //获取一条记录(MYSQL_ASSOC,MYSQL_NUM,MYSQL_BOTH)           
    public function get_one($sql,$result_type = MYSQL_ASSOC) {
        $query = $this->query($sql);
        $rt =& mysql_fetch_array($query,$result_type);
        $this->write_log("获取一条记录 ".$sql);
        return $rt;
    }
 
    //获取全部记录
    public function get_all($sql,$result_type = MYSQL_ASSOC) {
        $query = $this->query($sql);
        $i = 0;
        $rt = array();
        while($row =& mysql_fetch_array($query,$result_type)) {
            $rt[$i]=$row;
            $i++;
        }
        $this->write_log("获取全部记录 ".$sql);
        return $rt;
    }
     
    //插入
    public function insert($table,$dataArray) {
        $field = "";
        $value = "";
        if( !is_array($dataArray) || count($dataArray)<=0) {
            $this->halt('没有要插入的数据');
            return false;
        }
        while(list($key,$val)=each($dataArray)) {
            $field .="$key,";
            $value .="'$val',";
        }
        $field = substr( $field,0,-1);
        $value = substr( $value,0,-1);
        $sql = "insert into $table($field) values($value)";
        $this->write_log("插入 ".$sql);
        if(!$this->query($sql)) return false;
        return true;
    }
 
    //更新
    public function update( $table,$dataArray,$condition="") {
        if( !is_array($dataArray) || count($dataArray)<=0) {
            $this->halt('没有要更新的数据');
            return false;
        }
        $value = "";
        while( list($key,$val) = each($dataArray))
        $value .= "$key = '$val',";
        $value .= substr( $value,0,-1);
        $sql = "update $table set $value where 1=1 and $condition";
        $this->write_log("更新 ".$sql);
        if(!$this->query($sql)) return false;
        return true;
    }
 
    //删除
    public function delete( $table,$condition="") {
        if( empty($condition) ) {
            $this->halt('没有设置删除的条件');
            return false;
        }
        $sql = "delete from $table where 1=1 and $condition";
        $this->write_log("删除 ".$sql);
        if(!$this->query($sql)) return false;
        return true;
    }
 
    //返回结果集
    public function fetch_array($query, $result_type = MYSQL_ASSOC){
        $this->write_log("返回结果集");
        return mysql_fetch_array($query, $result_type);
    }
 
    //获取记录条数
    public function num_rows($results) {
        if(!is_bool($results)) {
            $num = mysql_num_rows($results);
            $this->write_log("获取的记录条数为".$num);
            return $num;
        } else {
            return 0;
        }
    }
 
    //释放结果集
    public function free_result() {
        $void = func_get_args();
        foreach($void as $query) {
            if(is_resource($query) && get_resource_type($query) === 'mysql result') {
                return mysql_free_result($query);
            }
        }
        $this->write_log("释放结果集");
    }
 
    //获取最后插入的id
    public function insert_id() {
        $id = mysql_insert_id($this->link_id);
        $this->write_log("最后插入的id为".$id);
        return $id;
    }
 
    //关闭数据库连接
    protected function close() {
        $this->write_log("已关闭数据库连接");
        return @mysql_close($this->link_id);
    }
 
    //错误提示
    private function halt($msg='') {
        $msg .= "\r\n".mysql_error();
        $this->write_log($msg);
        die($msg);
    }
 
    //析构函数
    public function __destruct() {
        $this->free_result();
        $use_time = ($this-> microtime_float())-($this->time);
        $this->write_log("完成整个查询任务,所用时间为".$use_time);
        if($this->is_log){
            fclose($this->handle);
        }
    }
     
    //写入日志文件
    public function write_log($msg=''){
        if($this->is_log){
            $text = date("Y-m-d H:i:s")." ".$msg."\r\n";
            fwrite($this->handle,$text);
        }
    }
     
    //获取毫秒数
    public function microtime_float() {
        list($usec, $sec) = explode(" ", microtime());
        return ((float)$usec + (float)$sec);
    }
}
 
?>

使用方法

 代码如下 复制代码

$db = new DB();
调用
$db->insert_id();//获取最新IP地址

静态化页面的好处就不说了,现在我们下文要介绍的实现方法就是利用定义的模板页面和标签然后再利用php读取模板页面之后进入分析替换就可以了,具体我们来看两个例子。

方案:使用模板替换技术(没有时间延迟)

 代码如下 复制代码

/*
|------------------
| <www.111cn.net>
|------------------
*/
$oper = $_POST['oper'];//添加操作
if($oper === 'add')
{
    $title = $_POST['title'];
    $content = $_POST['content'];
   
    //如果严格按MVC,这里应该调用model了
    $con = mysql_connect('localhost', 'root', '123456');
    if(!$con)
    {
        die('连接失败!');
    }
    mysql_select_db('news', $con);
    $sql = "insert into question(null, '$title', '$content', '')";
    if(mysql_query($sql, $con))
    {
        //1.生成静态文件
        $id = mysql_insert_id();
        $html_filename = 'news-id'.$id.'.html';
        $html_fp = fopen($html_filename, 'w');
       
        //2.把模板文件读取(news.html)
        $fp = fopen('news.tpl', 'r');
        //r 只读方式打开; r+ 读写方式打开; w 写入方式打开:文件内容将被清空!如果文件不存在将创建; a 以追加的方式打开
       
        //3.循环读取
        //如果没有读到文件的最后,就一直读取
        while(!feof($fp))
        {
            //一行行读
            $row = fgets($fp);
            //把占位符替换掉 => 可以自定义完整的替换规则函数
            $row = str_replace('%title%', $title, $row);//如果不重新赋值$row, $row值不会改变
            $row = str_replace('%content%', $content, $row);
           
            fwrite($html_fp, $row);//4.将内容写入静态文件
        }

        //5.文件必须关闭
        fclose($html_fp);
        fclose($fp);
       
        echo "添加成功。<a href='newslist.php'>点击查看新闻!</a>";
    }
    else
    {
        die('添加失败!');
    }
}
//此时在新闻列表内,点击查看详情的链接,可以改成生成的静态页面地址,直接进入静态文件。

//news.tpl模板文件
/*
<html>
    <head>
        <meta charset="utf-8" />
        <title>%title%</title>
    </head>
    <body>
        <h1>%title%</h1>
        <pre>%content%</pre>
    </body>
</html>
*/

方案:如果静态文件存在,且生成时间30秒内,直接返回静态页面(有时间延迟)

 代码如下 复制代码

/*
|------------------
| <www.111cn.net>
|------------------
*/
header('content-type:text/html;charset=utf-8');
$id = $_GET['id'] ? intval($_GET['id']) : '';
if($id === '') die('请输入要查询的新闻id!');
$html_file = "news-id-".$id.".html";

//1.主要代码
if(file_exists($html_file) && filemtime($html_file) + 30 >= time())
{
    echo '静态页面:';
    echo file_get_contents($html_file);exit;
}

//这里也可以使用DB工具类
$con = mysql_connect('localhost', 'root', '123456');
if(!$con)
{
    die('连接失败!');
}
mysql_select_db('testdb', $con);
$sql = "select * from bo_question where question_id = $id";
$res = mysql_query($sql, $con);
if($row = mysql_fetch_assoc($res))
{
    ob_start();//2.启动ob缓存
    header('content-type:text/html;charset=utf-8');
    echo '<head><meta http-equiv="content-type" content="text/html;charset=utf-8" /></head>';
    echo '<table style="border:1px solid red;" cellspacing="0" width="400px" height="200px">';
    echo '<tr><td>问题详细内容</td></tr>';
    echo "<tr><td>标题:{$row['question_title']}</td></tr>";
    echo "<tr><td>详细:{$row['question_detail']}</td></tr>";
    echo '</table>';
    $ob_str = ob_get_contents();
    //3.把ob_str保存到一个静态文件页面,取文件名有讲究:1.唯一标识该新闻 2.利于seo
    file_put_contents("news-id-".$id.".html", $ob_str);
  
  //关闭数据库连接(非必须; 非长连接下,脚本执行完会自动关闭)
  mysql_close($con);
}else{
    echo '没有查询到资源!';
}

从上面看我们头一种生成静态页面的方法更合适于页面的后期维护哦,后者是比较难维护的哦,推荐使用第一种办法。

校验码身份证计算