PHPExcel导入Excel数据 不指定

jed , 2018-3-14 09:37 , 代码编程 , 评论(0) , 阅读(1653) , Via 本站原创

public function importFromExcel($excel_url)
{
    //Loader::import('phpexcel.PHPExcel');
    Loader::import('phpexcel.PHPExcel.IOFactory');
    // $phpExcel = new \PHPExcel();

    $fileExt = getExt($excel_url);
    if ($fileExt == 'xls') {
        $reader = \PHPExcel_IOFactory::createReader('Excel5');
    } else {
        $reader = \PHPExcel_IOFactory::createReader('Excel2007');
    }
    //$reader = \PHPExcel_IOFactory::createReader('Excel2007');
    //$reader = \PHPExcel_IOFactory::createReader('Excel5');
    $allSheets = $reader->load('/www/FenFa/public'.$excel_url);
    $excel_arr = $allSheets->getSheet(0)->toArray();
    array_shift($excel_arr);
    $data = [];
    foreach ($excel_arr as $k=>$v) {
        if ($v[1]) {
            $data[$k]['data_time']        = strtotime(str_replace('.', '-', $v[0]));
            $data[$k]['cooperation_id']   = $v[1];
            $data[$k]['settlement_price'] = $v[2];
            $data[$k]['settlement_ratio'] = $v[3];
            $data[$k]['settlement_num']   = $v[4];
        }
    }

    foreach ($data as $v) {
        if ($v['cooperation_id']) {
            Db::name('data')->insert($v);
        }
    }
}

php 文件原生上传函数 不指定

jed , 2018-3-14 09:29 , 代码编程 , 评论(0) , 阅读(2072) , Via 本站原创
php 文件原生上传函数

*自定义一个图片等比缩放函数
*@param string $picname 被缩放图片名
*@param string $path 被缩放图片路径
*@param int $maxWidth 图片被缩放后的最大宽度
*@param int $maxHeight 图片被缩放后的最大高度
*@param string $pre 缩放后的图片名前缀,默认为"s_"
*@return boolen 返回布尔值表示成功与否。
*/
function imageResize($picname,$path,$maxWidth,$maxHeight,$pre="s_"){
    $path = rtrim($path,"/")."/";
    //1获取被缩放的图片信息
    $info = getimagesize($path.$picname);
    //获取图片的宽和高
    $width = $info[0];
    $height = $info[1];
    
    //2根据图片类型,使用对应的函数创建画布源。
    switch($info[2]){
        case 1: //gif格式
            $srcim = imagecreatefromgif($path.$picname);
            break;
        case 2: //jpeg格式
            $srcim = imagecreatefromjpeg($path.$picname);
            break;
        case 3: //png格式
            $srcim = imagecreatefrompng($path.$picname);
            break;
       default:
            return false;
            //die("无效的图片格式");
            break;
    }
    //3. 计算缩放后的图片尺寸
    if($maxWidth/$width<$maxHeight/$height){
        $w = $maxWidth;
        $h = ($maxWidth/$width)*$height;
    }else{
        $w = ($maxHeight/$height)*$width;
        $h = $maxHeight;
    }
    //4. 创建目标画布
    $dstim = imagecreatetruecolor($w,$h);

    //5. 开始绘画(进行图片缩放)
    imagecopyresampled($dstim,$srcim,0,0,0,0,$w,$h,$width,$height);

    //6. 输出图像另存为
    switch($info[2]){
        case 1: //gif格式
            imagegif($dstim,$path.$pre.$picname);
            break;
        case 2: //jpeg格式
            imagejpeg($dstim,$path.$pre.$picname);
            break;
        case 3: //png格式
            imagepng($dstim,$path.$pre.$picname);
            break;
    }
  }

PHP批量转换文件编码为utf-8 不指定

jed , 2018-3-14 09:26 , 代码编程 , 评论(0) , 阅读(1409) , Via 本站原创

使用时向 read_dir 函数传入路径和要转换到的编码, 默认utf-8

比如传入这个路径,则函数会将WWW文件夹下所有的编码转换为utf-8:
read_dir("D:\WEB\phpStudy\PHPTutorial\WWW");

php常用正则验证 不指定

