【PHP】开发中常用自定义小功能函数

一些可用的常用的小功能函数,依照具体的项目、业务,开发者需要自己修改定制。

一、获取可阅读的随机字符串,主要用来设置简单随机密码。

function readableRadStr($length=8) {
    $conso = array('b','c','d','f','g','h','j','k','l',
'm','n','p','r','s','t','v','w','x','y','z');
    $vocla = array('a', 'e', 'i', 'o', 'u');
    $password = '';
    for ($i = 0;$i < $length;) {
        $password .= $conso[mt_rand(0, count($conso)-1)];
        $password .= $vocla[mt_rand(0, count($vocla)-1)];
        $i += 2;
    }
    return $password;
}

二、获取客户端的真实IP。

function getRealIpAddr() {
    if ( !empty($_SERVER['HTTP_CLIENT_IP']) ) {
        $ip=$_SERVER['HTTP_CLIENT_IP'];
    } elseif ( !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
        //to check ip is pass from proxy
        $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

三、列出某个目录下的所有文件。

function listFiles($dir) {
    if ( is_dir($dir) && $handle=opendir($dir)) {
        while ( ($file = readdir($handle)) !== false ) {
            if( $file != "." && $file != ".." && $file != "Thumbs.db" ) {
                echo $dir.$file."\n";
            }
        }
        closedir($handle);
    }
}

四、递归销毁整个目录。(慎用)

function delDir($dir) {
    if ( $dir == '/' || substr($dir, 0, 5) != '/tmp/' || strlen($dir) <= strlen('/tmp/') ) {
        return false;
    }

    //先删除目录下的文件:
    $dh=opendir($dir);
    while ($file=readdir($dh)) {
        if($file!="." && $file!="..") {
            $fullpath=$dir."/".$file;
            if(!is_dir($fullpath)) {
                unlink($fullpath);
            } else {
                delDir($fullpath);
            }
        }
    }

    closedir($dh);
    //删除当前文件夹:
    if( rmdir($dir) ) {
        return true;
    } else {
        return false;
    }
}

五、PHP解析xml数据为array。

function xmlToArray($xml) {
    //禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    // $values = $this->R_IN($values); 对于特殊字符进行过滤
    return $values;
}


六、PHP检查两个字符串的相似度。

// $percent = NULL;// PHP不需要声明变量
similar_text('ligang love NI', 'ligang  love U', $percent);
echo $percent;


这个函数还是比较有用的,可以底层扩展自己改进算法再次实现。

 Levenshtein这个函数可以计算两个字符串之间的编辑距离。

七、根据身份证计算生日。

function idNoToBirth($idno) {
    $idno = trim($idno);
    if ( !preg_match("/^[0-9]*$/", $idno) ) {
        return '';
    }
    if (strlen($idno) != 15 && strlen($idno) != 18) {
        return '';
    }
    if (strlen($idno) == 18) {
        $tyear = substr($idno,6,4);
        $tmonth = substr($idno,10,2);
        $tday = substr($idno,12,2);
        return $tyear.'-'.$tmonth.'-'.$tday;
    }else {
        $tyear = '19'.substr($idno,6,2);
        $tmonth = substr($idno,8,2);
        $tday = substr($idno,10,2);
        return $tyear.'-'.$tmonth.'-'.$tday;
    }
}


八、根据生日计算年龄。

function age($date) {
    $year_diff = '';
    $time = strtotime($date);
    if ( false === $time ) {
        return '';
    }
    $date = date('Y-m-d', $time);
    list($year, $month, $day) = explode('-', $date);
    $year_diff = date('Y') - $year;
    $month_diff = date('m') - $month;
    $day_diff = date('d') - $day;
    if ( $day_diff < 0 || $month_diff < 0 ) {
        $year_diff--;
    }
    return $year_diff;
}


九、ZIP压缩。(非加密)

/* creates a compressed zip file */
function create_zip($files = array(),$destination = '',$overwrite = false) {
    //if the zip file already exists and overwrite is false, return false
    if(file_exists($destination) && !$overwrite) { 
        return false; 
    }
    $valid_files = array();
    // if files were passed in...
    if( is_array($files) ) {
        //cycle through each file
        foreach($files as $file) {
            //make sure the file exists
            if( file_exists($file) ) {
                $valid_files[] = $file;
            }
        }
    }
    // if we have good files...
    if ( count($valid_files) ) {
        //create the archive
        $zip = new ZipArchive();
        if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
            return false;
        }
        //add the files
        foreach($valid_files as $file) {
            $zip->addFile($file,$file);
        }
        $zip->close();
        //check to make sure the file exists
        return file_exists($destination);
    }   
    else {
        return false;
    }
}


十、ZIP压缩。(加密)

function packFiles($file_dir = '', $zip_pwd, $target_file) {
    $target_dir = '';// 这里是配置
    if ( !is_dir($target_dir) ) {
        mkdir($target_dir, 0777, true);
    }
    $target_path = sprintf('%s/%s', $target_dir, $target_file);
    // 如果已经存在该文件,先删除该文件
    if ( is_file($target_path) && $target_path != '/') {
        unlink($target_path);
    }
    $cmd = sprintf("zip -P %s -rj %s %s", $zip_pwd, $target_path, $file_dir);
    ob_start();// 一定要加这句话,因为下面的system会有输出到缓冲区
    $re = system($cmd);
    if ( $re == false ) {
        return false;
    }
    ob_clean();// 清除输出缓冲区


    return true;
}

十一、ZIP解压。

function unzipFile($file, $destination) {
    // create object
    $zip = new ZipArchive() ;
    // open archive
    if ($zip->open($file) !== TRUE) {
        die ('Could not open archive');
    }
    // extract contents to destination directory
    $zip->extractTo($destination);
    // close archive
    $zip->close();
    echo 'Archive extracted to directory';
}
unzipFile('myzipfile.zip','./');


十二、PHP获取随机字符串,用来生成订单号。

function createNonceStr($length=16) {
    try {
        if ($length > 32) {
            throw new LogicException("随机字符串不能大于32长度",EXCEPT_REQ);
        }
        // 微信文档说:推荐使用大小写字母和数字
        $chars = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $str = "";
        for ($i = 0;$i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    } catch (LogicException $e){
        die($e->getMessage());
    }
}


带有时间信息的订单号。

function createOrderId() {
    $pre = date('YmdHis');
    return $pre.createNonceStr(32-strlen($pre));
}


十三、关键词高亮。

function highlight($sString, $aWords) {
    if (!is_array ($aWords) || empty ($aWords) || !is_string ($sString)) {
        return false;
    }
    $sWords = implode ('|', $aWords);
    return preg_replace ('@\b('.$sWords.')\b@si', '<strong style="background-color:yellow">$1</strong>', $sString);
}
echo highlight('ligang love u,do you know this?', array('love', 'this'));

十四、各种字符串正则匹配的异常检查。
/**
     * 手机号验证
     * @param string $str
     * @return bool
     */
    static function mobile($str) {
        return preg_match("/^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/", $str);
    }
    /**
     * 固定电话(严格)
    */
    static function telephone($str) {
        return preg_match("/^(0[0-9]{2}-)?([2-9][0-9]{7})$|^(0[0-9]{3}-)?([2-9][0-9]{6})$/", $str);
    }
    /**
     * 固定电话(非严格)
    */
    static function simpletelephone($str) {
        return preg_match("/^\d{11}$/", $str);
    }
    /**
     * 顺丰快递单号
     */
    static function sfPostId($str) {
        return preg_match("/^\d{12}$/", $str);
    }
    /**
     * 下行手机验证码 6位数字
     * @param string $str
     * @return bool
     */
    static function smsCode($str) {
        return preg_match("/^\d{6}$/",$str);
    }
    /**
     * 验证邮政编码
    */
    static function postCode($str) {
        return preg_match("/^\d{6}$/",$str);
    }

    /**
     * EMAIL验证
     */
    static function email($str) {
        return preg_match("/^([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/",$str);
    }


    /**
     * QQ验证
     */
    static function qq($str) {
        return preg_match("/^[1-9]\d{4,11}$/", $str);
    }

    /**
     * 用户密码
     * @param string $str
     * @return boolean
     */
    static function passwd($str) {
        return preg_match("/^[a-zA-Z0-9]{6,20}$/", $str);
    }
    /**
     * 身份证号验证
     * @param string $str
     * @return boolean
     */
    static function idno($str) {
        return preg_match("/(^\d{15}$)|(^\d{17}(\d|X)$)/", $str);
    }
    /**
     * 检查是整形数字字符串,也就是只有数字
     */
    static function intNum($str) {
        return preg_match("/^[0-9]*$/", $str);
    }
    /**
     * 检查一个字符串只有数字+.
     */
    static function floatNum($str) {
        return preg_match("/^[0-9|.]*$/", $str);
    }
    /**
     * 对于类似订单号进行检查
     */
    static function orderStr($str) {
        return preg_match("/^[0-9|A-Z|a-z|-]*$/", $str);
    }
    /**
     * 检查是一个合法的url
     */
    static function url($str) {
        $url = $str;
        if (filter_var( $url, FILTER_VALIDATE_URL )) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 判断一个字符串是不是json
    */
    static function isJson($str) {
        return !is_null(json_decode($str));
    }


十五、计算代码的执行时间,检查2段代码的执行效率的区别,通常用来判断算法的优劣。

$length = 100000;
// 计算代码段的执行时间,以此来判断效率区别
$time_start = microtime(true);
/*
for( $i=0; $i < $length; $i++) {
    for ( $i=0;$i < $length; $i++ ) {
        ;
    }
}*/
$time_end = microtime(true);
echo $time_end - $time_start;


十六、将package中的各种参数按照key的ascii码字典顺序排列,并使用url中key-value的格式,拼接成字符串,通常用在签名验证。

function formatQueryParaMap($paraMap, $strtolowerFlag=false,$urlEncodeFlag=false) {
    if ( !is_array($paraMap) ) {
        return '';
    }
    $buff = '';
    ksort($paraMap);
    foreach ($paraMap as $k=>$v) {
        // 之所有排除sign,paysign,表示这几个字段通常就是签名结果字段,一般不参与签名
        if ($v != null && $v != 'null' && strtolower($k) != 'sign' && strtolower($k) != 'paysign') {
            // 表示是否进行urlEncode编码,一般不用
            if ( $urlEncodeFlag ) {
                $v = urlencode($v);
            }
            // 表示key是否转小写,一般情况下不用,不排除某些业务需要
            if ( $strtolowerFlag ) {
                $buff .= strtolower($k)."=".$v."&";
            } else {
                $buff .= $k.'='.$v.'&';
            }
        }
    }
    $reqPar = '';
    if (strlen($buff) > 0) {
        $reqPar = substr($buff, 0, strlen($buff) - 1);
    }
    return $reqPar;
}
$test = array(
    'order_id' => '1234123412341234',
    'money' => 'nihao a',
    'order_time' => date('Y-m-d H:i:s'),
    );
echo formatQueryParaMap($test);

十七、PHP中模拟浏览器下载文件。

/**
 * @param string $img_url 下载文件地址
 * @param string $save_path 下载文件保存目录
 * @param string $filename 下载文件保存名称
 * @return bool
 */
function curlDownFile($img_url, $save_path = '', $filename = '') {
    if (trim($img_url) == '') {
        return false;
    }
    if (trim($save_path) == '') {
        $save_path = './';
    }

    //创建保存目录
    if (!file_exists($save_path) && !mkdir($save_path, 0777, true)) {
        return false;
    }
    if (trim($filename) == '') {
        $img_ext = strrchr($img_url, '.');
        $img_exts = array('.gif', '.jpg', '.png');
        if (!in_array($img_ext, $img_exts)) {
            return false;
        }
        $filename = time() . $img_ext;
    }

    // curl下载文件
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $img_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $img = curl_exec($ch);
    curl_close($ch);

    // 保存文件到制定路径
    file_put_contents($filename, $img);

    unset($img, $url);
    return true;
}

// 执行函数之后,会在当前文件的同一目录下生成下载好的图片
curlDownFile('http://mimg.127.net/logo/163logo.gif');


在使用这个函数过程,要根据实际情况选择改变传入的参数,并根据实际的环境(windows\linux,来看看是否需要创建保存的目录)。

给出的链接只要是浏览器可以访问到的,浏览器可以下载到的图片、文件,即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值