jed , 2018-3-14 09:23 , 代码编程 , 评论(0) , 阅读(2313) , Via 本站原创

//正则验证手机号 正确返回 true
function preg_mobile($mobile) {
  if(preg_match("/^1[34578]\d{9}$/", $mobile)) {
    return TRUE;
  } else {
    return FALSE;
  }
}
//验证电话号码
function preg_tel($tel) {
  if(preg_match("/^(\(\d{3,4}\)|\d{3,4}-)?\d{7,8}$/", $tel)) {
    return TRUE;
  } else {
    return FALSE;
  }
}
//验证身份证号(15位或18位数字)
function preg_idcard($idcard) {
  if(preg_match("/^\d{15}|\d{18}$/", $idcard)) {
    return TRUE;
  } else {
    return FALSE;
  }
}
//验证是否是数字(这里小数点会认为是字符)
function preg_digit($digit) {
  if(preg_match("/^\d*$/", $digit)) {
    return TRUE;
  } else {
    return FALSE;
  }
}
//验证是否是数字(可带小数点的数字)
function preg_num($num) {
  if(is_numeric($num)) {
    return TRUE;
  } else {
    return FALSE;
  }
}
//验证由数字、26个英文字母或者下划线组成的字符串
function preg_str($str) {
  if(preg_match("/^\w+$/", $str)) {
    return TRUE;
  } else {
    return FALSE;
  }
}
//验证用户密码(以字母开头,长度在6-18之间,只能包含字符、数字和下划线)
function preg_password($str) {
  if(preg_match("/^[a-zA-Z]\w{5,17}$/", $str)) {
    return TRUE;
  } else {
    return FALSE;
  }
}
//验证汉字
function preg_chinese($str) {
  if(preg_match("/^[\u4e00-\u9fa5],{0,}$/", $str)) {
    return TRUE;
  } else {
    return FALSE;
  }
}
//验证Email地址
function preg_email($email) {
  if(preg_match("/^\w+[-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/", $email)) {
    return TRUE;
  } else {
    return FALSE;
  }
}
//验证网址URL
function preg_link($url) {
  if(preg_match("/http:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is", $url)) {
    return TRUE;
  } else {
    return FALSE;
  }
}
//腾讯QQ号
function preg_qq($qq) {
  if(preg_match("/^[1-9][0-9]{4,}$/", $qq)) {
    return TRUE;
  } else {
    return FALSE;
  }
}
//验证中国邮政编码 6位数字
function preg_post($post) {
  if(preg_match("/^[1-9]\d{5}(?!\d)$/", $post)) {
    return TRUE;
  } else {
    return FALSE;
  }
}
//验证IP地址
function preg_ip($ip) {
  if(preg_match("/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/", $ip)) {
    return TRUE;
  } else {
    return FALSE;
  }
}

MYSQL 批量修改表前缀 不指定

jed , 2018-3-14 09:22 , 数据库技术 , 评论(0) , 阅读(1416) , Via 本站原创

<?php
/*
* MYSQL 批量修改表前缀
*/
error_reporting(0);
$old_pre = 'tdr_'; // 原表前缀
$new_pre = 'db_'; // 新表前缀
// 配置连接
$db = new mysqli('127.0.0.1', 'db_user', 'db_pass', 'db_name');
if ($db->connect_error) die('Connect Error (' . $db->connect_errno . ') ' . $db->connect_error);

$query = $db->query('SHOW TABLES;');
$list = $query->fetch_all();
echo 'table : ', count($list),'<hr>';

$len = strlen($old_pre);
foreach ($list as $val) {
    $new_name = $new_pre.substr($val[0], $len, strlen($val[0])-$len);
    echo "ALTER TABLE {$val[0]} RENAME {$new_name};<br />";
    $db->query("ALTER TABLE {$val[0]} RENAME {$new_name};");
}
echo '<hr>success.';

$db->close();
?>

PHP常用代码片段 不指定

jed , 2018-3-14 09:20 , 代码编程 , 评论(0) , 阅读(1617) , Via 本站原创

/**
* 高效判断远程文件是否存在
* @param $file
* @return bool 存在返回 true 不存在或者其他原因返回false
*/
function remoteFileExist($file)
{
    if(preg_match('/^http:\/\//',$file)){
        //远程文件
        if(ini_get('allow_url_fopen')){
            if(@fopen($file,'r')) return true;
        }
        else{
            $parseurl=parse_url($file);
            $host=$parseurl['host'];
            $path=$parseurl['path'];
            $fp=fsockopen($host,80, $errno, $errstr, 10);
            if(!$fp)return false;
            fputs($fp,"GET {$path} HTTP/1.1 \r\nhost:{$host}\r\n\r\n");
            if(preg_match('/HTTP\/1.1 200/',fgets($fp,1024))) return true;
        }
        return false;
    }
    return file_exists($file);
}

/**
* 对象obj 转数组array
* @param $object
* @return mixed
*/
function object2array(&$object) {
    $object =  json_decode( json_encode( $object),true);
    return  $object;
}

/**
* @param 字节大小 $size
* @param 保留小数位数 $dec
* 格式化文件大小
*/
function file_size($size, $dec=2) {
  $a = array("B", "KB", "MB", "GB", "TB", "PB");
  $pos = 0;
  while ($size >= 1024) {
     $size /= 1024;
       $pos++;
  }
  return round($size,$dec)." ".$a[$pos];
}

/**
* 隐藏手机号中间4位
* @param $phone
* @return mixed
*/
function hidetel($phone){
    $IsWhat = preg_match('/(0[0-9]{2,3}[-]?[2-9][0-9]{6,7}[-]?[0-9]?)/i',$phone);
    if($IsWhat == 1){
        return preg_replace('/(0[0-9]{2,3}[-]?[2-9])[0-9]{3,4}([0-9]{3}[-]?[0-9]?)/i','$1****$2',$phone);
    }else{
        return  preg_replace('/(1[3587]{1}[0-9])[0-9]{4}([0-9]{4})/i','$1****$2',$phone);
    }
}

/**
* 时间格式化
* @param $time
* @return string
*/
function formatTime($time) {
    $now_time = time();
    $t = $now_time - $time;
    $mon = (int) ($t / (86400 * 30));
    if ($mon >= 1) {
        return '一个月前';
    }
    $day = (int) ($t / 86400);
    if ($day >= 1) {
        return $day . '天前';
    }
    $h = (int) ($t / 3600);
    if ($h >= 1) {
        return $h . '小时前';
    }
    $min = (int) ($t / 60);
    if ($min >= 1) {
        return $min . '分钟前';
    }
    return '刚刚';
}

/**
* 时间格式化
* @param $time
* @return string
*/
function pincheTime($time) {
     $today  =  strtotime(date('Y-m-d')); //今天零点
      $here   =  (int)(($time - $today)/86400) ;
      if($here==1){
          return '明天';  
      }
      if($here==2) {
          return '后天';  
      }
      if($here>=3 && $here<7){
          return $here.'天后';  
      }
      if($here>=7 && $here<30){
          return '一周后';  
      }
      if($here>=30 && $here<365){
          return '一个月后';  
      }
      if($here>=365){
          $r = (int)($here/365).'年后';
          return   $r;
      }
     return '今天';
}

/**
*
* @param 时间戳 $time
* 友好时间显示
* @return
*/
function timeline($time){
    if(time()<=$time){
    return date("Y-m-d H:i:s",$time);
    }else{
    $t = time()-$time;  
    $f = array(  
        '31536000'=>'年',  
        '2592000'=>'个月',  
        '604800'=>'星期',  
        '86400'=>'天',  
        '3600'=>'小时',  
        '60'=>'分钟',  
        '1'=>'秒'  
    );  
    foreach($f as $k=>$v){  
        if(0 != $c = floor($t/(int)$k)){  
            return $c.$v.'前';  
        }  
    }
    }
}

/**
* 计算两个时间的时差
* @param $begin_time
* @param $end_time
* @return array
*/
function timeDiff($begin_time, $end_time) {
    if ($begin_time < $end_time) {
        $starttime = $begin_time;
        $endtime = $end_time;
    } else {
        $starttime = $end_time;
        $endtime = $begin_time;
    }
    $timediff = $endtime - $starttime;
    $days = intval( $timediff / 86400 );
    $remain = $timediff % 86400;
    $hours = sprintf("%02d", intval( $remain / 3600 ));
    $remain = $remain % 3600;
    $mins = sprintf("%02d", intval( $remain / 60 ));
    $secs = sprintf("%02d",$remain % 60);
    $res = array( "day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs );
    return $res;
}

/**
* 获取当前毫秒时间戳
* @return string
*/
function getMillisecond() {
    list($t1, $t2) = explode(' ', microtime());
    return $t2 .  ceil( ($t1 * 1000) );
}

/**
* 生成n位随机数
* @param int $length
* @return string
*/
function createRandomKey($length=32) {
    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    $str ="";
    for ( $i = 0; $i < $length; $i++ )  {
        $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
    }
    return $str;
}

/**
* 生成n位包含$string的随机数
* @param int $length
* @param string $str
* @return string
*/
function createRandomStringKey($length=32, $chars = "abcdefghijklmnopqrstuvwxyz0123456789") {
    $str ="";
    for ( $i = 0; $i < $length; $i++ )  {
        $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
    }
    return $str;
}

/**
* post的curl 兼容https
* @param $url
* @param $data
* @return mixed
*/
function curlPostForHttps($url, $data) {

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        "Content-Type: application/json", "Content-Length: ".strlen($data)));
    $result = json_decode(curl_exec($curl), true);
    curl_close($curl);

    return $result;

}

/**
* 16进制颜色值转 rgb
* @param $colour
* @return array|bool
*/
function hex2rgb( $colour ) {
    if ( $colour[0] == '#' ) {
        $colour = substr( $colour, 1 );
    }
    if ( strlen( $colour ) == 6 ) {
        list( $r, $g, $b ) = array( $colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5] );
    } elseif ( strlen( $colour ) == 3 ) {
        list( $r, $g, $b ) = array( $colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2] );
    } else {
        return false;
    }
    $r = hexdec( $r );
    $g = hexdec( $g );
    $b = hexdec( $b );
    return array( 'red' => $r, 'green' => $g, 'blue' => $b );
}

/**
* 系统邮件发送函数
* @param $address 收件人邮件
* @param $title    邮件标题
* @param $message  邮件内容
* @return bool
*/
function sendMail($address,$title,$message, $filePath=null) {
    $mail = new PHPMailer();
    // 设置PHPMailer使用SMTP服务器发送Email
    $mail->IsSMTP();
    // 设置邮件的字符编码,若不指定,则为'UTF-8'
    $mail->CharSet='UTF-8';
    // 添加收件人地址,可以多次使用来添加多个收件人
    $mail->AddAddress($address);
    // SMTP调试功能 0=关闭 1 = 错误和消息 2 = 消息
    $mail->SMTPDebug = 0;
    // 设置邮件正文
    $mail->Body=$message;
    // 设置邮件头的From字段。
    $mail->From=config('mail.from');
    // 设置发件人名字
    $mail->FromName=config('mail.fromName');
    // 设置邮件标题
    $mail->Subject=$title;
    // 设置SMTP服务器。
    $mail->Host=config('mail.host');
    // SMTP服务器的端口号
    $mail->Port = config('mail.port');
    // 设置为"需要验证"
    $mail->SMTPAuth=true;
    // 启用SSL加密为true
    $mail->SMTPSecure =true;

    // 添加附件
    if ($filePath != null) {
        $mail->AddAttachment($filePath);
    }
    // 设置用户名和密码。
    $mail->Username=config('mail.username');
    $mail->Password=config('mail.password');
    // 发送邮件。
    return($mail->Send());
}

/**
* 指定位置插入字符串
* @param $str  原字符串
* @param $i    插入位置
* @param $substr 插入字符串
* @return string 处理后的字符串
*/
function insertToStr($str, $i, $substr){
    //指定插入位置前的字符串
    $startstr="";
    for($j=0; $j<$i; $j++){
        $startstr .= $str[$j];
    }

    //指定插入位置后的字符串
    $laststr="";
    for ($j=$i; $j<strlen($str); $j++){
        $laststr .= $str[$j];
    }

    //将插入位置前,要插入的,插入位置后三个字符串拼接起来
    $str = $startstr . $substr . $laststr;

    //返回结果
    return $str;
}

/**
* 阿拉伯数字转中文数字
* @param $num
* @return string
*/
function ToChinaseNum($num)
{
    $char = array("零","一","二","三","四","五","六","七","八","九");
    $dw = array("","十","百","千","万","亿","兆");
    $retval = "";
    $proZero = false;
    for($i = 0;$i < strlen($num);$i++)
    {
        if($i > 0)    $temp = (int)(($num % pow (10,$i+1)) / pow (10,$i));
        else $temp = (int)($num % pow (10,1));

        if($proZero == true && $temp == 0) continue;

        if($temp == 0) $proZero = true;
        else $proZero = false;

        if($proZero)
        {
            if($retval == "") continue;
            $retval = $char[$temp].$retval;
        }
        else $retval = $char[$temp].$dw[$i].$retval;
    }
    if($retval == "一十") $retval = "十";
    return $retval;
}

PHP开启错误提示 不指定

jed , 2018-3-14 09:13 , 代码编程 , 评论(0) , 阅读(1755) , Via 本站原创

ini_set('display_errors','On');

error_reporting(E_ALL);

PHP实现区块链技术(转载) 不指定

jed , 2018-3-14 09:01 , 代码编程 , 评论(0) , 阅读(1655) , Via 本站原创

<?php
/**
* 区块链相关算法
*/
class Block
{
    
    public $timestamp; //时间
  
    public $index; //索引
    
    public $data; //数据

    public $prevHash; //上一个哈希值
    
    public $hash; //当前哈希值

    public function __construct($index, $timestamp, $data, $prevHash = '')
    {
        $this->index = $index;
        $this->timestamp = $timestamp;
        $this->data = $data;
        $this->prevHash = $prevHash;
        $this->hash = $this->calculateHash();
    }
    /**
     * 加密算法
     * @return string
     */
    public function calculateHash()
    {
        return hash('sha256', $this->index . $this->prevHash . $this->timestamp . json_encode($this->data));
    }
}
/**
* 区块链
* Class BlockChain
*/
class BlockChain
{

    public $chain = []; // Block[]

    public function __construct()
    {
        $this->chain = [$this->createGenesisBlock()];
    }
    /**
     * 创世区块
     * @return Block
     */
    public function createGenesisBlock()
    {
        return new Block(0, '2017-01-23', 'forecho', '0');
    }
    /**
     * 获取最新的区块
     * @return Block|mixed
     */
    public function getLatestBlock()
    {
        return $this->chain[count($this->chain) - 1];
    }
    /**
     * 添加区块
     * @param Block $newBlock
     */
    public function addBlock(Block $newBlock)
    {
        $newBlock->prevHash = $this->getLatestBlock()->hash;
        $newBlock->hash = $newBlock->calculateHash();
        array_push($this->chain, $newBlock);
    }
    /**
     * 验证区块链
     * @return bool
     */
    public function isChainValid()
    {
        for ($i = 1; $i < count($this->chain); $i++) {
            $currentBlock = $this->chain[$i];
            $prevBlock = $this->chain[$i - 1];
            if ($currentBlock->hash !== $currentBlock->calculateHash()) {
                return false;
            }
            if ($currentBlock->prevHash !== $prevBlock->hash) {
                return false;
            }
        }
        return true;
    }
}
// test
$blockChain = new BlockChain();
$blockChain->addBlock(new Block(1, '2017-02-23', ['amount' => 1]));
$blockChain->addBlock(new Block(2, '2017-03-23', ['amount' => 3]));
$blockChain->addBlock(new Block(3, '2017-04-23', ['amount' => 20]));
print_r($blockChain);
echo "区块链验证通过吗?" . ($blockChain->isChainValid() ? '通过' : '失败') . PHP_EOL;
$blockChain->chain[1]->data = ['amount' => 2];
$blockChain->chain[1]->hash = $blockChain->chain[1]->calculateHash();
echo "区块链验证通过吗?" . ($blockChain->isChainValid() ? '通过' : '失败') . PHP_EOL;

分页: 4/6 第一页 上页 1 2 3 4 5 6 下页 最后页 [ 显示模式: 摘要 | 列表 ]